Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(daemon): atomic agent-driver cutover (#504)

Gustavo Yecf9f0318e835
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 085f384bd..7ee326f2b 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -4,7 +4,7 @@
# CI/CD workflows require review
.github/ @alookai/core-dev
-# Published agent-driver API entry points and their golden reports
+# Private workspace agent-driver API entry points and their golden reports
/src/daemon/agent-driver/etc/api/ @alookai/core-dev
/src/daemon/agent-driver/src/index.ts @alookai/core-dev
/src/daemon/agent-driver/src/host.ts @alookai/core-dev
diff --git a/.github/workflows/api-surface-check.yml b/.github/workflows/api-surface-check.yml
new file mode 100644
index 000000000..a429d95cc
--- /dev/null
+++ b/.github/workflows/api-surface-check.yml
@@ -0,0 +1,27 @@
+name: API Surface Check
+
+on:
+ pull_request:
+ branches: [main]
+
+permissions:
+ contents: read
+
+concurrency:
+ group: api-check-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
+jobs:
+ api-check:
+ name: API Report Check
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
+ with:
+ node-version: 22
+ cache: pnpm
+ - run: pnpm install --frozen-lockfile
+ - run: pnpm api:check
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c4911c745..a6ea4b7bb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -109,6 +109,7 @@ jobs:
TURBO_SCM_HEAD: ${{ needs.scope.outputs.head_sha }}
run: pnpm turbo run lint --affected
- run: pnpm typegrep:ws
+ - run: pnpm typegrep:agent-driver
knip:
name: Dead Code Detection (knip)
@@ -215,27 +216,41 @@ jobs:
restore-keys: |
turbo-${{ runner.os }}-${{ runner.arch }}-${{ github.job }}-
- run: pnpm install --frozen-lockfile
+ - name: Run Windows process authority fixtures
+ run: pnpm --filter @alook/agent-driver exec vitest run src/internal/killTree.test.ts
+ - name: Run agent-driver tests in isolation
+ run: pnpm --filter @alook/agent-driver exec vitest run --no-file-parallelism --coverage --coverage.reporter=json --coverage.reporter=text
+ - name: Upload Windows agent-driver coverage
+ uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7
+ with:
+ token: ${{ secrets.CODECOV_TOKEN }}
+ files: ./src/daemon/agent-driver/coverage/coverage-final.json
+ disable_search: true
+ fail_ci_if_error: true
+ name: windows-agent-driver
+ - name: Run Windows daemon admission fixture
+ run: |
+ pnpm --filter @alook/agent-driver build
+ pnpm --filter @alook/daemon exec vitest run src/daemon/createDaemon.test.ts -t "starts the builtin Codex lane from a fresh nested daemon workspace"
- name: Run daemon tests in isolation
if: needs.scope.outputs.full == 'true'
env:
VITEST_MAX_WORKERS: 1
- run: pnpm turbo run test --filter=@alook/daemon
+ run: pnpm --filter @alook/daemon test
- name: Run affected daemon tests in isolation
if: needs.scope.outputs.full != 'true'
env:
VITEST_MAX_WORKERS: 1
- TURBO_SCM_BASE: ${{ needs.scope.outputs.base_sha }}
- TURBO_SCM_HEAD: ${{ needs.scope.outputs.head_sha }}
- run: pnpm turbo run test --affected --filter=@alook/daemon
+ run: pnpm --filter @alook/daemon test
- name: Run remaining workspace tests
if: needs.scope.outputs.full == 'true'
- run: pnpm turbo run test --filter='!@alook/daemon'
+ run: pnpm turbo run test --filter='!@alook/daemon' --filter='!@alook/agent-driver'
- name: Run affected workspace tests
if: needs.scope.outputs.full != 'true'
env:
TURBO_SCM_BASE: ${{ needs.scope.outputs.base_sha }}
TURBO_SCM_HEAD: ${{ needs.scope.outputs.head_sha }}
- run: pnpm turbo run test --affected --filter='!@alook/daemon'
+ run: pnpm turbo run test --affected --filter='!@alook/daemon' --filter='!@alook/agent-driver'
- name: Run CI script tests
run: pnpm vitest run --project ci-scripts
@@ -345,6 +360,7 @@ jobs:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
+ - run: pnpm --filter @alook/agent-driver build
- run: pnpm vitest run --coverage --coverage.reporter=json --coverage.reporter=text
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7
with:
diff --git a/.github/workflows/publish-daemon.yml b/.github/workflows/publish-daemon.yml
index d59780fc0..cb8e8f7d8 100644
--- a/.github/workflows/publish-daemon.yml
+++ b/.github/workflows/publish-daemon.yml
@@ -60,6 +60,10 @@ jobs:
- run: pnpm install --frozen-lockfile
if: steps.check.outputs.skip == 'false'
+ - name: Build bundled agent driver
+ if: steps.check.outputs.skip == 'false'
+ run: pnpm -C src/daemon/agent-driver run build
+
- name: Build daemon bundle
if: steps.check.outputs.skip == 'false'
run: pnpm -C src/daemon run build
diff --git a/package.json b/package.json
index 2e9b053c2..c2ae39601 100644
--- a/package.json
+++ b/package.json
@@ -7,8 +7,8 @@
"test": "turbo run test && vitest run --project ci-scripts",
"predev": "[ -f src/web/.dev.vars ] || (cp src/web/.dev.vars.example src/web/.dev.vars && sed -i '' \"s|^BETTER_AUTH_SECRET=$|BETTER_AUTH_SECRET=$(openssl rand -base64 32)|\" src/web/.dev.vars && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$(openssl rand -base64 32)|\" src/web/.dev.vars && echo '✓ Generated src/web/.dev.vars (fill in OAuth keys if needed)'); [ -f src/email-worker/.dev.vars ] || (cp src/email-worker/.dev.vars.example src/email-worker/.dev.vars && KEY=$(grep '^ENCRYPTION_KEY=' src/web/.dev.vars | cut -d= -f2-) && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$KEY|\" src/email-worker/.dev.vars && echo '✓ Generated src/email-worker/.dev.vars (synced ENCRYPTION_KEY from web)')",
"dev": "turbo run dev --filter=@alook/web --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/wake-worker --filter=@alook/shared",
- "clean": "rm -rf node_modules src/*/node_modules src/*/dist src/*/.turbo .turbo src/web/.next src/web/.open-next src/*/.wrangler .alook",
- "clean:builds": "rm -rf src/*/dist src/web/.next src/web/.open-next .turbo src/*/.turbo",
+ "clean": "rm -rf node_modules src/*/node_modules src/*/dist src/*/.turbo src/daemon/agent-driver/node_modules src/daemon/agent-driver/dist src/daemon/agent-driver/.turbo .turbo src/web/.next src/web/.open-next src/*/.wrangler .alook",
+ "clean:builds": "rm -rf src/*/dist src/daemon/agent-driver/dist src/web/.next src/web/.open-next .turbo src/*/.turbo src/daemon/agent-driver/.turbo",
"reinstall": "pnpm run clean && pnpm install",
"typecheck": "turbo run typecheck",
"lint": "turbo run lint",
@@ -40,12 +40,15 @@
"db:migrate:remote": "pnpm --filter @alook/web exec wrangler d1 migrations apply alook-app --remote",
"bump": "node scripts/bump-version.mjs",
"typegrep:ws": "node scripts/lint-ws-events.mjs",
+ "typegrep:agent-driver": "node scripts/check-agent-driver-boundaries.mjs",
+ "api:check": "pnpm --filter @alook/agent-driver api:check",
+ "api:update": "pnpm --filter @alook/agent-driver api:update",
"logo:generate": "node scripts/generate-logo-assets.mjs",
"readme:capture": "node src/web/readme-capture/capture.mjs",
"prepare": "simple-git-hooks"
},
"simple-git-hooks": {
- "pre-commit": "pnpm typecheck && pnpm lint && pnpm test && pnpm typegrep:ws && pnpm knip"
+ "pre-commit": "pnpm typecheck && pnpm lint && pnpm test && pnpm typegrep:ws && pnpm typegrep:agent-driver && pnpm knip"
},
"devDependencies": {
"@vitest/coverage-v8": "^4.1.10",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2a294e5c8..7bece65c4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -121,6 +121,9 @@ importers:
specifier: ^8.21.3
version: 8.21.3
devDependencies:
+ '@alook/agent-driver':
+ specifier: workspace:*
+ version: link:agent-driver
'@alook/shared':
specifier: workspace:*
version: link:../shared
@@ -146,6 +149,30 @@ importers:
specifier: ^4.1.10
+ src/daemon/agent-driver:
+ devDependencies:
+ '@microsoft/api-extractor':
+ specifier: ^7.58.13
+ version: 7.58.13(@types/[email protected])
+ '@types/node':
+ specifier: ^20.0.0
+ version: 20.19.43
+ eslint:
+ specifier: ^9.39.5
+ version: 9.39.5([email protected])
+ knip:
+ specifier: ^5.85.0
+ version: 5.88.1(@types/[email protected])([email protected])
+ typescript:
+ specifier: ^6.0.3
+ version: 6.0.3
+ typescript-eslint:
+ specifier: ^8.67.0
+ vitest:
+ specifier: ^4.1.10
+
src/desktop:
devDependencies:
'@tauri-apps/cli':
@@ -2280,6 +2307,21 @@ packages:
'@mermaid-js/[email protected]':
resolution: {integrity: sha512-gxK9ZX2+Fex5zu8LhRQoMeMPEHbc73UKZ0FQ54YrQtUxE1VVhMwzeNtKRPAu5aXks4FasbMe4xB4bWrmq6Jlxw==}
+ '@microsoft/[email protected]':
+ resolution: {integrity: sha512-iDu1AtuRC2Z8XVs2SieZieVavF1FXPBX1C9pMexJh8Dx/Dd/3ZZ4nRQp/PU2Vk2rUHWuBz1wOyL4DcuhVnBXwg==}
+ engines: {node: '>=20.9.0'}
+
+ '@microsoft/[email protected]':
+ resolution: {integrity: sha512-htjkWdR+ovlBiQuBbMutIuiu/dzKYpFrBRRuHGlpo7J81cPzmMTBKxE8j+aWSs5HxvXHCvatVe4vQ9CKqSvZaA==}
+ engines: {node: '>=20.9.0'}
+ hasBin: true
+
+ '@microsoft/[email protected]':
+ resolution: {integrity: sha512-9brPoVdfN9k9g0dcWkFeA7IH9bbcttzDJlXvkf8b2OBzd5MueR1V2wkKBL0abn0otvmkHJC6aapBOTJDDeMCZg==}
+
+ '@microsoft/[email protected]':
+ resolution: {integrity: sha512-xgAyonlVVS+q7Vc7qLW0UrJU7rSFcETRWsqdXZtjzRU8dF+6CkozTK4V4y1LwOX7j8r/vHphjDeMeGI4tNGeGA==}
+
'@modelcontextprotocol/[email protected]':
resolution: {integrity: sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==}
engines: {node: '>=18'}
@@ -2888,8 +2930,8 @@ packages:
engines: {node: '>=18'}
hasBin: true
- '@react-grab/[email protected]':
- resolution: {integrity: sha512-Px/Hwhhyk2PubCA4ZaRFsfvwxhbxXsetJyvqC6aFFi8WhJhA+oVC33aTzuAeWmM3fhb4/8ce8YsHXI1d6ChcKg==}
+ '@react-grab/[email protected]':
+ resolution: {integrity: sha512-LVfA+j5cFT0Szd958WRD8W/B8ucCtz4ViiveDKWLqAwBkZFW9VRW1ZvwOUhp/M3SmVPtjDaRkW12GvAuTArP+Q==}
hasBin: true
'@rolldown/[email protected]':
@@ -3002,6 +3044,39 @@ packages:
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
+ '@rushstack/[email protected]':
+ resolution: {integrity: sha512-g/Z47ZwARn/VkTnHcyJslrR26erRf1G5JbqPlfGZGBCrOcrEt8fTQXXDVhUDDNl/g/v3TXI1dNiAAT5FEks8BA==}
+ engines: {node: '>=20.9.0'}
+ peerDependencies:
+ '@types/node': '*'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@rushstack/[email protected]':
+ resolution: {integrity: sha512-gulfhBs6n+I5b7DvjKRfhMGyUejtSgOHTclF/eONr8hcgF1APEDjhxIsfdUYYMzC3rvLwGluqLjbwCFZ8nxrog==}
+ peerDependencies:
+ '@types/node': '*'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@rushstack/[email protected]':
+ resolution: {integrity: sha512-aAA518n6wxxjCfnTAOjQnm7ngNE0FVHxHAw2pxKlIhxrMn0XQjGcXKF0oKWpjBgJOmsaJpVob/v+zr3zxgPWuA==}
+
+ '@rushstack/[email protected]':
+ resolution: {integrity: sha512-KxphDhPGC4xDrKg8O4yrWCEpPMi87aJc1iycXqMVh1dLgV0M34hiH9ZTgWjBRmcrT/OIHoOeWf48npcQFzgp+g==}
+ engines: {node: '>=20.9.0'}
+ peerDependencies:
+ '@types/node': '*'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@rushstack/[email protected]':
+ resolution: {integrity: sha512-+jNbxhh8CkrZYxMk9X3GRYM2+Myr1xCCj+eHbJ9Vp+PCdNHS0TUl5QQFT6UbM/aTFRCzs5jiBTKYzBRpe5uYbQ==}
+ engines: {node: '>=20.9.0'}
+
'@sec-ant/[email protected]':
resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==}
@@ -3726,6 +3801,9 @@ packages:
resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ebDJ9b0e702Yr7pWgB0jzm+CX4Srzz8RcXtLJDJB+BSccqMa36uyH/zUsSYao5+BD1ytv3k3rPYCq4mAE1hsXA==}
+
resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}
@@ -4200,6 +4278,14 @@ packages:
resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==}
engines: {node: '>= 8.0.0'}
+ resolution: {integrity: sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==}
+ peerDependencies:
+ ajv: ^8.5.0
+ peerDependenciesMeta:
+ ajv:
+ optional: true
+
resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==}
peerDependencies:
@@ -4219,6 +4305,9 @@ packages:
resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==}
+ resolution: {integrity: sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==}
+
resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}
@@ -5838,6 +5927,10 @@ packages:
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
+ resolution: {integrity: sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==}
+ engines: {node: '>=14.14'}
+
resolution: {integrity: sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==}
engines: {node: '>=14.14'}
@@ -6160,6 +6253,10 @@ packages:
resolution: {integrity: sha512-AiohS3H80sXO6owEltjGX+glb7qXaDhBoJb9XcQVH4UI207xu/bDLUcadVKp7Qe576reg9yr/PXZjV5qx8gfbA==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-rKtvo6a868b5Hu3heneU+L4yEQ4jYKLtjpnPeUdK7h0yzXGmyBTypknlkCvHFBqfX9YlorEiMM6Dnq/5atfHkw==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
engines: {node: '>=0.8.19'}
@@ -6452,6 +6549,9 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
+ resolution: {integrity: sha512-8wb9Yw966OSxApiCt0K3yNJL8pnNeIv+OEq2YMidz4FKP6nonSRoOXc80iXY4JaN2FC11B9qsNmDsm+ZOfMROA==}
+
resolution: {integrity: sha512-XrchZOFZUl/T3vTwRe8XK+cJrGtMF4th1ARnDfwbBXFKThGhlsxEE4Zu03AD/bjJSt/9jT/mxrOCkJWOg77aPA==}
@@ -6547,6 +6647,14 @@ packages:
resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-tpy5o7zu1MjawVkLPuahymVJekYY3kYjvzcoInhIchgePxTlo+api90tBv2KfhAIe5uXh+mez1tAfmbv8/TiZg==}
+ engines: {node: '>=18.18.0'}
+ hasBin: true
+ peerDependencies:
+ '@types/node': '>=18'
+ typescript: '>=5.0.4 <7'
+
resolution: {integrity: sha512-WXTXbmocrw7gqm1A1TQvFN0OgJ7hUSU6E1g6SPRIzzHFogUBhXByc7cYeOFVtJ2uODg7DP4VbESYBYnfbtBYsg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -7129,6 +7237,10 @@ packages:
resolution: {integrity: sha512-sypXsD5fjY88fZNedPqnwrwR1dwfnfbfW7MfvMyIfPJdtRiCCOpUnjWGeFVYYZ+0fQVICye6Juu+vZgzTEx8XA==}
engines: {node: '>=22.0.0'}
+ resolution: {integrity: sha512-Rwi3pnapEqirPSbWbrZaa6N3nmqq4Xer/2XooiOKyV3q12ML06f7MOuc5DVH8ONZIFhwIYQ3yzPH4nt7iWHaTg==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
@@ -7792,8 +7904,8 @@ packages:
react: '>=16.4.0'
react-dom: '>=16.4.0'
- resolution: {integrity: sha512-zRkHKq/8a1msCpEOp8BDROeQZT50m0OH2XPrP6jk5op+JAHrlsm3pj7eAQMOsct87EZDeGNnu4r+sGsJJzyw1Q==}
+ resolution: {integrity: sha512-ohhsfXD4qN0j6cMQd56aaVJBPDF3kUdviF/Od1Eak/rEIXQ3svQ4gjkwTfuTZwTBnxHRL16p9JqdlVQO5nUHqA==}
hasBin: true
peerDependencies:
react: '>=17.0.0'
@@ -7974,6 +8086,11 @@ packages:
resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==}
+ resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==}
+ engines: {node: '>= 0.4'}
+ hasBin: true
+
resolution: {integrity: sha512-tqt+NBWwyaMgw3zDsnygx4CByWjQEJHOPMdslYhppaQSJUtL/D4JO9CcBBlhPoI8lz9oJIDXkwXfhF4aWqP8xQ==}
engines: {node: '>= 0.4'}
@@ -8079,6 +8196,11 @@ packages:
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
hasBin: true
+ resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==}
+ engines: {node: '>=10'}
+ hasBin: true
+
resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}
engines: {node: '>=10'}
@@ -8282,6 +8404,10 @@ packages:
resolution: {integrity: sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==}
+ resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==}
+ engines: {node: '>=0.6.19'}
+
resolution: {integrity: sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==}
engines: {node: '>=4'}
@@ -8411,6 +8537,10 @@ packages:
resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
@@ -8649,6 +8779,10 @@ packages:
resolution: {integrity: sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-X2wH19RAPZE3+ldGicOkoj/SIA83OIxcJ6Cuaw23hf8Xc6fQpvZXY0SftE2JgS0QhYLUG4uwodSI3R53keyh7w==}
+ engines: {node: '>=14'}
+
resolution: {integrity: sha512-b7zoBQvpWp0vuN5q2vK2RRBR2SvuruQAs50DApdDveBSn3eSYd84IaHodFqQIMlvY9K2VnyBUEXgwOBuGU9GBg==}
engines: {node: '>=14'}
@@ -11015,6 +11149,41 @@ snapshots:
dependencies:
langium: 4.2.2
+ '@microsoft/[email protected](@types/[email protected])':
+ dependencies:
+ '@microsoft/tsdoc': 0.16.0
+ '@microsoft/tsdoc-config': 0.18.1
+ '@rushstack/node-core-library': 5.24.0(@types/[email protected])
+ transitivePeerDependencies:
+ - '@types/node'
+
+ '@microsoft/[email protected](@types/[email protected])':
+ dependencies:
+ '@microsoft/api-extractor-model': 7.33.11(@types/[email protected])
+ '@microsoft/tsdoc': 0.16.0
+ '@microsoft/tsdoc-config': 0.18.1
+ '@rushstack/node-core-library': 5.24.0(@types/[email protected])
+ '@rushstack/rig-package': 0.7.3
+ '@rushstack/terminal': 0.24.3(@types/[email protected])
+ '@rushstack/ts-command-line': 5.3.13(@types/[email protected])
+ diff: 8.0.4
+ minimatch: 10.2.3
+ resolve: 1.22.12
+ semver: 7.7.4
+ source-map: 0.6.1
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - '@types/node'
+
+ '@microsoft/[email protected]':
+ dependencies:
+ '@microsoft/tsdoc': 0.16.0
+ ajv: 8.18.0
+ jju: 1.4.0
+ resolve: 1.22.12
+
+ '@microsoft/[email protected]': {}
+
'@modelcontextprotocol/[email protected]([email protected])':
dependencies:
'@hono/node-server': 2.1.1([email protected])
@@ -11485,7 +11654,7 @@ snapshots:
- react-native-b4a
- supports-color
- '@react-grab/[email protected]':
+ '@react-grab/[email protected]':
dependencies:
agent-install: 0.0.6
commander: 14.0.3
@@ -11555,6 +11724,45 @@ snapshots:
'@rtsao/[email protected]': {}
+ '@rushstack/[email protected](@types/[email protected])':
+ dependencies:
+ ajv: 8.20.0
+ ajv-draft-04: 1.0.0([email protected])
+ ajv-formats: 3.0.1([email protected])
+ fs-extra: 11.3.6
+ import-lazy: 4.0.0
+ jju: 1.4.0
+ resolve: 1.22.12
+ semver: 7.7.4
+ optionalDependencies:
+ '@types/node': 20.19.43
+
+ '@rushstack/[email protected](@types/[email protected])':
+ optionalDependencies:
+ '@types/node': 20.19.43
+
+ '@rushstack/[email protected]':
+ dependencies:
+ jju: 1.4.0
+ resolve: 1.22.12
+
+ '@rushstack/[email protected](@types/[email protected])':
+ dependencies:
+ '@rushstack/node-core-library': 5.24.0(@types/[email protected])
+ '@rushstack/problem-matcher': 0.2.1(@types/[email protected])
+ supports-color: 8.1.1
+ optionalDependencies:
+ '@types/node': 20.19.43
+
+ '@rushstack/[email protected](@types/[email protected])':
+ dependencies:
+ '@rushstack/terminal': 0.24.3(@types/[email protected])
+ '@types/argparse': 1.0.38
+ argparse: 1.0.10
+ string-argv: 0.3.2
+ transitivePeerDependencies:
+ - '@types/node'
+
'@sec-ant/[email protected]': {}
'@sentry-internal/[email protected]':
@@ -12304,6 +12512,8 @@ snapshots:
tslib: 2.8.1
optional: true
+ '@types/[email protected]': {}
+
dependencies:
'@types/node': 25.9.4
@@ -12706,7 +12916,7 @@ snapshots:
obug: 2.1.3
std-env: 4.2.0
tinyrainbow: 3.1.0
'@vitest/[email protected]':
dependencies:
@@ -12843,6 +13053,10 @@ snapshots:
dependencies:
humanize-ms: 1.2.1
+ optionalDependencies:
+ ajv: 8.20.0
+
optionalDependencies:
ajv: 8.20.0
@@ -12858,6 +13072,13 @@ snapshots:
json-schema-traverse: 0.4.1
uri-js: 4.4.1
+ dependencies:
+ fast-deep-equal: 3.1.3
+ fast-uri: 3.1.5
+ json-schema-traverse: 1.0.0
+ require-from-string: 2.0.2
+
dependencies:
fast-deep-equal: 3.1.3
@@ -14149,7 +14370,7 @@ snapshots:
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
- eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -14182,7 +14403,7 @@ snapshots:
tinyglobby: 0.2.17
unrs-resolver: 1.12.2
optionalDependencies:
- eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
@@ -14196,7 +14417,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -14696,6 +14917,12 @@ snapshots:
+ dependencies:
+ graceful-fs: 4.2.11
+ jsonfile: 6.2.1
+ universalify: 2.0.1
+
dependencies:
graceful-fs: 4.2.11
@@ -15120,6 +15347,8 @@ snapshots:
es-module-lexer: 2.3.1
module-details-from-path: 1.0.4
+
@@ -15394,6 +15623,8 @@ snapshots:
+
@@ -15472,6 +15703,24 @@ snapshots:
+ dependencies:
+ '@nodelib/fs.walk': 1.2.8
+ '@types/node': 20.19.43
+ fast-glob: 3.3.3
+ formatly: 0.3.0
+ jiti: 2.7.0
+ minimist: 1.2.8
+ oxc-resolver: 11.24.2
+ picocolors: 1.1.1
+ picomatch: 4.0.5
+ smol-toml: 1.8.0
+ strip-json-comments: 5.0.3
+ typescript: 6.0.3
+ unbash: 2.2.0
+ yaml: 2.9.0
+ zod: 4.4.3
+
dependencies:
fdir: 6.5.0([email protected])
@@ -16336,6 +16585,10 @@ snapshots:
- bufferutil
- utf-8-validate
+ dependencies:
+ brace-expansion: 5.0.9
+
dependencies:
brace-expansion: 5.0.7
@@ -17194,9 +17447,9 @@ snapshots:
react: 19.2.8
react-dom: 19.2.8([email protected])
dependencies:
- '@react-grab/cli': 0.1.50
+ '@react-grab/cli': 0.2.0
bippy: 0.6.1([email protected])
optionalDependencies:
react: 19.2.8
@@ -17224,7 +17477,7 @@ snapshots:
react: 19.2.8
react-doctor: 0.9.12(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))
react-dom: 19.2.8([email protected])
- react-grab: 0.1.50([email protected])
+ react-grab: 0.2.0([email protected])
optionalDependencies:
esbuild: 0.28.2
@@ -17498,6 +17751,13 @@ snapshots:
+ dependencies:
+ es-errors: 1.3.0
+ is-core-module: 2.16.2
+ path-parse: 1.0.7
+ supports-preserve-symlinks-flag: 1.0.0
+
dependencies:
es-errors: 1.3.0
@@ -17621,6 +17881,8 @@ snapshots:
+
@@ -18044,6 +18306,8 @@ snapshots:
optional: true
+
dependencies:
is-fullwidth-code-point: 2.0.0
@@ -18193,6 +18457,10 @@ snapshots:
dependencies:
has-flag: 4.0.0
+ dependencies:
+ has-flag: 4.0.0
+
@@ -18459,6 +18727,8 @@ snapshots:
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index f8085125b..150730a21 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -2,6 +2,7 @@ packages:
- "src/shared"
- "src/cli"
- "src/daemon"
+ - "src/daemon/agent-driver"
- "src/web"
- "src/email-worker"
- "src/ws-do"
diff --git a/scripts/agent-driver-loc.mjs b/scripts/agent-driver-loc.mjs
new file mode 100644
index 000000000..9b027a7e9
--- /dev/null
+++ b/scripts/agent-driver-loc.mjs
@@ -0,0 +1,78 @@
+#!/usr/bin/env node
+
+import { execFileSync } from "node:child_process"
+import fs from "node:fs"
+import path from "node:path"
+import { fileURLToPath } from "node:url"
+
+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
+const ref = process.argv[2] || null
+
+// Fixed for the lifetime of the atomic PR. New package code and every legacy
+// driver/session/manager composition file share one denominator, so moves and
+// temporary duplication cannot masquerade as production LOC reduction.
+const scopeRoots = [
+ "src/daemon/src/drivers",
+ "src/daemon/src/runtime",
+ "src/daemon/src/manager",
+ "src/daemon/src/daemon/createDaemon.ts",
+ "src/daemon/src/types.ts",
+ "src/daemon/src/runtimeConfig.ts",
+ "src/daemon/src/discovery.ts",
+ "src/daemon/agent-driver/src",
+]
+
+function isProductionTypeScript(file) {
+ return file.endsWith(".ts") && !file.endsWith(".test.ts") && !file.endsWith(".spec.ts")
+}
+
+function currentFiles() {
+ const files = []
+ const visit = (relative) => {
+ const absolute = path.join(repoRoot, relative)
+ if (!fs.existsSync(absolute)) return
+ const stat = fs.statSync(absolute)
+ if (stat.isFile()) {
+ if (isProductionTypeScript(relative)) files.push(relative)
+ return
+ }
+ for (const entry of fs.readdirSync(absolute).sort()) {
+ visit(path.posix.join(relative, entry))
+ }
+ }
+ for (const root of scopeRoots) visit(root)
+ return [...new Set(files)].sort()
+}
+
+function refFiles(gitRef) {
+ const output = execFileSync(
+ "git",
+ ["ls-tree", "-r", "--name-only", gitRef, "--", ...scopeRoots],
+ { cwd: repoRoot, encoding: "utf8" },
+ )
+ return [...new Set(output.split("\n").filter(isProductionTypeScript))].sort()
+}
+
+function content(file) {
+ if (!ref) return fs.readFileSync(path.join(repoRoot, file), "utf8")
+ return execFileSync("git", ["show", `${ref}:${file}`], { cwd: repoRoot, encoding: "utf8" })
+}
+
+function physicalLines(text) {
+ if (!text) return 0
+ const lines = text.split(/\r?\n/)
+ return lines.at(-1) === "" ? lines.length - 1 : lines.length
+}
+
+const files = ref ? refFiles(ref) : currentFiles()
+const entries = files.map((file) => ({ file, lines: physicalLines(content(file)) }))
+const result = {
+ schemaVersion: 1,
+ ref: ref ?? "WORKTREE",
+ scopeRoots,
+ excludes: ["**/*.test.ts", "**/*.spec.ts", "non-TypeScript files"],
+ files: entries,
+ total: entries.reduce((sum, entry) => sum + entry.lines, 0),
+}
+
+process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)
diff --git a/scripts/bump-version.mjs b/scripts/bump-version.mjs
index 5417dafbb..21a718c25 100644
--- a/scripts/bump-version.mjs
+++ b/scripts/bump-version.mjs
@@ -4,7 +4,7 @@ import { join } from "node:path";
import { execSync } from "node:child_process";
const ROOT = new URL("..", import.meta.url).pathname.replace(/\/$/, "");
-const WORKSPACE_DIRS = ["src/shared", "src/cli", "src/app", "src/daemon", "src/web", "src/email-worker", "src/ws-do", "src/wake-worker", "src/desktop"];
+const WORKSPACE_DIRS = ["src/shared", "src/cli", "src/app", "src/daemon", "src/daemon/agent-driver", "src/web", "src/email-worker", "src/ws-do", "src/wake-worker", "src/desktop"];
const DEPLOY_TRIGGER_DIRS = ["src/web", "src/email-worker", "src/ws-do", "src/wake-worker"];
function readPkg(dir) {
diff --git a/scripts/check-agent-driver-boundaries.mjs b/scripts/check-agent-driver-boundaries.mjs
new file mode 100644
index 000000000..1d1bb7a68
--- /dev/null
+++ b/scripts/check-agent-driver-boundaries.mjs
@@ -0,0 +1,28 @@
+import { readFileSync, readdirSync, statSync } from "node:fs";
+import { join, relative } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = fileURLToPath(new URL("../", import.meta.url));
+const daemonSource = join(root, "src/daemon/src");
+const violations = [];
+
+function visit(directory) {
+ for (const name of readdirSync(directory)) {
+ const path = join(directory, name);
+ if (statSync(path).isDirectory()) {
+ visit(path);
+ continue;
+ }
+ if (!name.endsWith(".ts") || name.endsWith(".test.ts")) continue;
+ if (readFileSync(path, "utf8").includes("@alook/agent-driver/adapter-author")) {
+ violations.push(relative(root, path));
+ }
+ }
+}
+
+visit(daemonSource);
+if (violations.length > 0) {
+ console.error(`Daemon production must not import adapter-author:\n${violations.join("\n")}`);
+ process.exit(1);
+}
+console.log("agent-driver production import boundary: PASS");
diff --git a/scripts/ci/api-report-contract.test.ts b/scripts/ci/api-report-contract.test.ts
new file mode 100644
index 000000000..197ac070f
--- /dev/null
+++ b/scripts/ci/api-report-contract.test.ts
@@ -0,0 +1,19 @@
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { describe, expect, it } from "vitest";
+
+const apiDirectory = resolve(process.cwd(), "src/daemon/agent-driver/etc/api");
+
+describe("agent-driver API reports", () => {
+ it.each(["root", "host", "adapter-author", "testing"])("has no hidden exported dependency in %s", (name) => {
+ const report = readFileSync(resolve(apiDirectory, `${name}.api.md`), "utf8");
+ expect(report).not.toContain("ae-forgotten-export");
+ });
+
+ it("captures transitively exposed adapter-author input shapes", () => {
+ const report = readFileSync(resolve(apiDirectory, "adapter-author.api.md"), "utf8");
+ expect(report).toContain("export interface AdapterLaunchConfig");
+ expect(report).toContain("runtimeConfig?: Config;");
+ expect(report).toContain("export type InputMode = \"busy\" | \"idle\";");
+ });
+});
diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.ts
index 2ce7e0b37..4fa9460ca 100644
--- a/scripts/ci/workflow-contract.test.ts
+++ b/scripts/ci/workflow-contract.test.ts
@@ -3,6 +3,7 @@ import { resolve } from "node:path"
import { describe, expect, it } from "vitest"
const workflowRoot = resolve(import.meta.dirname, "../../.github/workflows")
+const repositoryRoot = resolve(import.meta.dirname, "../..")
function normalizeWorkflow(text: string): string {
return text.replace(/\r\n/g, "\n")
}
@@ -45,6 +46,16 @@ const desktopUpdateRoute = readFileSync(
)
const publishWorkflows = ["publish-app.yml", "publish-cli.yml", "publish-daemon.yml"]
.map((name) => normalizeWorkflow(readFileSync(resolve(workflowRoot, name), "utf8")))
+const publishDaemonWorkflow = normalizeWorkflow(
+ readFileSync(resolve(workflowRoot, "publish-daemon.yml"), "utf8"),
+)
+const agentDriverPackage = JSON.parse(
+ readFileSync(resolve(repositoryRoot, "src/daemon/agent-driver/package.json"), "utf8"),
+) as { private?: boolean; publishConfig?: unknown }
+const daemonPackage = JSON.parse(
+ readFileSync(resolve(repositoryRoot, "src/daemon/package.json"), "utf8"),
+) as { devDependencies?: Record<string, string> }
+const workspaceManifest = readFileSync(resolve(repositoryRoot, "pnpm-workspace.yaml"), "utf8")
function ciJob(name: string): string {
const start = ciWorkflow.indexOf(`\n ${name}:\n`)
@@ -98,10 +109,67 @@ describe("Bun workflow setup", () => {
})
})
+describe("Private agent driver package", () => {
+ it("remains an independent private workspace dependency of the daemon", () => {
+ expect(agentDriverPackage.private).toBe(true)
+ expect(agentDriverPackage).not.toHaveProperty("publishConfig")
+ expect(workspaceManifest).toContain('"src/daemon/agent-driver"')
+ expect(daemonPackage.devDependencies?.["@alook/agent-driver"]).toBe("workspace:*")
+ })
+
+ it("cannot be published by a repository workflow", () => {
+ expect(existsSync(resolve(workflowRoot, "publish-agent-driver.yml"))).toBe(false)
+ })
+
+ it("builds the workspace driver before a clean daemon publish build", () => {
+ const driverBuild = publishDaemonWorkflow.indexOf("pnpm -C src/daemon/agent-driver run build")
+ const daemonBuild = publishDaemonWorkflow.indexOf("pnpm -C src/daemon run build")
+ expect(driverBuild).toBeGreaterThan(0)
+ expect(daemonBuild).toBeGreaterThan(driverBuild)
+ })
+})
+
describe("CI test budgets", () => {
it("gives the slower Windows workspace suite enough job time", () => {
expect(ciJob("test-windows")).toContain("timeout-minutes: 15")
})
+
+ it("runs Windows process-authority and full driver fixtures in isolation before the daemon suite", () => {
+ const windows = ciJob("test-windows")
+ const processAuthority = windows.indexOf(
+ "pnpm --filter @alook/agent-driver exec vitest run src/internal/killTree.test.ts",
+ )
+ const driver = windows.indexOf(
+ "pnpm --filter @alook/agent-driver exec vitest run --no-file-parallelism --coverage --coverage.reporter=json --coverage.reporter=text",
+ )
+ const coverageUpload = windows.indexOf("files: ./src/daemon/agent-driver/coverage/coverage-final.json")
+ const focusedAdmission = windows.indexOf(
+ "pnpm --filter @alook/daemon exec vitest run src/daemon/createDaemon.test.ts",
+ )
+ const daemon = windows.indexOf("pnpm --filter @alook/daemon test")
+ expect(processAuthority).toBeGreaterThan(0)
+ expect(driver).toBeGreaterThan(processAuthority)
+ expect(coverageUpload).toBeGreaterThan(driver)
+ expect(focusedAdmission).toBeGreaterThan(coverageUpload)
+ expect(daemon).toBeGreaterThan(focusedAdmission)
+ })
+
+ it("uploads the Windows driver report without accidentally discovering unrelated files", () => {
+ const windows = ciJob("test-windows")
+ expect(windows).toContain("disable_search: true")
+ expect(windows).toContain("name: windows-agent-driver")
+ expect(windows).toContain("fail_ci_if_error: true")
+ })
+
+ it("does not rerun Windows process-bearing packages inside the Turbo workspace step", () => {
+ const windows = ciJob("test-windows")
+ expect(windows).toContain(
+ "run: pnpm turbo run test --filter='!@alook/daemon' --filter='!@alook/agent-driver'",
+ )
+ expect(windows).toContain(
+ "run: pnpm turbo run test --affected --filter='!@alook/daemon' --filter='!@alook/agent-driver'",
+ )
+ })
})
describe("CI dependency setup", () => {
@@ -168,12 +236,16 @@ describe("Turbo CI execution", () => {
expect(ciJob("quality")).toContain("run: pnpm typecheck")
expect(ciJob("quality")).toContain("run: pnpm lint")
expect(ciJob("knip")).toContain("run: pnpm knip")
- for (const job of ["test-linux", "test-windows"]) {
- const definition = ciJob(job)
- expect(definition).toContain("run: pnpm turbo run test --filter=@alook/daemon")
- expect(definition).toContain("run: pnpm turbo run test --filter='!@alook/daemon'")
+ const linux = ciJob("test-linux")
+ expect(linux).toContain("run: pnpm turbo run test --filter=@alook/daemon")
+ const windows = ciJob("test-windows")
+ expect(windows).toContain("run: pnpm --filter @alook/daemon test")
+ expect(linux).toContain("run: pnpm turbo run test --filter='!@alook/daemon'")
+ expect(windows).toContain(
+ "run: pnpm turbo run test --filter='!@alook/daemon' --filter='!@alook/agent-driver'",
+ )
+ for (const definition of [linux, windows])
expect(definition.match(/VITEST_MAX_WORKERS: 1/g)).toHaveLength(2)
- }
expect(ciJob("build")).toContain(
"run: pnpm build --filter=@alook/shared --filter=@alook/web --filter=@alook/cli --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/wake-worker",
)
diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md
new file mode 100644
index 000000000..cc25879c6
--- /dev/null
+++ b/src/daemon/AGENTS.md
@@ -0,0 +1,99 @@
+# Daemon design contract
+
+These rules define the product architecture and runtime behavior for
+`src/daemon`. `agent-driver/AGENTS.md` adds package-specific rules.
+
+## Design from the product guarantee
+
+- Never trade away a stronger user capability because a weaker state machine is
+ easier to implement, own, clean up, or test. Define the user's minimum
+ guarantee first; optimization and deduplication operate above that floor.
+- Persistent execution is the default and preferred product model. If a backend
+ supports a native persistent session, process, or transport, keep it
+ persistent. Never replace it with per-turn execution for engineering
+ convenience. A lifecycle downgrade requires an explicit product decision.
+- A priority statement is not cancellation. Do not remove or rewrite a locked
+ architecture, capability, module, or package boundary without an explicit
+ decision to change that design.
+
+## Architecture
+
+- D1/server state owns durable messages and read state. The wake coordinator
+ owns unread reminder coverage. The daemon manager owns logical-session and
+ admission orchestration. The independent agent-driver package owns provider
+ protocols, physical sessions, capabilities, and process lifecycles.
+- A stored message is not proof of wake delivery. A WebSocket acknowledgement is
+ not proof of session injection. A driver receipt is not proof of terminal
+ cleanup. Keep these boundaries and authorities separate.
+- Daemon code consumes declared contracts and capabilities. Provider names,
+ wire events, SDK objects, and transport quirks stay inside adapters.
+- In-memory state coordinates only the current daemon instance. Unread work must
+ remain recoverable after disconnect, crash, restart, reset, model switch, or
+ failed spawn.
+
+## Wake is lossless
+
+- Every unread must be covered by at least one effective wake injection. Wakes
+ may merge from N to 1; they must never collapse from N to 0.
+- Every accepted WebSocket wake that advances an unread watermark must reach the
+ current logical session or remain reliably queued for it. This is required
+ while the agent is active or admitting too; never acknowledge and suppress a
+ new watermark into unowned memory.
+- Coverage ends only when model-seen proves the agent actually observed that
+ unread. `active`, `admitting`, persistence, transport send/ack, driver receipt,
+ or a later incidental inbox pull do not satisfy this condition.
+- A higher watermark arriving during active work enters the same persistent
+ logical session. Its adapter may steer now, inject at a safe boundary, or
+ queue the next turn, but delivery cannot wait for outbound alignment or
+ shutdown.
+- Deduplicate by stable semantic identity and covered watermark, not by the
+ existence of an active turn. Preserve order; settle multi-channel coverage per
+ channel; return every unseen watermark to idempotent FIFO retry after failure,
+ idle, close, or epoch replacement.
+
+## Session and turn authority
+
+- Bind mutable authority to the exact session instance/epoch and root turn.
+ Stale, duplicate, unknown, child, or superseded events cannot close, revive,
+ delete, or settle the current owner.
+- Only the matching root terminal ends root execution. Subagent completion is
+ not root completion. Long-running root tools remain live work across silence;
+ a queued-next-turn diagnostic must not hide that tool ownership.
+- A queued command receipt preserves provisional responsibility; it does not
+ complete the command. Acceptance settles it. Failure, close, or exit requeues
+ it exactly once. True unacknowledged admissions and true inactive roots must
+ still time out.
+- Reset, stop, model switch, restart, and recovery preserve unread work and
+ fence the old epoch. Old cleanup can affect only its captured instance and
+ must never delete or terminate a replacement.
+- A stop receipt, including `already_stopping`, is not terminal. The exact
+ session's `closed` completion is authoritative only after logical and physical
+ cleanup has finished.
+
+## Capability and process ownership
+
+- Busy delivery is capability-driven: immediate steer, safe-boundary injection,
+ or next-turn queue. These modes change when an injection is consumed, never
+ whether it is delivered. Do not fake unsupported steering or branch shared
+ code on backend names.
+- Every CLI, tool, and MCP server belongs to one agent-driver process authority.
+ Before spawn, the daemon/host ensures the workspace and working directory
+ exist; fresh start cannot depend on a previous run or adapter side effect.
+- On POSIX, retain bounded authority over the exact root's captured descendant
+ PIDs and descendant-owned process groups through TERM/KILL. Never global-scan
+ or signal an unrelated group. On Windows, retain the Job Object boundary.
+- Shutdown completes only after snapshotted sessions reach `closed` and every
+ owned process is dead. Killing only the root, sending a signal, or exhausting
+ a grace period is not successful cleanup; daemon exit must leave no orphan.
+
+## Required behavioral proof
+
+- Test the public chain: durable unread -> wake coverage -> session injection ->
+ model-seen -> ordered handling. Isolated downstream tests cannot prove wake
+ delivery.
+- Cover persistent reuse, rapid-message N-to-1 delivery, message-during-work,
+ failure/retry, partial observation, reset/replacement fencing, long root tools,
+ root-vs-child terminal correlation, and clean shutdown.
+- Process cleanup requires real operating-system trees, including detached
+ descendants. Every built-in backend must pass the same user journeys with its
+ declared capability and without loss, duplication, false terminal, or orphan.
diff --git a/src/daemon/README.md b/src/daemon/README.md
index 8ea7b8402..ef432ef86 100644
--- a/src/daemon/README.md
+++ b/src/daemon/README.md
@@ -1,22 +1,17 @@
# @alook/daemon
-A **pure, host-neutral agent-runtime "driver" abstraction** in TypeScript.
-
-It documents — as compilable code — how a host adapts many different AI coding
-runtimes (Claude Code, Codex, Gemini, Kimi, Pi, Copilot, Cursor, OpenCode,
-Antigravity) behind one uniform interface, and how it delivers messages into a
-running agent (the "steering" mechanism).
-
-The backend hardcodes **no specific host platform**. The agent always invokes a
-stable CLI name (`alook`); `cliTransport.ts` writes a small wrapper by that
-name into a per-launch state dir, prepends it to `PATH`, and forwards to the
-host's real `targetCommand` — **decoupling the agent-facing name from the host's
-real binary** (the host can rename/relocate its CLI without touching the agent
-surface). It also injects an `ALOOK_*` env contract. The default
-`MOCK_CLI_CONFIG` wires no `targetCommand` (the wrapper errors if invoked); a
-real deployment passes its own `CliTransportConfig` (CLI name, env prefix,
-`targetCommand`) and its own system-prompt communication guide. The abstraction
-is what's reusable — plug in whatever host you like.
+Alook's host daemon: control-plane connectivity, agent scheduling, credentials,
+diagnostics, and lifecycle orchestration.
+
+Runtime execution lives in the independently buildable `@alook/agent-driver`
+package under `agent-driver/`. That package adapts Claude Code, Codex, Cursor,
+OpenCode, and Pi behind one public `AgentSession` contract. The daemon consumes
+that contract and does not speak vendor process or SDK protocols.
+
+The driver package remains host-neutral. Its CLI transport creates a per-launch
+state directory, exposes a stable `alook` command through `PATH`, and composes
+explicit environment layers supplied by the host. Vendor adapters never import
+daemon credentials or control-plane code.
> **Provenance.** The shapes, protocols, flag strings, and control flow here were
> derived by studying how production agent-runtime daemons drive these CLIs, then
@@ -61,67 +56,60 @@ into logs, bug reports, or chat.
## The big idea
-The daemon never speaks a runtime's native protocol directly. Each runtime is
-wrapped by a **`Driver`** (`src/types.ts`) that knows how to:
-
-1. **`spawn`** (or `createSession`) — launch the runtime,
-2. **`encodeStdinMessage`** — encode an outgoing user message for the runtime's
- input channel,
-3. **`parseLine`** — normalize the runtime's output into a tiny shared event
- vocabulary (`ParsedEvent`: `session_init`, `thinking`, `text`, `tool_call`,
- `tool_output`, `compaction_*`, `turn_end`, `error`, `telemetry`).
-
-A generic **session host** then runs the process and fans `ParsedEvent`s out to
-the daemon:
+The daemon creates an `AgentDriverSdk`, probes or opens a selected backend, and
+then works only with an `AgentSession`:
-- `ChildProcessRuntimeSession` (`src/runtime/runtimeSession.ts`) for CLI runtimes.
-- `SdkRuntimeSession` (`src/runtime/sdkRuntimeSession.ts`) for in-process SDK
- runtimes (pi).
+- `start(message)` admits the first command.
+- `send(message)` accepts, queues, or rejects a later command with a typed receipt.
+- `interrupt(...)` and `stop(...)` provide bounded lifecycle control.
+- `snapshot()` exposes logical state without leaking process/SDK objects.
+- `events` is an async stream of normalized `AgentEvent` values.
+- `closed` settles exactly once with terminal and host-cleanup facts.
-Because everything downstream consumes the same `ParsedEvent` stream and the
-same `Driver` capability flags, the rest of the daemon is transport-agnostic.
+Inside `@alook/agent-driver`, a backend adapter declares its execution model and
+normalizes vendor output. `LogicalAgentSession` owns admission, FIFO queueing,
+safe-boundary delivery, terminal ordering, and cleanup. Internal `ProcessLane`
+and `SdkLane` hosts make child-process and in-process SDK transports look alike;
+they are deliberately not public daemon primitives.
---
-## Two delivery models (the heart of it)
+## Persistent delivery models (the heart of it)
When a message arrives, what happens depends on the runtime's lifecycle:
-### Persistent runtimes (claude, codex, kimi, pi)
-One long-lived process spans many turns. A new message is **written onto the
-still-open input channel** — no restart. This is "steering."
-
-The busy-delivery mode is **derived from `lifecycle`** (`busyDeliveryModeOf` /
-`supportsStdinNotificationOf` in `types.ts`) — `lifecycle.stdin` is the single
-source of truth, so a driver's mode can't drift from it (it used to: a driver
-could declare `lifecycle.stdin: "gated"` yet `busyDeliveryMode: "direct"`).
-`persistent+direct → direct`, `persistent+gated → gated`, `per_turn → none`.
-
-- **`direct`** (kimi, pi): write immediately; the runtime tolerates injection
- any time.
-- **`gated`** (claude, codex): a raw write mid-stream could collide with an active
- signed thinking block, so writes are **held until a safe boundary**,
- implemented by:
- - `apmStateMachine` (`src/runtime/apmStateMachine.ts`) — the policy reducers
- that decide *when* to flush queued inbox notices and emit the concrete
- `notify_stdin` / `deliver_stdin` effects (clause `SMR-002`). Flushing is
- blocked while `outstanding_tool_uses > 0`, while `compacting`, while
- `reviewing` (Codex review mode), or when `tool_boundary_flush_disabled`.
- Compaction *and* review exit are treated as safe flush boundaries.
+### Safe-boundary runtimes (Claude and Codex)
+
+One child process spans many turns. Both adapters declare `lifetime: "session"`;
+their public capability is `midTurnDelivery: "safe_boundary_queue"`. A message arriving during tool use,
+compaction, or review is queued by `LogicalAgentSession` and receives a later
+`command_accepted` or `command_failed` event. The daemon does not implement that
+protocol or queue.
For Claude specifically, the input channel is **stream-json**: the process is
launched with `--input-format stream-json --output-format stream-json
--include-partial-messages`, and each message is one NDJSON line
`{"type":"user","message":{"role":"user","content":[{"type":"text","text":…}]}}`.
-### Per-turn runtimes (gemini, copilot, cursor, opencode, antigravity)
-The process handles exactly one turn and exits. `supportsStdinNotification` is
-`false` and `encodeStdinMessage` returns `null`. A new message means a **brand-new
-process**; the agent re-checks the inbox each wake. This lifecycle
-(`lifecycle.kind: "per_turn"`) drives the `## Message Notifications` section
-generated by `buildCliSystemPrompt` — no driver hand-writes this reminder.
-`opencode` is a special per-turn case: it defers spawning until a concrete
-message and terminates the process on turn end.
+### In-process SDK runtime (Pi)
+
+Pi declares the `in_process_sdk` transport and
+`midTurnDelivery: "steer"`. Its lane delegates prompt, steer, abort, and dispose
+to the SDK while preserving the same receipts, events, and terminal contract.
+
+### Persistent queued runtime (Cursor)
+
+Cursor keeps one `cursor-agent acp` process and ACP session for the logical
+session. Each idle command is a `session/prompt` request; while one is active,
+later commands remain in the logical next-turn FIFO until its correlated
+response arrives. Interrupt sends `session/cancel` without killing the process.
+
+### Persistent service runtime (OpenCode)
+
+OpenCode starts one authenticated, loopback-only v2 service per logical session.
+Root prompts and busy steers share the same service and vendor session. Durable
+session SSE is replayed by event id and sequence across reconnects; a separate
+live stream handles permissions.
---
@@ -129,67 +117,48 @@ message and terminates the process on turn end.
| Runtime | Lifecycle | Transport / protocol | Steering | Initial input | Output format |
|---|---|---|---|---|---|
-| **claude** | persistent | child process, stream-json NDJSON | `gated` | `{type:"user",…}` line on stdin | stream-json |
-| **codex** | persistent | child process, JSON-RPC 2.0 (`app-server --listen stdio://`) | `gated` | `initialize` → `thread/start`/`resume` | JSON-RPC notifications |
-| **kimi** | persistent | child process, JSON-RPC "wire" | `direct` (`steer`) | `initialize` → `prompt` | JSON-RPC events |
-| **pi** | persistent | in-process SDK (`@earendil-works/pi-coding-agent`), multi-provider | `direct` | `session.prompt()` | SDK event callback |
-| **gemini** | per-turn | child process, stream-json | none | prompt on stdin, then close | stream-json |
-| **copilot** | per-turn | child process, JSON | none | prompt as `-p` arg | JSON events |
-| **cursor** | per-turn | child process, stream-json | none | prompt as trailing arg | stream-json |
-| **opencode** | per-turn (defer-spawn, terminate-on-end) | child process, JSON | none | prompt as `-- <arg>` | JSON events |
-| **antigravity** | per-turn | child process, **plain text** | none | prompt on stdin, then close | plain text lines |
-
-(Each driver's exact launch flags live in its file under `src/drivers/`.)
+| **claude** | persistent session | stream-json NDJSON | `safe_boundary_queue` | stdin user-message line | stream-json |
+| **codex** | persistent session | JSON-RPC 2.0 (`app-server --listen stdio://`) | `safe_boundary_queue` | `initialize` → `thread/start`/`resume` | JSON-RPC notifications |
+| **pi** | persistent session | `@earendil-works/pi-coding-agent` | `steer` | `session.prompt()` | SDK callback |
+| **cursor** | persistent session | ACP JSON-RPC 2.0 (`cursor-agent acp`) | `next_turn_queue` | `session/prompt` | `session/update` + correlated prompt response |
+| **opencode** | persistent session | authenticated HTTP + SSE (`opencode serve --pure`) | `steer` | v2 session prompt API | durable + live SSE |
+
+(Exact launch flags live in `agent-driver/src/adapters/<backend>/`.)
---
## Layout
```
+agent-driver/
+ src/
+ contract.ts # public SDK, session, receipt, event, and result types
+ sdk.ts # createAgentDriverSdk
+ registry.ts # built-in ids and capabilities
+ controller/
+ logical-session.ts # admission, queueing, turns, stop, cleanup
+ process-host.ts # internal child-process lane
+ sdk-host.ts # internal in-process SDK lane
+ adapters/<backend>/ # vendor launch + normalization
+ host/default-host.ts # standalone host implementation
+ internal/ # adapter-only transport/config/process helpers
+ testing/ # public conformance fixtures
src/
- types.ts # Driver interface + ParsedEvent + lifecycle/capability types
- index.ts # public entry point
- logger.ts # tiny structured logger (ALOOK_LOG_LEVEL); wired through
- # wsControlChannel.ts/agentRouter.ts/managerRuntime.ts too, not just cli/daemonStart.ts
- drivers/
- index.ts # getDriver(runtimeId) registry ← start here
- cliTransport.ts # shared: state dir, token, decoupling cliName wrapper -> targetCommand, env
- systemPrompt.ts # shared: standing-prompt assembly
- probe.ts # CLI/binary detection + version
- claude.ts # Claude Code driver
- claudeLaunch.ts # args / command / spawn-spec / prompt-file
- claudeProviderIsolation.ts # custom-provider HOME/config isolation
- claudeEventNormalizer.ts # stream-json → ParsedEvent
- codex.ts / codexEventNormalizer.ts / codexTelemetrySidecar.ts
- gemini.ts copilot.ts cursor.ts opencode.ts antigravity.ts
- kimi.ts # child-process Kimi (JSON-RPC wire)
- pi.ts # in-process Pi SDK (multi-provider)
- runtime/
- runtimeSession.ts # ChildProcessRuntimeSession + descriptor
- sdkRuntimeSession.ts # SdkRuntimeSession (in-process)
- apmStateMachine.ts # gated-delivery policy reducers (SMR-002)
- progressState.ts # liveness / stall detection
- notificationState.ts # inbox-notice de-dup + batching
- errorDiagnostics.ts # runtime-error classification + scrubbing
- inbox/
- projection.ts # bucket pending messages by target → notice snapshots
- stateMachine.ts # pre-action freshness guard (forward / hold / bypass)
+ index.ts # daemon exports; re-exports the driver public API
+ drivers/index.ts # daemon runtime lookup/probe facade only
+ logger.ts # structured daemon logging
+ runtime/ # manager liveness, notification, error helpers
+ inbox/ # unread projection and freshness policy
manager/
- managerPolicy.ts # pure reducer: single-flight, wake/sleep, queue+coalesce, stalled
- managerRuntime.ts # AgentProcessManager: applies effects to real sessions
- server/
- contract.ts # ServerApi (data) + EnrollmentApi (machine→runner key) + HostControlChannel (control) + AdminApi
- wsControlServer.ts # server end of the control plane over ws (machine-key authed)
- wsControlChannel.ts # host end: WebSocket HostControlChannel (injectable socket, reconnect + heartbeat + resync)
- daemon/
- createDaemon.ts # runtime-agnostic daemon factory (driver/sessionFactory/runtimes INJECTED; no test code)
- cli/
- index.ts # the `alook` agent CLI skeleton (message send / inbox pull)
- proxyServerApi.ts # agent data-plane client: voucher → proxy → server (identity from the voucher)
- credentials/
- credentialProxy.ts # CredentialBroker (mint/revoke/check per-voucher vouchers) + local key-swapping proxy
+ agentDriverHost.ts # host resource/env/CLI preparation
+ managerPolicy.ts # pure scheduling reducer
+ managerRuntime.ts # applies effects through AgentSession
+ server/ # data/control-plane contracts and WebSockets
+ daemon/createDaemon.ts # runtime-agnostic daemon composition
+ cli/ # lifecycle CLI and proxy data-plane client
+ credentials/ # voucher broker and key-swapping proxy
scripts/
- daemon.ts # local entry: delegates to the canonical `alook daemon` parser
+ daemon.ts # local daemon entry
```
## Host orchestration (manager + server)
@@ -361,22 +330,42 @@ posting a message in a channel it's a member of — the real wake-producer path
(`src/web` → `src/wake-worker` → `src/ws-do`) delivers `agent:wake` over the
daemon's real `WsControlChannel`.
-> **Run the source, not `dist/` (yet).** `pnpm run build` emits JS, but the
-> current Bundler-resolution emit produces extensionless relative imports that
-> Node's native ESM rejects (`Cannot find module './types'`). Until that's
-> switched to NodeNext or bundled, consume the library through a TS toolchain
-> (tsx / ts-node / vite / esbuild / webpack).
+`pnpm --filter @alook/daemon build` emits a self-contained daemon bundle. The
+published tarball includes the runtime-driver implementation, while
+`@alook/agent-driver` is also independently buildable and publishable for hosts
+that want only the logical-session SDK.
## Usage sketch
```ts
-import { getDriver, createChildProcessRuntimeSession } from "@alook/daemon";
-
-const driver = getDriver("claude");
-const session = createChildProcessRuntimeSession(driver, ctx);
-session.on("runtime_event", (e) => handleParsedEvent(e));
-await session.start({ text: initialPrompt });
-
-// Later, a message arrives while the agent is working:
-session.send({ text: "new message from #general", mode: "busy" }); // steer
+import { createAgentDriverSdk } from "@alook/agent-driver";
+
+const sdk = createAgentDriverSdk();
+const opened = await sdk.open({
+ backend: "codex",
+ launch: {
+ workingDirectory: ".",
+ instructions: { format: "markdown", content: "Be concise." },
+ launchId: "launch-example",
+ },
+ config: {
+ model: { kind: "default" },
+ mode: "default",
+ },
+});
+if (!opened.ok) throw new Error(opened.error.message);
+
+const { session } = opened;
+const eventsDone = (async () => {
+ for await (const event of session.events) {
+ if (event.type === "text_delta") process.stdout.write(event.text);
+ }
+})();
+
+await session.start({ id: "command-1", kind: "user", text: "Inspect this repository." });
+await session.send({ id: "command-2", kind: "user", text: "Now summarize the risks." });
+await session.stop({ reason: "owner_request", forceAfterMs: 5_000 });
+const result = await session.closed;
+await eventsDone;
+void result;
```
diff --git a/src/daemon/agent-driver/.gitignore b/src/daemon/agent-driver/.gitignore
new file mode 100644
index 000000000..072940b0c
--- /dev/null
+++ b/src/daemon/agent-driver/.gitignore
@@ -0,0 +1,3 @@
+dist/
+LICENSE
+*.tgz
diff --git a/src/daemon/agent-driver/AGENTS.md b/src/daemon/agent-driver/AGENTS.md
new file mode 100644
index 000000000..3d64857bc
--- /dev/null
+++ b/src/daemon/agent-driver/AGENTS.md
@@ -0,0 +1,55 @@
+# Agent driver design contract
+
+These rules add to `../AGENTS.md` for the independent
+`@alook/agent-driver` workspace package.
+
+## Independent private boundary
+
+- Keep agent-driver as an independent private package even without an external
+ consumer. Its purpose is to make daemon/provider coupling structurally
+ impossible. Do not fold it into daemon source or change its directory/package
+ boundary merely because publishing is a lower priority.
+- Keep its manifest, declared exports, build, tests, API reports, ownership, and
+ artifact-isolation checks. Daemon consumes only declared root/host contracts;
+ it never deep-imports adapters, controllers, transports, provider SDKs, or
+ internals.
+- Daemon may bundle the package from the same commit, but its packed artifact
+ must not require a separately published agent-driver at runtime.
+
+## Persistent provider contract
+
+- Use each provider's strongest native persistent session, process, and
+ transport. Never substitute a per-turn process for an available persistent
+ protocol to simplify shared lifecycle code.
+- Keep vendor protocol details inside the adapter. Normalize them into public
+ session events, receipts, snapshots, capabilities, and terminal results;
+ vendor SDK objects are never daemon authority.
+- Declare busy delivery truthfully as immediate steer, safe-boundary injection,
+ or next-turn queue. A queued receipt retains command ownership; it is not
+ acceptance or completion. Never report a fake steer.
+- All modes preserve stable command identity, order, and exact-once settlement
+ across queueing, interruption, close, failure, and restart.
+
+## Root, terminal, and process authority
+
+- Correlate events to the exact physical session, logical epoch, and root turn.
+ Child/subagent, stale, unknown, and duplicate terminals cannot become root
+ terminals or start root idle cleanup.
+- Stop receipts admit a request. `already_stopping` preserves the existing
+ cleanup owner; `session.closed` becomes terminal only after lanes, transports,
+ and processes are cleaned. Late cleanup cannot affect a replacement session.
+- All CLI launches and termination go through the package's single host process
+ authority. Adapters have no direct spawn/kill escape path.
+- POSIX cleanup retains bounded authority over captured descendants and their
+ owned process groups, including detached MCP/tool groups. Windows cleanup
+ remains inside the kill-on-close Job Object authority.
+
+## Contract standard
+
+- Shared conformance covers native persistent reuse, declared busy-delivery
+ semantics, stable receipts, root-vs-child terminal correlation, recovery, and
+ complete process cleanup for every built-in adapter. A fake adapter alone is
+ not evidence for real providers.
+- Adapter-specific behavior may strengthen but never weaken shared semantics.
+ Public exports, API reports, and packaged artifacts must preserve the same
+ boundary as source imports.
diff --git a/src/daemon/agent-driver/CLAUDE.md b/src/daemon/agent-driver/CLAUDE.md
new file mode 120000
index 000000000..47dc3e3d8
--- /dev/null
+++ b/src/daemon/agent-driver/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/src/daemon/agent-driver/README.md b/src/daemon/agent-driver/README.md
new file mode 100644
index 000000000..f819529b9
--- /dev/null
+++ b/src/daemon/agent-driver/README.md
@@ -0,0 +1,153 @@
+# @alook/agent-driver
+
+Repository-private logical-session drivers for Claude, Codex, Cursor, OpenCode,
+and Pi.
+
+The package's exported contract owns backend lifecycle, message admission,
+buffering, queueing, interrupts, stop deadlines, and normalized events. The
+daemon selects a backend and interacts with one `AgentSession`; process and SDK
+implementation details are internal.
+
+The package root exposes only the logical SDK/session/event/result contract.
+`@alook/agent-driver/testing` contains black-box exported-session fixtures.
+Repository adapters use the separately versioned
+`@alook/agent-driver/adapter-author` extension boundary; process and vendor-SDK
+declarations are intentionally absent from both the root and `/testing`
+declarations. The daemon uses the narrow `@alook/agent-driver/host` boundary for
+host resource preparation and the host-enabled built-in SDK factory.
+
+```ts
+import { createAgentDriverSdk } from "@alook/agent-driver";
+
+const sdk = createAgentDriverSdk();
+const opened = await sdk.open({
+ backend: "codex",
+ launch: {
+ workingDirectory: ".",
+ instructions: { format: "markdown", content: "Be concise." },
+ launchId: "launch-example",
+ },
+ config: {
+ model: { kind: "default" },
+ mode: "default",
+ },
+});
+if (!opened.ok) throw new Error(opened.error.message);
+
+const session = opened.session;
+const observedText: string[] = [];
+const eventsDone = (async () => {
+ for await (const event of session.events) {
+ if (event.type === "text_delta") observedText.push(event.text);
+ }
+})();
+
+const receipt = await session.start({
+ id: "command-example",
+ kind: "user",
+ text: "Explain this repository.",
+});
+if (receipt.status === "rejected") throw new Error(receipt.reason);
+
+await session.stop({ reason: "owner_request", forceAfterMs: 5_000 });
+const result = await session.closed;
+await eventsDone;
+void { result, observedText };
+```
+
+## Built-in execution matrix
+
+All built-ins keep one physical lane for the lifetime of a logical session.
+There is no per-turn built-in fallback.
+
+| Backend | Physical lifetime | Transport | Busy delivery | Terminal owner |
+|---|---|---|---|---|
+| Claude | session | `stdio_stream` / `claude.stream-json.v1` | `safe_boundary_queue` | `vendor_message` |
+| Codex | session | `stdio_rpc` / `codex.app-server.v1` | `safe_boundary_queue` | `transport_request` |
+| Cursor | session | `stdio_rpc` / `cursor.acp.v1` | `next_turn_queue` | `transport_request` |
+| OpenCode | session | `http_sse` / `opencode.v2.service.1.17.20` | `steer` | `transport_request` |
+| Pi | session | `in_process_sdk` / `pi_sdk` | `steer` | `prompt_invocation` |
+
+Pi's runtime behavior did not change in this migration. It already kept one
+SDK session and used prompt/steer/abort/dispose on that session; contract v1
+formalizes that existing persistent behavior as an `in_process_sdk`
+`RuntimeLane`.
+
+## Repository adapter contract v1 migration
+
+Repository adapters must import `ADAPTER_AUTHOR_CONTRACT_VERSION` from
+`@alook/agent-driver/adapter-author` and set every
+`AgentBackendRegistration.contractVersion` to that value (currently the numeric
+literal `1`). Missing, older, and unknown newer versions fail closed before host
+preparation or adapter open.
+
+For contract v1:
+
+- declare `BackendAdapter.execution` with `lifetime`, an opaque
+ `transport.kind`/`transport.protocol`, `wakeStart`, and `terminalOwnership`;
+- make registration capabilities agree with it: `sessionLifetime` maps to
+ `execution.lifetime`, and `midTurnDelivery` describes the lane's real busy
+ delivery behavior;
+- replace one-shot spawn or SDK entry points with `openLane()`, returning one
+ `RuntimeLane` that implements `start`, `send`, `interrupt`, `stop`, and the
+ typed `RuntimeLaneEventMap` listener surface;
+- return a non-empty authoritative receipt from every successful lane
+ admission and emit terminal events with the matching owner identity; do not
+ derive completion from output text or a generic idle/exit signal;
+- report an unavailable required protocol/capability as incompatible or
+ unhealthy. Do not silently fall back to a one-shot runtime.
+
+Package semver and the numeric adapter-author contract version are independent.
+Only an incompatible `/adapter-author` change increments the latter.
+
+## Diagnostics
+
+`session.snapshot().diagnostics` is the exported, read-only diagnostic surface.
+`deliveryPhase` comes from the same logical-session facts that own admission and
+FIFO delivery. Its fixed precedence is admission wait, in-flight steering,
+next-turn queue, compaction, review, tool wait, generic work, then idle. This
+keeps a queued or in-flight delivery from being hidden by a generic working
+state.
+
+The accompanying metrics are cumulative and contain no prompt, response, tool,
+credential, path, or vendor payload:
+
+- physical opens and logical turns;
+- command-admission count and total admission latency in milliseconds;
+- queue-dwell count and total dwell time in milliseconds;
+- SSE reconnect count;
+- resume outcome and terminal-owner kind.
+
+Every numeric metric is finite and non-negative. A latency or dwell value is a
+`*TotalMs` accumulator, not an instantaneous sample.
+
+## Migration from daemon-owned runtimes
+
+Daemon integrations should create one `AgentSession`, attach its event iterator
+before `start`, and keep that session until `closed` settles. Do not spawn a
+backend per turn or infer completion from text, idle notifications, process
+exit, or SDK callbacks that do not own the current terminal receipt. Each
+command settles exactly once through `command_accepted` or `command_failed`; a
+queued receipt is not final.
+
+Cursor moved from one-shot `--print` execution to one persistent ACP session,
+and OpenCode moved from one-shot `run` execution to one authenticated loopback
+v2 service. Pi remains the same persistent SDK session; only its contract shape
+was formalized.
+
+The old daemon trace field `apmPhase` has been removed. Trace consumers should
+read `deliveryPhase` and the allowlisted cumulative metrics projected from the
+session snapshot. The daemon's pending-delivery mode is used only during the
+narrow interval before the driver has observed an admission; after that, the
+snapshot is authoritative.
+
+## Rollback
+
+Cursor and OpenCode migrations are isolated backend commit stacks and can be
+reverted independently without reverting the shared `RuntimeLane` contract:
+revert Cursor's `94b864c8`, `9e9f1697`, then `3ca4ff65`, or OpenCode's
+`c2d98fb4`, then `ba2b2121`, in newest-first order. A rollback must disable the
+affected backend or leave it incompatible/unhealthy if ACP or v2 is unavailable;
+it must not ship, retain, or automatically select the restored one-shot path.
+Do not fall back to `cursor-agent --print` or `opencode run`. Verify the
+unaffected backends and the capability probe before resuming rollout.
diff --git a/src/daemon/agent-driver/RELEASE_NOTES.md b/src/daemon/agent-driver/RELEASE_NOTES.md
new file mode 100644
index 000000000..604cf9d42
--- /dev/null
+++ b/src/daemon/agent-driver/RELEASE_NOTES.md
@@ -0,0 +1,53 @@
+# Release notes
+
+## Persistent built-in sessions and logical diagnostics
+
+- Unified Claude, Codex, Cursor, OpenCode, and Pi behind the persistent
+ `RuntimeLane` contract. Ten sequential root turns now reuse one physical open
+ for every built-in backend.
+- Migrated Cursor from one-shot `--print` execution to a persistent ACP session.
+- Migrated OpenCode from one-shot `run` execution to one authenticated,
+ loopback-only v2 service with durable replay and exact internal SSE reconnect
+ accounting.
+- Pi runtime behavior is unchanged: its existing single persistent SDK session
+ is now formally represented by the contract-v1 `in_process_sdk` `RuntimeLane`.
+- Added shared FIFO stress conformance for active busy delivery, stale-terminal
+ races, and idle bursts. Every command has exactly one final accepted/failed
+ event.
+- Added `AgentSessionSnapshot.diagnostics`, including deterministic logical
+ `deliveryPhase` and cumulative, payload-free operational metrics.
+- Removed the daemon's fixed `apmPhase: "idle"` trace value. FSM traces now
+ project the authoritative logical delivery phase and allowlisted metrics.
+
+### Compatibility
+
+`AgentSessionSnapshot` gains one readonly structured field, `diagnostics`. This
+is an additive change to the private workspace API. There is no `apmPhase`
+compatibility alias.
+Code that constructs snapshot test doubles must add `diagnostics`; code that
+only reads existing snapshot fields remains source compatible.
+
+Adapter behavior and the adapter-author contract version are unchanged by the
+diagnostic surface. The OpenCode reconnect signal is an internal, exact
+allowlisted metric event and is not public telemetry.
+
+### Adapter-author contract v1
+
+Repository adapter registrations must use the exported
+`ADAPTER_AUTHOR_CONTRACT_VERSION` and set `contractVersion: 1`. Adapters must
+declare execution lifetime, opaque transport/protocol, wake behavior, and
+terminal ownership; registration capabilities must match those declarations.
+`openLane()` must return one `RuntimeLane` implementing typed events plus
+`start`, `send`, `interrupt`, and `stop`, with authoritative admission/terminal
+receipts. Missing or unsupported contract versions and declaration mismatches
+fail closed before host preparation/open. Missing required runtime capabilities
+must report incompatible/unhealthy and must not select a one-shot fallback.
+
+### Rollback
+
+The Cursor and OpenCode migrations can be reverted independently. Revert the
+Cursor stack (`94b864c8`, `9e9f1697`, `3ca4ff65`) or OpenCode stack
+(`c2d98fb4`, `ba2b2121`) newest first, without reverting the shared contract.
+Do not ship a rollback that restores or auto-selects `cursor-agent --print`
+or `opencode run`; disable the affected backend or surface it as
+incompatible/unhealthy until its required ACP/v2 capability is available.
diff --git a/src/daemon/agent-driver/api-extractor.adapter-author.json b/src/daemon/agent-driver/api-extractor.adapter-author.json
new file mode 100644
index 000000000..c49fcc001
--- /dev/null
+++ b/src/daemon/agent-driver/api-extractor.adapter-author.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
+ "newlineKind": "lf",
+ "mainEntryPointFilePath": "<projectFolder>/dist/adapter-author.d.ts",
+ "apiReport": {
+ "enabled": true,
+ "reportFileName": "adapter-author",
+ "reportFolder": "<projectFolder>/etc/api",
+ "reportTempFolder": "<projectFolder>/temp/api"
+ },
+ "docModel": { "enabled": false },
+ "dtsRollup": { "enabled": false },
+ "tsdocMetadata": { "enabled": false },
+ "messages": {
+ "extractorMessageReporting": {
+ "ae-missing-release-tag": { "logLevel": "none" },
+ "ae-forgotten-export": { "logLevel": "error", "addToApiReportFile": false }
+ }
+ }
+}
diff --git a/src/daemon/agent-driver/api-extractor.host.json b/src/daemon/agent-driver/api-extractor.host.json
new file mode 100644
index 000000000..3e121c7bc
--- /dev/null
+++ b/src/daemon/agent-driver/api-extractor.host.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
+ "newlineKind": "lf",
+ "mainEntryPointFilePath": "<projectFolder>/dist/host.d.ts",
+ "apiReport": {
+ "enabled": true,
+ "reportFileName": "host",
+ "reportFolder": "<projectFolder>/etc/api",
+ "reportTempFolder": "<projectFolder>/temp/api"
+ },
+ "docModel": { "enabled": false },
+ "dtsRollup": { "enabled": false },
+ "tsdocMetadata": { "enabled": false },
+ "messages": {
+ "extractorMessageReporting": {
+ "ae-missing-release-tag": { "logLevel": "none" },
+ "ae-forgotten-export": { "logLevel": "error", "addToApiReportFile": false }
+ }
+ }
+}
diff --git a/src/daemon/agent-driver/api-extractor.root.json b/src/daemon/agent-driver/api-extractor.root.json
new file mode 100644
index 000000000..de0842f68
--- /dev/null
+++ b/src/daemon/agent-driver/api-extractor.root.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
+ "newlineKind": "lf",
+ "mainEntryPointFilePath": "<projectFolder>/dist/index.d.ts",
+ "apiReport": {
+ "enabled": true,
+ "reportFileName": "root",
+ "reportFolder": "<projectFolder>/etc/api",
+ "reportTempFolder": "<projectFolder>/temp/api"
+ },
+ "docModel": { "enabled": false },
+ "dtsRollup": { "enabled": false },
+ "tsdocMetadata": { "enabled": false },
+ "messages": {
+ "extractorMessageReporting": {
+ "ae-missing-release-tag": { "logLevel": "none" },
+ "ae-forgotten-export": { "logLevel": "error", "addToApiReportFile": false }
+ }
+ }
+}
diff --git a/src/daemon/agent-driver/api-extractor.testing.json b/src/daemon/agent-driver/api-extractor.testing.json
new file mode 100644
index 000000000..8046fb73e
--- /dev/null
+++ b/src/daemon/agent-driver/api-extractor.testing.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
+ "newlineKind": "lf",
+ "mainEntryPointFilePath": "<projectFolder>/dist/testing/index.d.ts",
+ "apiReport": {
+ "enabled": true,
+ "reportFileName": "testing",
+ "reportFolder": "<projectFolder>/etc/api",
+ "reportTempFolder": "<projectFolder>/temp/api"
+ },
+ "docModel": { "enabled": false },
+ "dtsRollup": { "enabled": false },
+ "tsdocMetadata": { "enabled": false },
+ "messages": {
+ "extractorMessageReporting": {
+ "ae-missing-release-tag": { "logLevel": "none" },
+ "ae-forgotten-export": { "logLevel": "error", "addToApiReportFile": false }
+ }
+ }
+}
diff --git a/src/daemon/agent-driver/eslint.config.ts b/src/daemon/agent-driver/eslint.config.ts
new file mode 100644
index 000000000..9fc40e6de
--- /dev/null
+++ b/src/daemon/agent-driver/eslint.config.ts
@@ -0,0 +1,59 @@
+import baseConfig from "../eslint.config.js";
+import { defineConfig } from "eslint/config";
+
+export default defineConfig([
+ ...baseConfig,
+ {
+ files: ["src/adapters/**/*.ts"],
+ rules: {
+ "@typescript-eslint/no-explicit-any": "off",
+ "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }],
+ },
+ },
+ {
+ files: ["src/adapters/**/*.ts"],
+ ignores: ["src/adapters/**/*.test.ts"],
+ rules: {
+ "no-restricted-imports": [
+ "error",
+ {
+ paths: ["child_process", "node:child_process"].map((name) => ({
+ name,
+ message:
+ "Do not import child_process in production adapters. Use the agent-driver process helpers so every agent CLI retains the shared process-tree teardown contract.",
+ })),
+ },
+ ],
+ "no-restricted-syntax": [
+ "error",
+ ...["child_process", "node:child_process"].flatMap((name) => [
+ {
+ selector: `ImportExpression[source.value='${name}']`,
+ message:
+ "Do not dynamically import child_process in production adapters. Use the agent-driver process helpers.",
+ },
+ {
+ selector: `CallExpression[callee.name='require'][arguments.0.value='${name}']`,
+ message:
+ "Do not require child_process in production adapters. Use the agent-driver process helpers.",
+ },
+ ]),
+ ],
+ },
+ },
+ {
+ files: ["src/contract.ts"],
+ rules: {
+ "@typescript-eslint/no-empty-object-type": "off",
+ "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }],
+ },
+ },
+ {
+ files: ["**/*.test.ts"],
+ rules: {
+ "@typescript-eslint/no-explicit-any": "off",
+ "@typescript-eslint/no-unused-vars": "off",
+ "prefer-const": "off",
+ },
+ },
+]);
diff --git a/src/daemon/agent-driver/etc/api/adapter-author.api.md b/src/daemon/agent-driver/etc/api/adapter-author.api.md
new file mode 100644
index 000000000..dc209f657
--- /dev/null
+++ b/src/daemon/agent-driver/etc/api/adapter-author.api.md
@@ -0,0 +1,1068 @@
+## API Report File for "@alook/agent-driver"
+
+> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
+
+```ts
+
+// @public
+export const ADAPTER_AUTHOR_CONTRACT_VERSION: 1;
+
+// @public (undocumented)
+export type AdapterEvent = {
+ kind: "session_init";
+ sessionId: string;
+} | {
+ kind: "thinking";
+ text: string;
+} | {
+ kind: "text";
+ text: string;
+} | {
+ kind: "tool_call";
+ name: string;
+ input: unknown;
+} | {
+ kind: "tool_output";
+ name: string;
+} | {
+ kind: "compaction_started";
+} | {
+ kind: "compaction_finished";
+} | {
+ kind: "review_started";
+} | {
+ kind: "review_finished";
+} | {
+ kind: "internal_progress";
+ source?: string;
+ itemType?: string;
+ payloadBytes?: number;
+} | {
+ kind: "runtime_diagnostic";
+ severity?: string;
+ source?: string;
+ message: string;
+} | {
+ kind: "runtime_metric";
+ name: "sse_reconnect";
+ increment: 1;
+} | {
+ kind: "turn_owner";
+ receipt: string;
+} | {
+ kind: "turn_end";
+ sessionId?: string;
+ turnOwner?: string;
+} | {
+ kind: "error";
+ message: string;
+} | {
+ kind: "telemetry";
+ name: "token_usage" | "rate_limits";
+ source: string;
+ usageKind?: string;
+ attrs: Record<string, unknown>;
+};
+
+// @public (undocumented)
+export interface AdapterLaunchConfig<Config = BackendConfig> {
+ // (undocumented)
+ agentDiscriminator?: string;
+ // (undocumented)
+ agentHandle?: string;
+ // (undocumented)
+ agentName?: string;
+ // (undocumented)
+ description?: string;
+ // (undocumented)
+ ownerHandle?: string;
+ // (undocumented)
+ runtimeConfig?: Config;
+ // (undocumented)
+ runtimeContext?: AdapterRuntimeContext;
+ // (undocumented)
+ sessionId?: string;
+}
+
+// @public (undocumented)
+export interface AdapterLaunchContext<Id extends string = BuiltinBackendId, Config = BackendConfig> {
+ // (undocumented)
+ agentId: string;
+ // (undocumented)
+ backend: Id;
+ // (undocumented)
+ config: AdapterLaunchConfig<Config>;
+ // (undocumented)
+ launchId: string;
+ // (undocumented)
+ prepared: PreparedExecutionResource;
+ // (undocumented)
+ prompt: string;
+ // (undocumented)
+ standingPrompt: string;
+ // (undocumented)
+ workingDirectory: string;
+}
+
+// @public (undocumented)
+export interface AdapterRuntimeContext {
+ // (undocumented)
+ agentId: string;
+ // (undocumented)
+ computerId: string;
+ // (undocumented)
+ computerName: string;
+ // (undocumented)
+ daemonVersion: string;
+ // (undocumented)
+ hostname: string;
+ // (undocumented)
+ os: string;
+ // (undocumented)
+ serverId: string;
+ // (undocumented)
+ workspacePath: string;
+}
+
+// @public (undocumented)
+export interface AdapterTransport {
+ // (undocumented)
+ readonly kind: WellKnownTransportKind | (string & {});
+ // (undocumented)
+ readonly metadata?: Readonly<Record<string, JsonValue>>;
+ // (undocumented)
+ readonly protocol: string;
+}
+
+// @public (undocumented)
+export interface AgentBackendRegistration<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+ // (undocumented)
+ readonly contractVersion: 1;
+ // (undocumented)
+ createAdapter(): BackendAdapter<Id, ConfigOf<Specs, Id>>;
+ // (undocumented)
+ readonly id: Id;
+}
+
+// @public (undocumented)
+export type AgentBackendRegistrationOf<Specs> = {
+ [Id in BackendId<Specs>]: AgentBackendRegistration<Specs, Id>;
+}[BackendId<Specs>];
+
+// @public (undocumented)
+export interface AgentDriverError {
+ // (undocumented)
+ readonly category: "runtime_unavailable" | "authentication" | "configuration" | "protocol" | "process" | "sdk" | "timeout" | "cancelled" | "buffer_overflow" | "internal";
+ // (undocumented)
+ readonly code: string;
+ // (undocumented)
+ readonly details?: JsonObject;
+ // (undocumented)
+ readonly message: string;
+ // (undocumented)
+ readonly retryable: boolean;
+}
+
+// @public (undocumented)
+export interface AgentDriverHost {
+ // (undocumented)
+ createId(): string;
+ // (undocumented)
+ now(): number;
+ // (undocumented)
+ onRawOutput(event: RawOutputEvent): void;
+ // (undocumented)
+ prepareExecution(input: PrepareExecutionInput): Promise<PrepareExecutionResult>;
+}
+
+// @public (undocumented)
+export interface AgentDriverRegistry<Specs> {
+ // (undocumented)
+ readonly backendIds: readonly BackendId<Specs>[];
+ // (undocumented)
+ get<Id extends BackendId<Specs>>(id: Id): AgentBackendRegistration<Specs, Id>;
+}
+
+// @public (undocumented)
+export interface AgentDriverSdk<Specs = BuiltinBackendSpecs> {
+ // (undocumented)
+ readonly backendIds: readonly BackendId<Specs>[];
+ // (undocumented)
+ open<Id extends BackendId<Specs>>(input: OpenSessionInput<Specs, Id>): Promise<OpenSessionResult<Specs, Id>>;
+ // (undocumented)
+ probe<Id extends BackendId<Specs>>(input: ProbeInput<Specs, Id>): Promise<BackendProbe<CapabilitiesOf<Specs, Id>>>;
+}
+
+// @public (undocumented)
+export type AgentEvent<Specs, Id extends BackendId<Specs>> = AgentEventEnvelope & (CoreAgentEventPayload | ExtraEventOf<Specs, Id>);
+
+// @public (undocumented)
+export interface AgentEventEnvelope {
+ // (undocumented)
+ readonly at: number;
+ // (undocumented)
+ readonly sequence: number;
+ // (undocumented)
+ readonly sessionInstanceId: string;
+}
+
+// @public (undocumented)
+export interface AgentEventStream<Event> extends AsyncIterable<Event> {
+ // (undocumented)
+ readonly maxBufferedBytes: 4_194_304;
+}
+
+// @public (undocumented)
+export interface AgentInstructions {
+ // (undocumented)
+ readonly content: string;
+ // (undocumented)
+ readonly format: "markdown";
+}
+
+// @public (undocumented)
+export interface AgentLaunchContext {
+ // (undocumented)
+ readonly instructions: AgentInstructions;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly resumeSessionId?: string;
+ // (undocumented)
+ readonly workingDirectory: string;
+}
+
+// @public (undocumented)
+export interface AgentMessage {
+ // (undocumented)
+ readonly id: string;
+ // (undocumented)
+ readonly kind: "user" | "system" | "recovery";
+ // (undocumented)
+ readonly sequence?: number;
+ // (undocumented)
+ readonly text: string;
+}
+
+// @public (undocumented)
+export interface AgentSession<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+ // (undocumented)
+ readonly closed: Promise<AgentSessionResult>;
+ // (undocumented)
+ readonly events: AgentEventStream<AgentEvent<Specs, Id>>;
+ // (undocumented)
+ interrupt(input: {
+ readonly requestId: string;
+ readonly reason: string;
+ }): Promise<InterruptResult>;
+ // (undocumented)
+ invokeExtension<Name extends ExtensionNames<Specs, Id>>(name: Name, input: ExtensionInput<Specs, Id, Name>): Promise<ExtensionResult<ExtensionOutput<Specs, Id, Name>>>;
+ // (undocumented)
+ send(message: AgentMessage): Promise<DeliveryReceipt>;
+ // (undocumented)
+ readonly sessionInstanceId: string;
+ // (undocumented)
+ snapshot(): AgentSessionSnapshot;
+ // (undocumented)
+ start(message: AgentMessage): Promise<DeliveryReceipt>;
+ // (undocumented)
+ stop(input: StopInput): Promise<StopReceipt>;
+}
+
+// @public (undocumented)
+export type AgentSessionResult = {
+ readonly outcome: "stopped";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly exitCode?: number | null;
+ readonly signal?: string | null;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "crashed";
+ readonly requested: false;
+ readonly backendSessionId?: string;
+ readonly exitCode: number | null;
+ readonly signal: string | null;
+ readonly error?: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "failed_to_start";
+ readonly requested: false;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "forced";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+};
+
+// @public (undocumented)
+export interface AgentSessionSnapshot {
+ // (undocumented)
+ readonly activeTurn?: {
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+ };
+ // (undocumented)
+ readonly backendSessionId?: string;
+ // (undocumented)
+ readonly diagnostics: {
+ readonly deliveryPhase: "idle" | "admission_wait" | "steering" | "next_turn_queued" | "compacting" | "reviewing" | "tool_wait" | "working";
+ readonly metrics: {
+ readonly physicalOpenCount: number;
+ readonly turnCount: number;
+ readonly commandAdmissionCount: number;
+ readonly commandAdmissionLatencyTotalMs: number;
+ readonly queueDwellCount: number;
+ readonly queueDwellTotalMs: number;
+ readonly sseReconnectCount: number;
+ readonly resumeOutcome: "not_requested" | "pending" | "resumed" | "reset_required" | "failed";
+ readonly terminalOwnerKind: "transport_request" | "vendor_message" | "prompt_invocation" | "lane_generation";
+ };
+ };
+ // (undocumented)
+ readonly lastEventSequence: number;
+ // (undocumented)
+ readonly queuedCommands: readonly {
+ readonly commandId: string;
+ readonly kind: AgentMessage["kind"];
+ }[];
+ // (undocumented)
+ readonly sessionInstanceId: string;
+ // (undocumented)
+ readonly state: "new" | "awaiting_first_message" | "starting" | "idle" | "working" | "stopping" | "closed";
+}
+
+// @public (undocumented)
+export type AgentTurnResult = {
+ readonly outcome: "success";
+ readonly backendSessionId: string;
+} | {
+ readonly outcome: "interrupted";
+ readonly backendSessionId?: string;
+} | {
+ readonly outcome: "failed";
+ readonly backendSessionId?: string;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface BackendAdapter<Id extends string = BuiltinBackendId, Config = BackendConfig> {
+ beginTurn?(): string;
+ // (undocumented)
+ readonly execution: BackendExecution;
+ // (undocumented)
+ readonly id: Id;
+ // (undocumented)
+ readonly instructionDelivery: {
+ readonly kind: "native";
+ } | {
+ readonly kind: "workspace_file";
+ readonly canonical: string;
+ readonly aliases: readonly string[];
+ };
+ // (undocumented)
+ openLane(ctx: AdapterLaunchContext<Id, Config>, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane>;
+ // (undocumented)
+ probe(command?: string): ProbeResult | Promise<ProbeResult>;
+}
+
+// @public (undocumented)
+export interface BackendCapabilities {
+ // (undocumented)
+ readonly commandOverride: boolean;
+ // (undocumented)
+ readonly disallowedTools: boolean;
+ // (undocumented)
+ readonly fastMode: boolean;
+ // (undocumented)
+ readonly interrupt: boolean;
+ // (undocumented)
+ readonly midTurnDelivery: "steer" | "safe_boundary_queue" | "next_turn_queue";
+ // (undocumented)
+ readonly modelSelection: "launchable" | "suggestion_only" | "unsupported";
+ // (undocumented)
+ readonly providerConfiguration: boolean;
+ // (undocumented)
+ readonly reasoningEffort: boolean;
+ // (undocumented)
+ readonly resume: "by_id" | "none";
+ // (undocumented)
+ readonly sessionLifetime: "persistent" | "per_turn";
+}
+
+// @public (undocumented)
+export type BackendConfig = ClaudeConfig | CodexConfig | CursorConfig | OpenCodeConfig | PiConfig;
+
+// @public (undocumented)
+export interface BackendExecution {
+ // (undocumented)
+ readonly lifetime: "session" | "turn";
+ // (undocumented)
+ readonly terminalOwnership: TerminalOwnership;
+ // (undocumented)
+ readonly transport: AdapterTransport;
+ // (undocumented)
+ readonly wakeStart: "immediate" | "deferred";
+}
+
+// @public (undocumented)
+export interface BackendExtensionSpec<Input, Output> {
+ // (undocumented)
+ readonly input: Input;
+ // (undocumented)
+ readonly output: Output;
+}
+
+// @public (undocumented)
+export type BackendId<Specs> = Extract<keyof Specs, string>;
+
+// @public (undocumented)
+export type BackendProbe<Capabilities> = {
+ readonly status: "healthy";
+ readonly version?: string;
+ readonly capabilities: Capabilities;
+} | {
+ readonly status: "unhealthy";
+ readonly error: AgentDriverError;
+ readonly capabilities: Capabilities;
+};
+
+// @public (undocumented)
+export interface BackendTypeSpec<Config, Capabilities, Extensions, ExtraEvent> {
+ // (undocumented)
+ readonly capabilities: Capabilities;
+ // (undocumented)
+ readonly config: Config;
+ // (undocumented)
+ readonly extensions: Extensions;
+ // (undocumented)
+ readonly extraEvent: ExtraEvent;
+}
+
+// @public (undocumented)
+export interface BaseBackendConfig {
+ // (undocumented)
+ readonly command?: string;
+ // (undocumented)
+ readonly environment?: Readonly<Record<string, string>>;
+}
+
+// @public (undocumented)
+export type BuiltinBackendId = "claude" | "codex" | "cursor" | "opencode" | "pi";
+
+// @public (undocumented)
+export interface BuiltinBackendSpecs {
+ // (undocumented)
+ readonly claude: BackendTypeSpec<ClaudeConfig, ClaudeCapabilities, {}, never>;
+ // (undocumented)
+ readonly codex: BackendTypeSpec<CodexConfig, CodexCapabilities, {}, never>;
+ // (undocumented)
+ readonly cursor: BackendTypeSpec<CursorConfig, CursorCapabilities, {}, never>;
+ // (undocumented)
+ readonly opencode: BackendTypeSpec<OpenCodeConfig, OpenCodeCapabilities, {}, never>;
+ // (undocumented)
+ readonly pi: BackendTypeSpec<PiConfig, PiCapabilities, {}, never>;
+}
+
+// @public (undocumented)
+export type CapabilitiesOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer Caps, infer _Extensions, infer _Event> ? Caps : never;
+
+// @public (undocumented)
+export type ClaudeCapabilities = FixedCapabilities<true, true, true, true, true, "safe_boundary_queue", "persistent">;
+
+// @public (undocumented)
+export interface ClaudeConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly disallowedTools?: string;
+ // (undocumented)
+ readonly mode: "default" | "fast";
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly provider: ClaudeProvider;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type ClaudeProvider = DefaultProvider | {
+ readonly kind: "custom_endpoint";
+ readonly apiUrl: string;
+ readonly apiKey: string;
+};
+
+// @public (undocumented)
+export type CodexCapabilities = FixedCapabilities<false, true, true, false, true, "safe_boundary_queue", "persistent">;
+
+// @public (undocumented)
+export interface CodexConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly mode: "default" | "fast";
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type ConfigOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer Config, infer _Caps, infer _Extensions, infer _Event> ? Config : never;
+
+// @public (undocumented)
+export type CoreAgentEventPayload = {
+ readonly type: "session_started";
+ readonly backendSessionId: string;
+} | {
+ readonly type: "command_queued";
+ readonly commandId: string;
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+} | {
+ readonly type: "command_accepted";
+ readonly commandId: string;
+ readonly turnId: string;
+ readonly delivery: "prompt" | "steer";
+} | {
+ readonly type: "command_failed";
+ readonly commandId: string;
+ readonly turnId?: string;
+ readonly error: AgentDriverError;
+} | {
+ readonly type: "turn_started";
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+} | {
+ readonly type: "thinking_delta";
+ readonly turnId: string;
+ readonly text: string;
+} | {
+ readonly type: "text_delta";
+ readonly turnId: string;
+ readonly text: string;
+} | {
+ readonly type: "tool_started";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly input: JsonValue;
+} | {
+ readonly type: "tool_finished";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly output?: JsonValue;
+} | {
+ readonly type: "compaction_started";
+ readonly turnId: string;
+} | {
+ readonly type: "compaction_finished";
+ readonly turnId: string;
+} | {
+ readonly type: "review_started";
+ readonly turnId: string;
+} | {
+ readonly type: "review_finished";
+ readonly turnId: string;
+} | {
+ readonly type: "internal_progress";
+ readonly turnId?: string;
+ readonly source?: string;
+ readonly itemType?: string;
+ readonly payloadBytes?: number;
+} | {
+ readonly type: "diagnostic";
+ readonly turnId?: string;
+ readonly severity: "debug" | "info" | "warning" | "error";
+ readonly source?: string;
+ readonly message: string;
+} | {
+ readonly type: "token_usage";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly usage: TokenUsage;
+ readonly details: JsonObject;
+} | {
+ readonly type: "rate_limits";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly details: JsonObject;
+} | {
+ readonly type: "turn_completed";
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+ readonly result: AgentTurnResult;
+} | {
+ readonly type: "session_failed";
+ readonly error: AgentDriverError;
+} | {
+ readonly type: "session_closed";
+ readonly result: AgentSessionResult;
+};
+
+// @public (undocumented)
+export function createAgentDriverRegistry<Specs>(registrations: readonly AgentBackendRegistrationOf<Specs>[]): AgentDriverRegistry<Specs>;
+
+// @public (undocumented)
+export interface CreateAgentDriverSdkOptions {
+ // (undocumented)
+ readonly host?: AgentDriverHost;
+ // (undocumented)
+ readonly hostReleaseTimeoutMs?: number;
+}
+
+// @public (undocumented)
+export function createAgentDriverSdkWithRegistry<Specs>(options: CreateAgentDriverSdkOptions & {
+ readonly registry: AgentDriverRegistry<Specs>;
+}): AgentDriverSdk<Specs>;
+
+// @public (undocumented)
+export function createBuiltinAgentDriverRegistry(): AgentDriverRegistry<BuiltinBackendSpecs>;
+
+// @public (undocumented)
+export type CursorCapabilities = FixedCapabilities<false, false, false, false, true, "next_turn_queue", "persistent">;
+
+// @public (undocumented)
+export type CursorConfig = ModelBackendConfig;
+
+// @public (undocumented)
+export interface DefaultAgentDriverHostOptions {
+ // (undocumented)
+ readonly environment?: Readonly<Record<string, string | undefined>>;
+ // (undocumented)
+ readonly onRawOutput?: (event: RawOutputEvent) => void;
+}
+
+// @public (undocumented)
+export type DefaultProvider = {
+ readonly kind: "default";
+};
+
+// @public (undocumented)
+export type DeliveryReceipt = {
+ readonly status: "accepted";
+ readonly delivery: "prompt" | "steer";
+ readonly commandId: string;
+ readonly turnId: string;
+} | {
+ readonly status: "queued";
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+ readonly commandId: string;
+} | {
+ readonly status: "rejected";
+ readonly reason: "closed" | "unsupported" | "invalid_input" | "runtime_unavailable" | "already_started" | "not_started" | "duplicate_conflict";
+ readonly error?: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface EncodeMessageOptions {
+ // (undocumented)
+ mode?: InputMode;
+}
+
+// @public (undocumented)
+export type ExtensionInput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> = ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer Input, infer _Output> ? Input : never;
+
+// @public (undocumented)
+export type ExtensionNames<Specs, Id extends BackendId<Specs>> = Extract<keyof ExtensionsOf<Specs, Id>, string>;
+
+// @public (undocumented)
+export type ExtensionOutput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> = ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer _Input, infer Output> ? Output : never;
+
+// @public (undocumented)
+export type ExtensionResult<Output> = {
+ readonly ok: true;
+ readonly value: Output;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type ExtensionsOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer Extensions, infer _Event> ? Extensions : never;
+
+// @public (undocumented)
+export type ExtraEventOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer _Extensions, infer Event> ? Event : never;
+
+// @public (undocumented)
+export type FixedCapabilities<Provider extends boolean, Reasoning extends boolean, Fast extends boolean, Tools extends boolean, Command extends boolean, Delivery extends BackendCapabilities["midTurnDelivery"], Lifetime extends BackendCapabilities["sessionLifetime"]> = BackendCapabilities & {
+ readonly modelSelection: "launchable";
+ readonly providerConfiguration: Provider;
+ readonly reasoningEffort: Reasoning;
+ readonly fastMode: Fast;
+ readonly disallowedTools: Tools;
+ readonly commandOverride: Command;
+ readonly resume: "by_id";
+ readonly sessionLifetime: Lifetime;
+ readonly midTurnDelivery: Delivery;
+ readonly interrupt: true;
+};
+
+// @public (undocumented)
+export type HostCleanupResult = {
+ readonly status: "not_acquired";
+} | {
+ readonly status: "released";
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+} | {
+ readonly status: "timed_out";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type InputMode = "busy" | "idle";
+
+// @public (undocumented)
+export type InterruptResult = {
+ readonly status: "accepted";
+ readonly requestId: string;
+ readonly turnId: string;
+} | {
+ readonly status: "not_running";
+} | {
+ readonly status: "unsupported";
+} | {
+ readonly status: "closed";
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type JsonObject = {
+ readonly [key: string]: JsonValue;
+};
+
+// @public (undocumented)
+export type JsonPrimitive = string | number | boolean | null;
+
+// @public (undocumented)
+export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];
+
+// @public (undocumented)
+export type LaneAdmission = {
+ readonly ok: true;
+ readonly acceptedAs: "prompt" | "steer";
+ readonly receipt: string;
+} | {
+ readonly ok: false;
+ readonly reason: string;
+ readonly error?: string;
+};
+
+// @public (undocumented)
+export interface LaneInterruptInput {
+ // (undocumented)
+ readonly reason?: string;
+ // (undocumented)
+ readonly requestId?: string;
+}
+
+// @public (undocumented)
+export interface LaneSendInput extends LaneStartInput {
+ // (undocumented)
+ readonly mode: InputMode;
+}
+
+// @public (undocumented)
+export interface LaneStartInput {
+ // (undocumented)
+ readonly sessionId?: string;
+ // (undocumented)
+ readonly terminalOwner?: string;
+ // (undocumented)
+ readonly text: string;
+}
+
+// @public (undocumented)
+export interface LaneStopInput {
+ // (undocumented)
+ readonly forceAfterMs?: number;
+ // (undocumented)
+ readonly reason?: string;
+ // (undocumented)
+ readonly signal?: "SIGTERM" | "SIGINT" | "SIGKILL";
+}
+
+// @public (undocumented)
+export interface ModelBackendConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly model: ModelSelection;
+}
+
+// @public (undocumented)
+export type ModelSelection = {
+ readonly kind: "default";
+} | {
+ readonly kind: "named";
+ readonly name: string;
+} | {
+ readonly kind: "custom";
+ readonly name: string;
+};
+
+// @public (undocumented)
+export type OpenCodeCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;
+
+// @public (undocumented)
+export type OpenCodeConfig = ModelBackendConfig;
+
+// @public (undocumented)
+export interface OpenSessionInput<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly config: ConfigOf<Specs, Id>;
+ // (undocumented)
+ readonly launch: AgentLaunchContext;
+}
+
+// @public (undocumented)
+export type OpenSessionResult<Specs, Id extends BackendId<Specs>> = {
+ readonly ok: true;
+ readonly session: AgentSession<Specs, Id>;
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type PiCapabilities = FixedCapabilities<true, true, false, false, false, "steer", "persistent">;
+
+// @public (undocumented)
+export interface PiConfig extends Omit<BaseBackendConfig, "command"> {
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly provider: PiProvider;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type PiProvider = DefaultProvider | {
+ readonly kind: "builtin";
+ readonly providerId: "google" | "openai" | "openrouter" | (string & {});
+ readonly apiKey: string;
+};
+
+// @public (undocumented)
+export interface PreparedExecutionResource {
+ // (undocumented)
+ readonly environmentLayers: Readonly<Record<"base" | "hostStatic" | "identityProtected" | "platformProtected" | "runtimeProtected" | "networkProtected" | "credentialSensitive", Readonly<Record<string, string | undefined>>>>;
+ // (undocumented)
+ readonly executablePath?: string;
+ // (undocumented)
+ release(input: {
+ readonly reason: "normal" | "failed_start" | "crash" | "requested_stop" | "consumer_closed";
+ readonly signal: AbortSignal;
+ readonly deadlineAt: number;
+ }): Promise<void>;
+}
+
+// @public (undocumented)
+export interface PrepareExecutionInput {
+ // (undocumented)
+ readonly backend: string;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly workingDirectory: string;
+}
+
+// @public (undocumented)
+export type PrepareExecutionResult = {
+ readonly ok: true;
+ readonly resource: PreparedExecutionResource;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface ProbeInput<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly command?: string;
+}
+
+// @public (undocumented)
+export interface ProbeResult {
+ // (undocumented)
+ lastError?: string;
+ // (undocumented)
+ status: "healthy" | "unhealthy";
+ // (undocumented)
+ version?: string;
+}
+
+// @public (undocumented)
+export interface RawOutputEvent {
+ // (undocumented)
+ readonly backend: string;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly stream: "stdout" | "stderr";
+ // (undocumented)
+ readonly text: string;
+}
+
+// @public (undocumented)
+export type ReasoningEffort = "low" | "medium" | "high";
+
+// @public (undocumented)
+export interface RuntimeLane {
+ // (undocumented)
+ readonly currentSessionId: string | null;
+ // (undocumented)
+ interrupt(input: LaneInterruptInput): Promise<boolean>;
+ // (undocumented)
+ on<K extends keyof RuntimeLaneEventMap>(event: K, listener: (value: RuntimeLaneEventMap[K]) => void): void;
+ // (undocumented)
+ send(input: LaneSendInput): Promise<LaneAdmission>;
+ // (undocumented)
+ start(input: LaneStartInput): Promise<LaneAdmission>;
+ // (undocumented)
+ stop(input: LaneStopInput): Promise<void>;
+}
+
+// @public (undocumented)
+export interface RuntimeLaneEventMap {
+ // (undocumented)
+ readonly error: unknown;
+ // (undocumented)
+ readonly exit: RuntimeLaneExit;
+ // (undocumented)
+ readonly runtime_event: AdapterEvent;
+ // (undocumented)
+ readonly stderr: string;
+}
+
+// @public (undocumented)
+export interface RuntimeLaneExit {
+ // (undocumented)
+ readonly code: number | null;
+ // (undocumented)
+ readonly reason: "requested" | "runtime_exit";
+ // (undocumented)
+ readonly signal: string | null;
+}
+
+// @public (undocumented)
+export interface RuntimeLaneOpenOptions {
+ // (undocumented)
+ readonly onRawStdoutLine?: (line: string) => void;
+}
+
+// @public (undocumented)
+export interface SpawnedProcess {
+ // (undocumented)
+ process: SpawnedProcessHandle;
+}
+
+// @public (undocumented)
+export interface SpawnedProcessHandle {
+ // (undocumented)
+ readonly exitCode: number | null;
+ // (undocumented)
+ kill(signal?: "SIGTERM" | "SIGINT" | "SIGKILL"): boolean;
+ // (undocumented)
+ on(event: "error", listener: (error: unknown) => void): unknown;
+ // (undocumented)
+ on(event: "exit" | "close", listener: (code: number | null, signal: string | null) => void): unknown;
+ // (undocumented)
+ readonly pid?: number;
+ // (undocumented)
+ readonly signalCode: string | null;
+ // (undocumented)
+ readonly stderr?: {
+ on(event: "data", listener: (chunk: {
+ toString(): string;
+ }) => void): unknown;
+ } | null;
+ // (undocumented)
+ readonly stdin?: {
+ readonly destroyed?: boolean;
+ readonly writable?: boolean;
+ readonly writableEnded?: boolean;
+ write(chunk: string): unknown;
+ } | null;
+ // (undocumented)
+ readonly stdout?: {
+ on(event: "data", listener: (chunk: {
+ toString(): string;
+ }) => void): unknown;
+ } | null;
+}
+
+// @public (undocumented)
+export interface StopInput {
+ // (undocumented)
+ readonly forceAfterMs: number;
+ // (undocumented)
+ readonly reason: "owner_request" | "idle_timeout" | "stalled" | "shutdown" | "reset";
+}
+
+// @public (undocumented)
+export type StopReceipt = {
+ readonly status: "accepted";
+ readonly requestId: string;
+} | {
+ readonly status: "already_stopping";
+ readonly requestId: string;
+} | {
+ readonly status: "closed";
+ readonly result: AgentSessionResult;
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type TerminalOwnership = "transport_request" | "vendor_message" | "prompt_invocation" | "lane_generation";
+
+// @public (undocumented)
+export interface TokenUsage {
+ // (undocumented)
+ readonly cachedInputTokens?: number;
+ // (undocumented)
+ readonly inputTokens?: number;
+ // (undocumented)
+ readonly outputTokens?: number;
+ // (undocumented)
+ readonly reasoningTokens?: number;
+ // (undocumented)
+ readonly totalTokens?: number;
+}
+
+// @public (undocumented)
+export interface VendorSessionHandle {
+ // (undocumented)
+ abort?(): void | Promise<void>;
+ // (undocumented)
+ dispose?(): void | Promise<void>;
+ // (undocumented)
+ readonly isStreaming?: boolean;
+ // (undocumented)
+ prompt(text: string): void | Promise<void>;
+ // (undocumented)
+ steer(text: string): void | Promise<void>;
+}
+
+// @public (undocumented)
+export type WellKnownTransportKind = "stdio_stream" | "stdio_rpc" | "http_sse" | "in_process_sdk" | "one_shot_cli";
+
+// (No @packageDocumentation comment for this package)
+
+```
diff --git a/src/daemon/agent-driver/etc/api/host.api.md b/src/daemon/agent-driver/etc/api/host.api.md
new file mode 100644
index 000000000..0d41d3a2b
--- /dev/null
+++ b/src/daemon/agent-driver/etc/api/host.api.md
@@ -0,0 +1,706 @@
+## API Report File for "@alook/agent-driver"
+
+> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
+
+```ts
+
+// @public (undocumented)
+export interface AgentDriverError {
+ // (undocumented)
+ readonly category: "runtime_unavailable" | "authentication" | "configuration" | "protocol" | "process" | "sdk" | "timeout" | "cancelled" | "buffer_overflow" | "internal";
+ // (undocumented)
+ readonly code: string;
+ // (undocumented)
+ readonly details?: JsonObject;
+ // (undocumented)
+ readonly message: string;
+ // (undocumented)
+ readonly retryable: boolean;
+}
+
+// @public (undocumented)
+export interface AgentDriverHost {
+ // (undocumented)
+ createId(): string;
+ // (undocumented)
+ now(): number;
+ // (undocumented)
+ onRawOutput(event: RawOutputEvent): void;
+ // (undocumented)
+ prepareExecution(input: PrepareExecutionInput): Promise<PrepareExecutionResult>;
+}
+
+// @public (undocumented)
+export interface AgentDriverSdk<Specs = BuiltinBackendSpecs> {
+ // (undocumented)
+ readonly backendIds: readonly BackendId<Specs>[];
+ // (undocumented)
+ open<Id extends BackendId<Specs>>(input: OpenSessionInput<Specs, Id>): Promise<OpenSessionResult<Specs, Id>>;
+ // (undocumented)
+ probe<Id extends BackendId<Specs>>(input: ProbeInput<Specs, Id>): Promise<BackendProbe<CapabilitiesOf<Specs, Id>>>;
+}
+
+// @public (undocumented)
+export type AgentEvent<Specs, Id extends BackendId<Specs>> = AgentEventEnvelope & (CoreAgentEventPayload | ExtraEventOf<Specs, Id>);
+
+// @public (undocumented)
+export interface AgentEventEnvelope {
+ // (undocumented)
+ readonly at: number;
+ // (undocumented)
+ readonly sequence: number;
+ // (undocumented)
+ readonly sessionInstanceId: string;
+}
+
+// @public (undocumented)
+export interface AgentEventStream<Event> extends AsyncIterable<Event> {
+ // (undocumented)
+ readonly maxBufferedBytes: 4_194_304;
+}
+
+// @public (undocumented)
+export interface AgentInstructions {
+ // (undocumented)
+ readonly content: string;
+ // (undocumented)
+ readonly format: "markdown";
+}
+
+// @public (undocumented)
+export interface AgentLaunchContext {
+ // (undocumented)
+ readonly instructions: AgentInstructions;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly resumeSessionId?: string;
+ // (undocumented)
+ readonly workingDirectory: string;
+}
+
+// @public (undocumented)
+export interface AgentMessage {
+ // (undocumented)
+ readonly id: string;
+ // (undocumented)
+ readonly kind: "user" | "system" | "recovery";
+ // (undocumented)
+ readonly sequence?: number;
+ // (undocumented)
+ readonly text: string;
+}
+
+// @public (undocumented)
+export interface AgentSession<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+ // (undocumented)
+ readonly closed: Promise<AgentSessionResult>;
+ // (undocumented)
+ readonly events: AgentEventStream<AgentEvent<Specs, Id>>;
+ // (undocumented)
+ interrupt(input: {
+ readonly requestId: string;
+ readonly reason: string;
+ }): Promise<InterruptResult>;
+ // (undocumented)
+ invokeExtension<Name extends ExtensionNames<Specs, Id>>(name: Name, input: ExtensionInput<Specs, Id, Name>): Promise<ExtensionResult<ExtensionOutput<Specs, Id, Name>>>;
+ // (undocumented)
+ send(message: AgentMessage): Promise<DeliveryReceipt>;
+ // (undocumented)
+ readonly sessionInstanceId: string;
+ // (undocumented)
+ snapshot(): AgentSessionSnapshot;
+ // (undocumented)
+ start(message: AgentMessage): Promise<DeliveryReceipt>;
+ // (undocumented)
+ stop(input: StopInput): Promise<StopReceipt>;
+}
+
+// @public (undocumented)
+export type AgentSessionResult = {
+ readonly outcome: "stopped";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly exitCode?: number | null;
+ readonly signal?: string | null;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "crashed";
+ readonly requested: false;
+ readonly backendSessionId?: string;
+ readonly exitCode: number | null;
+ readonly signal: string | null;
+ readonly error?: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "failed_to_start";
+ readonly requested: false;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "forced";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+};
+
+// @public (undocumented)
+export interface AgentSessionSnapshot {
+ // (undocumented)
+ readonly activeTurn?: {
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+ };
+ // (undocumented)
+ readonly backendSessionId?: string;
+ // (undocumented)
+ readonly diagnostics: {
+ readonly deliveryPhase: "idle" | "admission_wait" | "steering" | "next_turn_queued" | "compacting" | "reviewing" | "tool_wait" | "working";
+ readonly metrics: {
+ readonly physicalOpenCount: number;
+ readonly turnCount: number;
+ readonly commandAdmissionCount: number;
+ readonly commandAdmissionLatencyTotalMs: number;
+ readonly queueDwellCount: number;
+ readonly queueDwellTotalMs: number;
+ readonly sseReconnectCount: number;
+ readonly resumeOutcome: "not_requested" | "pending" | "resumed" | "reset_required" | "failed";
+ readonly terminalOwnerKind: "transport_request" | "vendor_message" | "prompt_invocation" | "lane_generation";
+ };
+ };
+ // (undocumented)
+ readonly lastEventSequence: number;
+ // (undocumented)
+ readonly queuedCommands: readonly {
+ readonly commandId: string;
+ readonly kind: AgentMessage["kind"];
+ }[];
+ // (undocumented)
+ readonly sessionInstanceId: string;
+ // (undocumented)
+ readonly state: "new" | "awaiting_first_message" | "starting" | "idle" | "working" | "stopping" | "closed";
+}
+
+// @public (undocumented)
+export type AgentTurnResult = {
+ readonly outcome: "success";
+ readonly backendSessionId: string;
+} | {
+ readonly outcome: "interrupted";
+ readonly backendSessionId?: string;
+} | {
+ readonly outcome: "failed";
+ readonly backendSessionId?: string;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface BackendCapabilities {
+ // (undocumented)
+ readonly commandOverride: boolean;
+ // (undocumented)
+ readonly disallowedTools: boolean;
+ // (undocumented)
+ readonly fastMode: boolean;
+ // (undocumented)
+ readonly interrupt: boolean;
+ // (undocumented)
+ readonly midTurnDelivery: "steer" | "safe_boundary_queue" | "next_turn_queue";
+ // (undocumented)
+ readonly modelSelection: "launchable" | "suggestion_only" | "unsupported";
+ // (undocumented)
+ readonly providerConfiguration: boolean;
+ // (undocumented)
+ readonly reasoningEffort: boolean;
+ // (undocumented)
+ readonly resume: "by_id" | "none";
+ // (undocumented)
+ readonly sessionLifetime: "persistent" | "per_turn";
+}
+
+// @public (undocumented)
+export interface BackendExtensionSpec<Input, Output> {
+ // (undocumented)
+ readonly input: Input;
+ // (undocumented)
+ readonly output: Output;
+}
+
+// @public (undocumented)
+export type BackendId<Specs> = Extract<keyof Specs, string>;
+
+// @public (undocumented)
+export type BackendProbe<Capabilities> = {
+ readonly status: "healthy";
+ readonly version?: string;
+ readonly capabilities: Capabilities;
+} | {
+ readonly status: "unhealthy";
+ readonly error: AgentDriverError;
+ readonly capabilities: Capabilities;
+};
+
+// @public (undocumented)
+export interface BackendTypeSpec<Config, Capabilities, Extensions, ExtraEvent> {
+ // (undocumented)
+ readonly capabilities: Capabilities;
+ // (undocumented)
+ readonly config: Config;
+ // (undocumented)
+ readonly extensions: Extensions;
+ // (undocumented)
+ readonly extraEvent: ExtraEvent;
+}
+
+// @public (undocumented)
+export interface BaseBackendConfig {
+ // (undocumented)
+ readonly command?: string;
+ // (undocumented)
+ readonly environment?: Readonly<Record<string, string>>;
+}
+
+// @public (undocumented)
+export type BuiltinBackendId = "claude" | "codex" | "cursor" | "opencode" | "pi";
+
+// @public (undocumented)
+export interface BuiltinBackendSpecs {
+ // (undocumented)
+ readonly claude: BackendTypeSpec<ClaudeConfig, ClaudeCapabilities, {}, never>;
+ // (undocumented)
+ readonly codex: BackendTypeSpec<CodexConfig, CodexCapabilities, {}, never>;
+ // (undocumented)
+ readonly cursor: BackendTypeSpec<CursorConfig, CursorCapabilities, {}, never>;
+ // (undocumented)
+ readonly opencode: BackendTypeSpec<OpenCodeConfig, OpenCodeCapabilities, {}, never>;
+ // (undocumented)
+ readonly pi: BackendTypeSpec<PiConfig, PiCapabilities, {}, never>;
+}
+
+// @public (undocumented)
+export type CapabilitiesOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer Caps, infer _Extensions, infer _Event> ? Caps : never;
+
+// @public (undocumented)
+export type ClaudeCapabilities = FixedCapabilities<true, true, true, true, true, "safe_boundary_queue", "persistent">;
+
+// @public (undocumented)
+export interface ClaudeConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly disallowedTools?: string;
+ // (undocumented)
+ readonly mode: "default" | "fast";
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly provider: ClaudeProvider;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type ClaudeProvider = DefaultProvider | {
+ readonly kind: "custom_endpoint";
+ readonly apiUrl: string;
+ readonly apiKey: string;
+};
+
+// @public (undocumented)
+export type CodexCapabilities = FixedCapabilities<false, true, true, false, true, "safe_boundary_queue", "persistent">;
+
+// @public (undocumented)
+export interface CodexConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly mode: "default" | "fast";
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type ConfigOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer Config, infer _Caps, infer _Extensions, infer _Event> ? Config : never;
+
+// @public (undocumented)
+export type CoreAgentEventPayload = {
+ readonly type: "session_started";
+ readonly backendSessionId: string;
+} | {
+ readonly type: "command_queued";
+ readonly commandId: string;
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+} | {
+ readonly type: "command_accepted";
+ readonly commandId: string;
+ readonly turnId: string;
+ readonly delivery: "prompt" | "steer";
+} | {
+ readonly type: "command_failed";
+ readonly commandId: string;
+ readonly turnId?: string;
+ readonly error: AgentDriverError;
+} | {
+ readonly type: "turn_started";
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+} | {
+ readonly type: "thinking_delta";
+ readonly turnId: string;
+ readonly text: string;
+} | {
+ readonly type: "text_delta";
+ readonly turnId: string;
+ readonly text: string;
+} | {
+ readonly type: "tool_started";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly input: JsonValue;
+} | {
+ readonly type: "tool_finished";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly output?: JsonValue;
+} | {
+ readonly type: "compaction_started";
+ readonly turnId: string;
+} | {
+ readonly type: "compaction_finished";
+ readonly turnId: string;
+} | {
+ readonly type: "review_started";
+ readonly turnId: string;
+} | {
+ readonly type: "review_finished";
+ readonly turnId: string;
+} | {
+ readonly type: "internal_progress";
+ readonly turnId?: string;
+ readonly source?: string;
+ readonly itemType?: string;
+ readonly payloadBytes?: number;
+} | {
+ readonly type: "diagnostic";
+ readonly turnId?: string;
+ readonly severity: "debug" | "info" | "warning" | "error";
+ readonly source?: string;
+ readonly message: string;
+} | {
+ readonly type: "token_usage";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly usage: TokenUsage;
+ readonly details: JsonObject;
+} | {
+ readonly type: "rate_limits";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly details: JsonObject;
+} | {
+ readonly type: "turn_completed";
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+ readonly result: AgentTurnResult;
+} | {
+ readonly type: "session_failed";
+ readonly error: AgentDriverError;
+} | {
+ readonly type: "session_closed";
+ readonly result: AgentSessionResult;
+};
+
+// @public (undocumented)
+export interface CreateAgentDriverSdkOptions {
+ // (undocumented)
+ readonly host?: AgentDriverHost;
+ // (undocumented)
+ readonly hostReleaseTimeoutMs?: number;
+}
+
+// @public (undocumented)
+export function createBuiltinAgentDriverSdk(options?: CreateAgentDriverSdkOptions): AgentDriverSdk<BuiltinBackendSpecs>;
+
+// @public (undocumented)
+export function createDefaultAgentDriverHost(options?: DefaultAgentDriverHostOptions): AgentDriverHost;
+
+// @public (undocumented)
+export type CursorCapabilities = FixedCapabilities<false, false, false, false, true, "next_turn_queue", "persistent">;
+
+// @public (undocumented)
+export type CursorConfig = ModelBackendConfig;
+
+// @public (undocumented)
+export interface DefaultAgentDriverHostOptions {
+ // (undocumented)
+ readonly environment?: Readonly<Record<string, string | undefined>>;
+ // (undocumented)
+ readonly onRawOutput?: (event: RawOutputEvent) => void;
+}
+
+// @public (undocumented)
+export type DefaultProvider = {
+ readonly kind: "default";
+};
+
+// @public (undocumented)
+export type DeliveryReceipt = {
+ readonly status: "accepted";
+ readonly delivery: "prompt" | "steer";
+ readonly commandId: string;
+ readonly turnId: string;
+} | {
+ readonly status: "queued";
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+ readonly commandId: string;
+} | {
+ readonly status: "rejected";
+ readonly reason: "closed" | "unsupported" | "invalid_input" | "runtime_unavailable" | "already_started" | "not_started" | "duplicate_conflict";
+ readonly error?: AgentDriverError;
+};
+
+// @public (undocumented)
+export type ExtensionInput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> = ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer Input, infer _Output> ? Input : never;
+
+// @public (undocumented)
+export type ExtensionNames<Specs, Id extends BackendId<Specs>> = Extract<keyof ExtensionsOf<Specs, Id>, string>;
+
+// @public (undocumented)
+export type ExtensionOutput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> = ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer _Input, infer Output> ? Output : never;
+
+// @public (undocumented)
+export type ExtensionResult<Output> = {
+ readonly ok: true;
+ readonly value: Output;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type ExtensionsOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer Extensions, infer _Event> ? Extensions : never;
+
+// @public (undocumented)
+export type ExtraEventOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer _Extensions, infer Event> ? Event : never;
+
+// @public (undocumented)
+export type FixedCapabilities<Provider extends boolean, Reasoning extends boolean, Fast extends boolean, Tools extends boolean, Command extends boolean, Delivery extends BackendCapabilities["midTurnDelivery"], Lifetime extends BackendCapabilities["sessionLifetime"]> = BackendCapabilities & {
+ readonly modelSelection: "launchable";
+ readonly providerConfiguration: Provider;
+ readonly reasoningEffort: Reasoning;
+ readonly fastMode: Fast;
+ readonly disallowedTools: Tools;
+ readonly commandOverride: Command;
+ readonly resume: "by_id";
+ readonly sessionLifetime: Lifetime;
+ readonly midTurnDelivery: Delivery;
+ readonly interrupt: true;
+};
+
+// @public (undocumented)
+export type HostCleanupResult = {
+ readonly status: "not_acquired";
+} | {
+ readonly status: "released";
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+} | {
+ readonly status: "timed_out";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type InterruptResult = {
+ readonly status: "accepted";
+ readonly requestId: string;
+ readonly turnId: string;
+} | {
+ readonly status: "not_running";
+} | {
+ readonly status: "unsupported";
+} | {
+ readonly status: "closed";
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type JsonObject = {
+ readonly [key: string]: JsonValue;
+};
+
+// @public (undocumented)
+export type JsonPrimitive = string | number | boolean | null;
+
+// @public (undocumented)
+export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];
+
+// @public (undocumented)
+export interface ModelBackendConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly model: ModelSelection;
+}
+
+// @public (undocumented)
+export type ModelSelection = {
+ readonly kind: "default";
+} | {
+ readonly kind: "named";
+ readonly name: string;
+} | {
+ readonly kind: "custom";
+ readonly name: string;
+};
+
+// @public (undocumented)
+export type OpenCodeCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;
+
+// @public (undocumented)
+export type OpenCodeConfig = ModelBackendConfig;
+
+// @public (undocumented)
+export interface OpenSessionInput<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly config: ConfigOf<Specs, Id>;
+ // (undocumented)
+ readonly launch: AgentLaunchContext;
+}
+
+// @public (undocumented)
+export type OpenSessionResult<Specs, Id extends BackendId<Specs>> = {
+ readonly ok: true;
+ readonly session: AgentSession<Specs, Id>;
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type PiCapabilities = FixedCapabilities<true, true, false, false, false, "steer", "persistent">;
+
+// @public (undocumented)
+export interface PiConfig extends Omit<BaseBackendConfig, "command"> {
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly provider: PiProvider;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type PiProvider = DefaultProvider | {
+ readonly kind: "builtin";
+ readonly providerId: "google" | "openai" | "openrouter" | (string & {});
+ readonly apiKey: string;
+};
+
+// @public (undocumented)
+export interface PreparedExecutionResource {
+ // (undocumented)
+ readonly environmentLayers: Readonly<Record<"base" | "hostStatic" | "identityProtected" | "platformProtected" | "runtimeProtected" | "networkProtected" | "credentialSensitive", Readonly<Record<string, string | undefined>>>>;
+ // (undocumented)
+ readonly executablePath?: string;
+ // (undocumented)
+ release(input: {
+ readonly reason: "normal" | "failed_start" | "crash" | "requested_stop" | "consumer_closed";
+ readonly signal: AbortSignal;
+ readonly deadlineAt: number;
+ }): Promise<void>;
+}
+
+// @public (undocumented)
+export interface PrepareExecutionInput {
+ // (undocumented)
+ readonly backend: string;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly workingDirectory: string;
+}
+
+// @public (undocumented)
+export type PrepareExecutionResult = {
+ readonly ok: true;
+ readonly resource: PreparedExecutionResource;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface ProbeInput<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly command?: string;
+}
+
+// @public (undocumented)
+export interface RawOutputEvent {
+ // (undocumented)
+ readonly backend: string;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly stream: "stdout" | "stderr";
+ // (undocumented)
+ readonly text: string;
+}
+
+// @public (undocumented)
+export type ReasoningEffort = "low" | "medium" | "high";
+
+// @public (undocumented)
+export function scrubAgentDriverDiagnosticText(value: unknown, fallback?: string): string;
+
+// @public (undocumented)
+export interface StopInput {
+ // (undocumented)
+ readonly forceAfterMs: number;
+ // (undocumented)
+ readonly reason: "owner_request" | "idle_timeout" | "stalled" | "shutdown" | "reset";
+}
+
+// @public (undocumented)
+export type StopReceipt = {
+ readonly status: "accepted";
+ readonly requestId: string;
+} | {
+ readonly status: "already_stopping";
+ readonly requestId: string;
+} | {
+ readonly status: "closed";
+ readonly result: AgentSessionResult;
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface TokenUsage {
+ // (undocumented)
+ readonly cachedInputTokens?: number;
+ // (undocumented)
+ readonly inputTokens?: number;
+ // (undocumented)
+ readonly outputTokens?: number;
+ // (undocumented)
+ readonly reasoningTokens?: number;
+ // (undocumented)
+ readonly totalTokens?: number;
+}
+
+// (No @packageDocumentation comment for this package)
+
+```
diff --git a/src/daemon/agent-driver/etc/api/root.api.md b/src/daemon/agent-driver/etc/api/root.api.md
new file mode 100644
index 000000000..e16abf6b6
--- /dev/null
+++ b/src/daemon/agent-driver/etc/api/root.api.md
@@ -0,0 +1,682 @@
+## API Report File for "@alook/agent-driver"
+
+> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
+
+```ts
+
+// @public (undocumented)
+export interface AgentDriverError {
+ // (undocumented)
+ readonly category: "runtime_unavailable" | "authentication" | "configuration" | "protocol" | "process" | "sdk" | "timeout" | "cancelled" | "buffer_overflow" | "internal";
+ // (undocumented)
+ readonly code: string;
+ // (undocumented)
+ readonly details?: JsonObject;
+ // (undocumented)
+ readonly message: string;
+ // (undocumented)
+ readonly retryable: boolean;
+}
+
+// @public (undocumented)
+export interface AgentDriverSdk<Specs = BuiltinBackendSpecs> {
+ // (undocumented)
+ readonly backendIds: readonly BackendId<Specs>[];
+ // (undocumented)
+ open<Id extends BackendId<Specs>>(input: OpenSessionInput<Specs, Id>): Promise<OpenSessionResult<Specs, Id>>;
+ // (undocumented)
+ probe<Id extends BackendId<Specs>>(input: ProbeInput<Specs, Id>): Promise<BackendProbe<CapabilitiesOf<Specs, Id>>>;
+}
+
+// @public (undocumented)
+export type AgentEvent<Specs, Id extends BackendId<Specs>> = AgentEventEnvelope & (CoreAgentEventPayload | ExtraEventOf<Specs, Id>);
+
+// @public (undocumented)
+export interface AgentEventEnvelope {
+ // (undocumented)
+ readonly at: number;
+ // (undocumented)
+ readonly sequence: number;
+ // (undocumented)
+ readonly sessionInstanceId: string;
+}
+
+// @public (undocumented)
+export interface AgentEventStream<Event> extends AsyncIterable<Event> {
+ // (undocumented)
+ readonly maxBufferedBytes: 4_194_304;
+}
+
+// @public (undocumented)
+export interface AgentInstructions {
+ // (undocumented)
+ readonly content: string;
+ // (undocumented)
+ readonly format: "markdown";
+}
+
+// @public (undocumented)
+export interface AgentLaunchContext {
+ // (undocumented)
+ readonly instructions: AgentInstructions;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly resumeSessionId?: string;
+ // (undocumented)
+ readonly workingDirectory: string;
+}
+
+// @public (undocumented)
+export interface AgentMessage {
+ // (undocumented)
+ readonly id: string;
+ // (undocumented)
+ readonly kind: "user" | "system" | "recovery";
+ // (undocumented)
+ readonly sequence?: number;
+ // (undocumented)
+ readonly text: string;
+}
+
+// @public (undocumented)
+export interface AgentSession<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+ // (undocumented)
+ readonly closed: Promise<AgentSessionResult>;
+ // (undocumented)
+ readonly events: AgentEventStream<AgentEvent<Specs, Id>>;
+ // (undocumented)
+ interrupt(input: {
+ readonly requestId: string;
+ readonly reason: string;
+ }): Promise<InterruptResult>;
+ // (undocumented)
+ invokeExtension<Name extends ExtensionNames<Specs, Id>>(name: Name, input: ExtensionInput<Specs, Id, Name>): Promise<ExtensionResult<ExtensionOutput<Specs, Id, Name>>>;
+ // (undocumented)
+ send(message: AgentMessage): Promise<DeliveryReceipt>;
+ // (undocumented)
+ readonly sessionInstanceId: string;
+ // (undocumented)
+ snapshot(): AgentSessionSnapshot;
+ // (undocumented)
+ start(message: AgentMessage): Promise<DeliveryReceipt>;
+ // (undocumented)
+ stop(input: StopInput): Promise<StopReceipt>;
+}
+
+// @public (undocumented)
+export type AgentSessionResult = {
+ readonly outcome: "stopped";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly exitCode?: number | null;
+ readonly signal?: string | null;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "crashed";
+ readonly requested: false;
+ readonly backendSessionId?: string;
+ readonly exitCode: number | null;
+ readonly signal: string | null;
+ readonly error?: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "failed_to_start";
+ readonly requested: false;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "forced";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+};
+
+// @public (undocumented)
+export interface AgentSessionSnapshot {
+ // (undocumented)
+ readonly activeTurn?: {
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+ };
+ // (undocumented)
+ readonly backendSessionId?: string;
+ // (undocumented)
+ readonly diagnostics: {
+ readonly deliveryPhase: "idle" | "admission_wait" | "steering" | "next_turn_queued" | "compacting" | "reviewing" | "tool_wait" | "working";
+ readonly metrics: {
+ readonly physicalOpenCount: number;
+ readonly turnCount: number;
+ readonly commandAdmissionCount: number;
+ readonly commandAdmissionLatencyTotalMs: number;
+ readonly queueDwellCount: number;
+ readonly queueDwellTotalMs: number;
+ readonly sseReconnectCount: number;
+ readonly resumeOutcome: "not_requested" | "pending" | "resumed" | "reset_required" | "failed";
+ readonly terminalOwnerKind: "transport_request" | "vendor_message" | "prompt_invocation" | "lane_generation";
+ };
+ };
+ // (undocumented)
+ readonly lastEventSequence: number;
+ // (undocumented)
+ readonly queuedCommands: readonly {
+ readonly commandId: string;
+ readonly kind: AgentMessage["kind"];
+ }[];
+ // (undocumented)
+ readonly sessionInstanceId: string;
+ // (undocumented)
+ readonly state: "new" | "awaiting_first_message" | "starting" | "idle" | "working" | "stopping" | "closed";
+}
+
+// @public (undocumented)
+export type AgentTurnResult = {
+ readonly outcome: "success";
+ readonly backendSessionId: string;
+} | {
+ readonly outcome: "interrupted";
+ readonly backendSessionId?: string;
+} | {
+ readonly outcome: "failed";
+ readonly backendSessionId?: string;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface BackendCapabilities {
+ // (undocumented)
+ readonly commandOverride: boolean;
+ // (undocumented)
+ readonly disallowedTools: boolean;
+ // (undocumented)
+ readonly fastMode: boolean;
+ // (undocumented)
+ readonly interrupt: boolean;
+ // (undocumented)
+ readonly midTurnDelivery: "steer" | "safe_boundary_queue" | "next_turn_queue";
+ // (undocumented)
+ readonly modelSelection: "launchable" | "suggestion_only" | "unsupported";
+ // (undocumented)
+ readonly providerConfiguration: boolean;
+ // (undocumented)
+ readonly reasoningEffort: boolean;
+ // (undocumented)
+ readonly resume: "by_id" | "none";
+ // (undocumented)
+ readonly sessionLifetime: "persistent" | "per_turn";
+}
+
+// @public (undocumented)
+export interface BackendExtensionSpec<Input, Output> {
+ // (undocumented)
+ readonly input: Input;
+ // (undocumented)
+ readonly output: Output;
+}
+
+// @public (undocumented)
+export type BackendId<Specs> = Extract<keyof Specs, string>;
+
+// @public (undocumented)
+export type BackendProbe<Capabilities> = {
+ readonly status: "healthy";
+ readonly version?: string;
+ readonly capabilities: Capabilities;
+} | {
+ readonly status: "unhealthy";
+ readonly error: AgentDriverError;
+ readonly capabilities: Capabilities;
+};
+
+// @public (undocumented)
+export interface BackendTypeSpec<Config, Capabilities, Extensions, ExtraEvent> {
+ // (undocumented)
+ readonly capabilities: Capabilities;
+ // (undocumented)
+ readonly config: Config;
+ // (undocumented)
+ readonly extensions: Extensions;
+ // (undocumented)
+ readonly extraEvent: ExtraEvent;
+}
+
+// @public (undocumented)
+export interface BaseBackendConfig {
+ // (undocumented)
+ readonly command?: string;
+ // (undocumented)
+ readonly environment?: Readonly<Record<string, string>>;
+}
+
+// @public (undocumented)
+export const BUILTIN_BACKEND_IDS: readonly ["claude", "codex", "cursor", "opencode", "pi"];
+
+// @public (undocumented)
+export type BuiltinBackendId = "claude" | "codex" | "cursor" | "opencode" | "pi";
+
+// @public (undocumented)
+export type BuiltinBackendSelection = {
+ [Id in BuiltinBackendId]: {
+ readonly backend: Id;
+ readonly config: ConfigOf<BuiltinBackendSpecs, Id>;
+ };
+}[BuiltinBackendId];
+
+// @public (undocumented)
+export interface BuiltinBackendSpecs {
+ // (undocumented)
+ readonly claude: BackendTypeSpec<ClaudeConfig, ClaudeCapabilities, {}, never>;
+ // (undocumented)
+ readonly codex: BackendTypeSpec<CodexConfig, CodexCapabilities, {}, never>;
+ // (undocumented)
+ readonly cursor: BackendTypeSpec<CursorConfig, CursorCapabilities, {}, never>;
+ // (undocumented)
+ readonly opencode: BackendTypeSpec<OpenCodeConfig, OpenCodeCapabilities, {}, never>;
+ // (undocumented)
+ readonly pi: BackendTypeSpec<PiConfig, PiCapabilities, {}, never>;
+}
+
+// @public (undocumented)
+export interface BuiltinRuntimeConfigInput {
+ // (undocumented)
+ readonly command?: string;
+ // (undocumented)
+ readonly disallowedTools?: string;
+ // (undocumented)
+ readonly envVars?: Readonly<Record<string, string>>;
+ // (undocumented)
+ readonly mode: {
+ readonly kind: "default" | "fast";
+ };
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly provider?: {
+ readonly kind: "default";
+ } | {
+ readonly kind: "custom";
+ readonly apiUrl: string;
+ readonly apiKey: string;
+ } | {
+ readonly kind: "pi-builtin";
+ readonly providerId: string;
+ readonly apiKey: string;
+ };
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+ // (undocumented)
+ readonly runtime: string;
+}
+
+// @public (undocumented)
+export type CapabilitiesOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer Caps, infer _Extensions, infer _Event> ? Caps : never;
+
+// @public (undocumented)
+export type ClaudeCapabilities = FixedCapabilities<true, true, true, true, true, "safe_boundary_queue", "persistent">;
+
+// @public (undocumented)
+export interface ClaudeConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly disallowedTools?: string;
+ // (undocumented)
+ readonly mode: "default" | "fast";
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly provider: ClaudeProvider;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type ClaudeProvider = DefaultProvider | {
+ readonly kind: "custom_endpoint";
+ readonly apiUrl: string;
+ readonly apiKey: string;
+};
+
+// @public (undocumented)
+export type CodexCapabilities = FixedCapabilities<false, true, true, false, true, "safe_boundary_queue", "persistent">;
+
+// @public (undocumented)
+export interface CodexConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly mode: "default" | "fast";
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type ConfigOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer Config, infer _Caps, infer _Extensions, infer _Event> ? Config : never;
+
+// @public (undocumented)
+export type CoreAgentEventPayload = {
+ readonly type: "session_started";
+ readonly backendSessionId: string;
+} | {
+ readonly type: "command_queued";
+ readonly commandId: string;
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+} | {
+ readonly type: "command_accepted";
+ readonly commandId: string;
+ readonly turnId: string;
+ readonly delivery: "prompt" | "steer";
+} | {
+ readonly type: "command_failed";
+ readonly commandId: string;
+ readonly turnId?: string;
+ readonly error: AgentDriverError;
+} | {
+ readonly type: "turn_started";
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+} | {
+ readonly type: "thinking_delta";
+ readonly turnId: string;
+ readonly text: string;
+} | {
+ readonly type: "text_delta";
+ readonly turnId: string;
+ readonly text: string;
+} | {
+ readonly type: "tool_started";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly input: JsonValue;
+} | {
+ readonly type: "tool_finished";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly output?: JsonValue;
+} | {
+ readonly type: "compaction_started";
+ readonly turnId: string;
+} | {
+ readonly type: "compaction_finished";
+ readonly turnId: string;
+} | {
+ readonly type: "review_started";
+ readonly turnId: string;
+} | {
+ readonly type: "review_finished";
+ readonly turnId: string;
+} | {
+ readonly type: "internal_progress";
+ readonly turnId?: string;
+ readonly source?: string;
+ readonly itemType?: string;
+ readonly payloadBytes?: number;
+} | {
+ readonly type: "diagnostic";
+ readonly turnId?: string;
+ readonly severity: "debug" | "info" | "warning" | "error";
+ readonly source?: string;
+ readonly message: string;
+} | {
+ readonly type: "token_usage";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly usage: TokenUsage;
+ readonly details: JsonObject;
+} | {
+ readonly type: "rate_limits";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly details: JsonObject;
+} | {
+ readonly type: "turn_completed";
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+ readonly result: AgentTurnResult;
+} | {
+ readonly type: "session_failed";
+ readonly error: AgentDriverError;
+} | {
+ readonly type: "session_closed";
+ readonly result: AgentSessionResult;
+};
+
+// @public (undocumented)
+export function createAgentDriverSdk(options?: PublicAgentDriverSdkOptions): AgentDriverSdk<BuiltinBackendSpecs>;
+
+// @public (undocumented)
+export type CursorCapabilities = FixedCapabilities<false, false, false, false, true, "next_turn_queue", "persistent">;
+
+// @public (undocumented)
+export type CursorConfig = ModelBackendConfig;
+
+// @public (undocumented)
+export type DefaultProvider = {
+ readonly kind: "default";
+};
+
+// @public (undocumented)
+export type DeliveryReceipt = {
+ readonly status: "accepted";
+ readonly delivery: "prompt" | "steer";
+ readonly commandId: string;
+ readonly turnId: string;
+} | {
+ readonly status: "queued";
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+ readonly commandId: string;
+} | {
+ readonly status: "rejected";
+ readonly reason: "closed" | "unsupported" | "invalid_input" | "runtime_unavailable" | "already_started" | "not_started" | "duplicate_conflict";
+ readonly error?: AgentDriverError;
+};
+
+// @public (undocumented)
+export type ExtensionInput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> = ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer Input, infer _Output> ? Input : never;
+
+// @public (undocumented)
+export type ExtensionNames<Specs, Id extends BackendId<Specs>> = Extract<keyof ExtensionsOf<Specs, Id>, string>;
+
+// @public (undocumented)
+export type ExtensionOutput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> = ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer _Input, infer Output> ? Output : never;
+
+// @public (undocumented)
+export type ExtensionResult<Output> = {
+ readonly ok: true;
+ readonly value: Output;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type ExtensionsOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer Extensions, infer _Event> ? Extensions : never;
+
+// @public (undocumented)
+export type ExtraEventOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer _Extensions, infer Event> ? Event : never;
+
+// @public (undocumented)
+export type FixedCapabilities<Provider extends boolean, Reasoning extends boolean, Fast extends boolean, Tools extends boolean, Command extends boolean, Delivery extends BackendCapabilities["midTurnDelivery"], Lifetime extends BackendCapabilities["sessionLifetime"]> = BackendCapabilities & {
+ readonly modelSelection: "launchable";
+ readonly providerConfiguration: Provider;
+ readonly reasoningEffort: Reasoning;
+ readonly fastMode: Fast;
+ readonly disallowedTools: Tools;
+ readonly commandOverride: Command;
+ readonly resume: "by_id";
+ readonly sessionLifetime: Lifetime;
+ readonly midTurnDelivery: Delivery;
+ readonly interrupt: true;
+};
+
+// @public (undocumented)
+export function getBuiltinBackendCapabilities<Id extends BuiltinBackendId>(backend: Id): CapabilitiesOf<BuiltinBackendSpecs, Id>;
+
+// @public (undocumented)
+export type HostCleanupResult = {
+ readonly status: "not_acquired";
+} | {
+ readonly status: "released";
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+} | {
+ readonly status: "timed_out";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type InterruptResult = {
+ readonly status: "accepted";
+ readonly requestId: string;
+ readonly turnId: string;
+} | {
+ readonly status: "not_running";
+} | {
+ readonly status: "unsupported";
+} | {
+ readonly status: "closed";
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type JsonObject = {
+ readonly [key: string]: JsonValue;
+};
+
+// @public (undocumented)
+export type JsonPrimitive = string | number | boolean | null;
+
+// @public (undocumented)
+export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];
+
+// @public (undocumented)
+export interface ModelBackendConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly model: ModelSelection;
+}
+
+// @public (undocumented)
+export type ModelSelection = {
+ readonly kind: "default";
+} | {
+ readonly kind: "named";
+ readonly name: string;
+} | {
+ readonly kind: "custom";
+ readonly name: string;
+};
+
+// @public (undocumented)
+export type OpenCodeCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;
+
+// @public (undocumented)
+export type OpenCodeConfig = ModelBackendConfig;
+
+// @public (undocumented)
+export interface OpenSessionInput<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly config: ConfigOf<Specs, Id>;
+ // (undocumented)
+ readonly launch: AgentLaunchContext;
+}
+
+// @public (undocumented)
+export type OpenSessionResult<Specs, Id extends BackendId<Specs>> = {
+ readonly ok: true;
+ readonly session: AgentSession<Specs, Id>;
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type PiCapabilities = FixedCapabilities<true, true, false, false, false, "steer", "persistent">;
+
+// @public (undocumented)
+export interface PiConfig extends Omit<BaseBackendConfig, "command"> {
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly provider: PiProvider;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type PiProvider = DefaultProvider | {
+ readonly kind: "builtin";
+ readonly providerId: "google" | "openai" | "openrouter" | (string & {});
+ readonly apiKey: string;
+};
+
+// @public (undocumented)
+export interface ProbeInput<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly command?: string;
+}
+
+// @public (undocumented)
+export interface PublicAgentDriverSdkOptions {
+ // (undocumented)
+ readonly hostReleaseTimeoutMs?: number;
+}
+
+// @public (undocumented)
+export type ReasoningEffort = "low" | "medium" | "high";
+
+// @public (undocumented)
+export interface StopInput {
+ // (undocumented)
+ readonly forceAfterMs: number;
+ // (undocumented)
+ readonly reason: "owner_request" | "idle_timeout" | "stalled" | "shutdown" | "reset";
+}
+
+// @public (undocumented)
+export type StopReceipt = {
+ readonly status: "accepted";
+ readonly requestId: string;
+} | {
+ readonly status: "already_stopping";
+ readonly requestId: string;
+} | {
+ readonly status: "closed";
+ readonly result: AgentSessionResult;
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export function toBuiltinBackendSelection(config: BuiltinRuntimeConfigInput): BuiltinBackendSelection;
+
+// @public (undocumented)
+export interface TokenUsage {
+ // (undocumented)
+ readonly cachedInputTokens?: number;
+ // (undocumented)
+ readonly inputTokens?: number;
+ // (undocumented)
+ readonly outputTokens?: number;
+ // (undocumented)
+ readonly reasoningTokens?: number;
+ // (undocumented)
+ readonly totalTokens?: number;
+}
+
+// (No @packageDocumentation comment for this package)
+
+```
diff --git a/src/daemon/agent-driver/etc/api/testing.api.md b/src/daemon/agent-driver/etc/api/testing.api.md
new file mode 100644
index 000000000..267de3795
--- /dev/null
+++ b/src/daemon/agent-driver/etc/api/testing.api.md
@@ -0,0 +1,732 @@
+## API Report File for "@alook/agent-driver"
+
+> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
+
+```ts
+
+// @public (undocumented)
+export interface AgentDriverConformanceFixture<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ completeFirstTurn(): Promise<void>;
+ // (undocumented)
+ readonly session: AgentSession<Specs, Id>;
+}
+
+// @public (undocumented)
+export interface AgentDriverConformanceResult {
+ // (undocumented)
+ readonly conflictingDuplicate: DeliveryReceipt;
+ // (undocumented)
+ readonly duplicateStart: DeliveryReceipt;
+ // (undocumented)
+ readonly events: readonly {
+ readonly type: string;
+ readonly sequence: number;
+ }[];
+ // (undocumented)
+ readonly firstStart: DeliveryReceipt;
+ // (undocumented)
+ readonly secondStart: DeliveryReceipt;
+ // (undocumented)
+ readonly sendBeforeStart: DeliveryReceipt;
+ // (undocumented)
+ readonly stop: StopReceipt;
+}
+
+// @public (undocumented)
+export interface AgentDriverError {
+ // (undocumented)
+ readonly category: "runtime_unavailable" | "authentication" | "configuration" | "protocol" | "process" | "sdk" | "timeout" | "cancelled" | "buffer_overflow" | "internal";
+ // (undocumented)
+ readonly code: string;
+ // (undocumented)
+ readonly details?: JsonObject;
+ // (undocumented)
+ readonly message: string;
+ // (undocumented)
+ readonly retryable: boolean;
+}
+
+// @public (undocumented)
+export interface AgentDriverHost {
+ // (undocumented)
+ createId(): string;
+ // (undocumented)
+ now(): number;
+ // (undocumented)
+ onRawOutput(event: RawOutputEvent): void;
+ // (undocumented)
+ prepareExecution(input: PrepareExecutionInput): Promise<PrepareExecutionResult>;
+}
+
+// @public (undocumented)
+export interface AgentDriverSdk<Specs = BuiltinBackendSpecs> {
+ // (undocumented)
+ readonly backendIds: readonly BackendId<Specs>[];
+ // (undocumented)
+ open<Id extends BackendId<Specs>>(input: OpenSessionInput<Specs, Id>): Promise<OpenSessionResult<Specs, Id>>;
+ // (undocumented)
+ probe<Id extends BackendId<Specs>>(input: ProbeInput<Specs, Id>): Promise<BackendProbe<CapabilitiesOf<Specs, Id>>>;
+}
+
+// @public (undocumented)
+export type AgentEvent<Specs, Id extends BackendId<Specs>> = AgentEventEnvelope & (CoreAgentEventPayload | ExtraEventOf<Specs, Id>);
+
+// @public (undocumented)
+export interface AgentEventEnvelope {
+ // (undocumented)
+ readonly at: number;
+ // (undocumented)
+ readonly sequence: number;
+ // (undocumented)
+ readonly sessionInstanceId: string;
+}
+
+// @public (undocumented)
+export interface AgentEventStream<Event> extends AsyncIterable<Event> {
+ // (undocumented)
+ readonly maxBufferedBytes: 4_194_304;
+}
+
+// @public (undocumented)
+export interface AgentInstructions {
+ // (undocumented)
+ readonly content: string;
+ // (undocumented)
+ readonly format: "markdown";
+}
+
+// @public (undocumented)
+export interface AgentLaunchContext {
+ // (undocumented)
+ readonly instructions: AgentInstructions;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly resumeSessionId?: string;
+ // (undocumented)
+ readonly workingDirectory: string;
+}
+
+// @public (undocumented)
+export interface AgentMessage {
+ // (undocumented)
+ readonly id: string;
+ // (undocumented)
+ readonly kind: "user" | "system" | "recovery";
+ // (undocumented)
+ readonly sequence?: number;
+ // (undocumented)
+ readonly text: string;
+}
+
+// @public (undocumented)
+export interface AgentSession<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+ // (undocumented)
+ readonly closed: Promise<AgentSessionResult>;
+ // (undocumented)
+ readonly events: AgentEventStream<AgentEvent<Specs, Id>>;
+ // (undocumented)
+ interrupt(input: {
+ readonly requestId: string;
+ readonly reason: string;
+ }): Promise<InterruptResult>;
+ // (undocumented)
+ invokeExtension<Name extends ExtensionNames<Specs, Id>>(name: Name, input: ExtensionInput<Specs, Id, Name>): Promise<ExtensionResult<ExtensionOutput<Specs, Id, Name>>>;
+ // (undocumented)
+ send(message: AgentMessage): Promise<DeliveryReceipt>;
+ // (undocumented)
+ readonly sessionInstanceId: string;
+ // (undocumented)
+ snapshot(): AgentSessionSnapshot;
+ // (undocumented)
+ start(message: AgentMessage): Promise<DeliveryReceipt>;
+ // (undocumented)
+ stop(input: StopInput): Promise<StopReceipt>;
+}
+
+// @public (undocumented)
+export type AgentSessionResult = {
+ readonly outcome: "stopped";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly exitCode?: number | null;
+ readonly signal?: string | null;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "crashed";
+ readonly requested: false;
+ readonly backendSessionId?: string;
+ readonly exitCode: number | null;
+ readonly signal: string | null;
+ readonly error?: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "failed_to_start";
+ readonly requested: false;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+} | {
+ readonly outcome: "forced";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+};
+
+// @public (undocumented)
+export interface AgentSessionSnapshot {
+ // (undocumented)
+ readonly activeTurn?: {
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+ };
+ // (undocumented)
+ readonly backendSessionId?: string;
+ // (undocumented)
+ readonly diagnostics: {
+ readonly deliveryPhase: "idle" | "admission_wait" | "steering" | "next_turn_queued" | "compacting" | "reviewing" | "tool_wait" | "working";
+ readonly metrics: {
+ readonly physicalOpenCount: number;
+ readonly turnCount: number;
+ readonly commandAdmissionCount: number;
+ readonly commandAdmissionLatencyTotalMs: number;
+ readonly queueDwellCount: number;
+ readonly queueDwellTotalMs: number;
+ readonly sseReconnectCount: number;
+ readonly resumeOutcome: "not_requested" | "pending" | "resumed" | "reset_required" | "failed";
+ readonly terminalOwnerKind: "transport_request" | "vendor_message" | "prompt_invocation" | "lane_generation";
+ };
+ };
+ // (undocumented)
+ readonly lastEventSequence: number;
+ // (undocumented)
+ readonly queuedCommands: readonly {
+ readonly commandId: string;
+ readonly kind: AgentMessage["kind"];
+ }[];
+ // (undocumented)
+ readonly sessionInstanceId: string;
+ // (undocumented)
+ readonly state: "new" | "awaiting_first_message" | "starting" | "idle" | "working" | "stopping" | "closed";
+}
+
+// @public (undocumented)
+export type AgentTurnResult = {
+ readonly outcome: "success";
+ readonly backendSessionId: string;
+} | {
+ readonly outcome: "interrupted";
+ readonly backendSessionId?: string;
+} | {
+ readonly outcome: "failed";
+ readonly backendSessionId?: string;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface BackendCapabilities {
+ // (undocumented)
+ readonly commandOverride: boolean;
+ // (undocumented)
+ readonly disallowedTools: boolean;
+ // (undocumented)
+ readonly fastMode: boolean;
+ // (undocumented)
+ readonly interrupt: boolean;
+ // (undocumented)
+ readonly midTurnDelivery: "steer" | "safe_boundary_queue" | "next_turn_queue";
+ // (undocumented)
+ readonly modelSelection: "launchable" | "suggestion_only" | "unsupported";
+ // (undocumented)
+ readonly providerConfiguration: boolean;
+ // (undocumented)
+ readonly reasoningEffort: boolean;
+ // (undocumented)
+ readonly resume: "by_id" | "none";
+ // (undocumented)
+ readonly sessionLifetime: "persistent" | "per_turn";
+}
+
+// @public (undocumented)
+export interface BackendExtensionSpec<Input, Output> {
+ // (undocumented)
+ readonly input: Input;
+ // (undocumented)
+ readonly output: Output;
+}
+
+// @public (undocumented)
+export type BackendId<Specs> = Extract<keyof Specs, string>;
+
+// @public (undocumented)
+export type BackendProbe<Capabilities> = {
+ readonly status: "healthy";
+ readonly version?: string;
+ readonly capabilities: Capabilities;
+} | {
+ readonly status: "unhealthy";
+ readonly error: AgentDriverError;
+ readonly capabilities: Capabilities;
+};
+
+// @public (undocumented)
+export interface BackendTypeSpec<Config, Capabilities, Extensions, ExtraEvent> {
+ // (undocumented)
+ readonly capabilities: Capabilities;
+ // (undocumented)
+ readonly config: Config;
+ // (undocumented)
+ readonly extensions: Extensions;
+ // (undocumented)
+ readonly extraEvent: ExtraEvent;
+}
+
+// @public (undocumented)
+export interface BaseBackendConfig {
+ // (undocumented)
+ readonly command?: string;
+ // (undocumented)
+ readonly environment?: Readonly<Record<string, string>>;
+}
+
+// @public (undocumented)
+export type BuiltinBackendId = "claude" | "codex" | "cursor" | "opencode" | "pi";
+
+// @public (undocumented)
+export interface BuiltinBackendSpecs {
+ // (undocumented)
+ readonly claude: BackendTypeSpec<ClaudeConfig, ClaudeCapabilities, {}, never>;
+ // (undocumented)
+ readonly codex: BackendTypeSpec<CodexConfig, CodexCapabilities, {}, never>;
+ // (undocumented)
+ readonly cursor: BackendTypeSpec<CursorConfig, CursorCapabilities, {}, never>;
+ // (undocumented)
+ readonly opencode: BackendTypeSpec<OpenCodeConfig, OpenCodeCapabilities, {}, never>;
+ // (undocumented)
+ readonly pi: BackendTypeSpec<PiConfig, PiCapabilities, {}, never>;
+}
+
+// @public (undocumented)
+export type CapabilitiesOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer Caps, infer _Extensions, infer _Event> ? Caps : never;
+
+// @public (undocumented)
+export type ClaudeCapabilities = FixedCapabilities<true, true, true, true, true, "safe_boundary_queue", "persistent">;
+
+// @public (undocumented)
+export interface ClaudeConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly disallowedTools?: string;
+ // (undocumented)
+ readonly mode: "default" | "fast";
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly provider: ClaudeProvider;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type ClaudeProvider = DefaultProvider | {
+ readonly kind: "custom_endpoint";
+ readonly apiUrl: string;
+ readonly apiKey: string;
+};
+
+// @public (undocumented)
+export type CodexCapabilities = FixedCapabilities<false, true, true, false, true, "safe_boundary_queue", "persistent">;
+
+// @public (undocumented)
+export interface CodexConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly mode: "default" | "fast";
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type ConfigOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer Config, infer _Caps, infer _Extensions, infer _Event> ? Config : never;
+
+// @public (undocumented)
+export type CoreAgentEventPayload = {
+ readonly type: "session_started";
+ readonly backendSessionId: string;
+} | {
+ readonly type: "command_queued";
+ readonly commandId: string;
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+} | {
+ readonly type: "command_accepted";
+ readonly commandId: string;
+ readonly turnId: string;
+ readonly delivery: "prompt" | "steer";
+} | {
+ readonly type: "command_failed";
+ readonly commandId: string;
+ readonly turnId?: string;
+ readonly error: AgentDriverError;
+} | {
+ readonly type: "turn_started";
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+} | {
+ readonly type: "thinking_delta";
+ readonly turnId: string;
+ readonly text: string;
+} | {
+ readonly type: "text_delta";
+ readonly turnId: string;
+ readonly text: string;
+} | {
+ readonly type: "tool_started";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly input: JsonValue;
+} | {
+ readonly type: "tool_finished";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly output?: JsonValue;
+} | {
+ readonly type: "compaction_started";
+ readonly turnId: string;
+} | {
+ readonly type: "compaction_finished";
+ readonly turnId: string;
+} | {
+ readonly type: "review_started";
+ readonly turnId: string;
+} | {
+ readonly type: "review_finished";
+ readonly turnId: string;
+} | {
+ readonly type: "internal_progress";
+ readonly turnId?: string;
+ readonly source?: string;
+ readonly itemType?: string;
+ readonly payloadBytes?: number;
+} | {
+ readonly type: "diagnostic";
+ readonly turnId?: string;
+ readonly severity: "debug" | "info" | "warning" | "error";
+ readonly source?: string;
+ readonly message: string;
+} | {
+ readonly type: "token_usage";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly usage: TokenUsage;
+ readonly details: JsonObject;
+} | {
+ readonly type: "rate_limits";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly details: JsonObject;
+} | {
+ readonly type: "turn_completed";
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+ readonly result: AgentTurnResult;
+} | {
+ readonly type: "session_failed";
+ readonly error: AgentDriverError;
+} | {
+ readonly type: "session_closed";
+ readonly result: AgentSessionResult;
+};
+
+// @public (undocumented)
+export function createFakeAgentDriverHost(overrides?: Partial<PreparedExecutionResource>): FakeAgentDriverHost;
+
+// @public (undocumented)
+export type CursorCapabilities = FixedCapabilities<false, false, false, false, true, "next_turn_queue", "persistent">;
+
+// @public (undocumented)
+export type CursorConfig = ModelBackendConfig;
+
+// @public (undocumented)
+export interface DefaultAgentDriverHostOptions {
+ // (undocumented)
+ readonly environment?: Readonly<Record<string, string | undefined>>;
+ // (undocumented)
+ readonly onRawOutput?: (event: RawOutputEvent) => void;
+}
+
+// @public (undocumented)
+export type DefaultProvider = {
+ readonly kind: "default";
+};
+
+// @public (undocumented)
+export type DeliveryReceipt = {
+ readonly status: "accepted";
+ readonly delivery: "prompt" | "steer";
+ readonly commandId: string;
+ readonly turnId: string;
+} | {
+ readonly status: "queued";
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+ readonly commandId: string;
+} | {
+ readonly status: "rejected";
+ readonly reason: "closed" | "unsupported" | "invalid_input" | "runtime_unavailable" | "already_started" | "not_started" | "duplicate_conflict";
+ readonly error?: AgentDriverError;
+};
+
+// @public (undocumented)
+export type ExtensionInput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> = ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer Input, infer _Output> ? Input : never;
+
+// @public (undocumented)
+export type ExtensionNames<Specs, Id extends BackendId<Specs>> = Extract<keyof ExtensionsOf<Specs, Id>, string>;
+
+// @public (undocumented)
+export type ExtensionOutput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> = ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer _Input, infer Output> ? Output : never;
+
+// @public (undocumented)
+export type ExtensionResult<Output> = {
+ readonly ok: true;
+ readonly value: Output;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type ExtensionsOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer Extensions, infer _Event> ? Extensions : never;
+
+// @public (undocumented)
+export type ExtraEventOf<Specs, Id extends BackendId<Specs>> = Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer _Extensions, infer Event> ? Event : never;
+
+// @public (undocumented)
+export interface FakeAgentDriverHost extends AgentDriverHost {
+ // (undocumented)
+ readonly rawOutput: RawOutputEvent[];
+ // (undocumented)
+ readonly releases: Array<Parameters<PreparedExecutionResource["release"]>[0]>;
+}
+
+// @public (undocumented)
+export type FixedCapabilities<Provider extends boolean, Reasoning extends boolean, Fast extends boolean, Tools extends boolean, Command extends boolean, Delivery extends BackendCapabilities["midTurnDelivery"], Lifetime extends BackendCapabilities["sessionLifetime"]> = BackendCapabilities & {
+ readonly modelSelection: "launchable";
+ readonly providerConfiguration: Provider;
+ readonly reasoningEffort: Reasoning;
+ readonly fastMode: Fast;
+ readonly disallowedTools: Tools;
+ readonly commandOverride: Command;
+ readonly resume: "by_id";
+ readonly sessionLifetime: Lifetime;
+ readonly midTurnDelivery: Delivery;
+ readonly interrupt: true;
+};
+
+// @public (undocumented)
+export type HostCleanupResult = {
+ readonly status: "not_acquired";
+} | {
+ readonly status: "released";
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+} | {
+ readonly status: "timed_out";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type InterruptResult = {
+ readonly status: "accepted";
+ readonly requestId: string;
+ readonly turnId: string;
+} | {
+ readonly status: "not_running";
+} | {
+ readonly status: "unsupported";
+} | {
+ readonly status: "closed";
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type JsonObject = {
+ readonly [key: string]: JsonValue;
+};
+
+// @public (undocumented)
+export type JsonPrimitive = string | number | boolean | null;
+
+// @public (undocumented)
+export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];
+
+// @public (undocumented)
+export interface ModelBackendConfig extends BaseBackendConfig {
+ // (undocumented)
+ readonly model: ModelSelection;
+}
+
+// @public (undocumented)
+export type ModelSelection = {
+ readonly kind: "default";
+} | {
+ readonly kind: "named";
+ readonly name: string;
+} | {
+ readonly kind: "custom";
+ readonly name: string;
+};
+
+// @public (undocumented)
+export type OpenCodeCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;
+
+// @public (undocumented)
+export type OpenCodeConfig = ModelBackendConfig;
+
+// @public (undocumented)
+export interface OpenSessionInput<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly config: ConfigOf<Specs, Id>;
+ // (undocumented)
+ readonly launch: AgentLaunchContext;
+}
+
+// @public (undocumented)
+export type OpenSessionResult<Specs, Id extends BackendId<Specs>> = {
+ readonly ok: true;
+ readonly session: AgentSession<Specs, Id>;
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export type PiCapabilities = FixedCapabilities<true, true, false, false, false, "steer", "persistent">;
+
+// @public (undocumented)
+export interface PiConfig extends Omit<BaseBackendConfig, "command"> {
+ // (undocumented)
+ readonly model: ModelSelection;
+ // (undocumented)
+ readonly provider: PiProvider;
+ // (undocumented)
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+// @public (undocumented)
+export type PiProvider = DefaultProvider | {
+ readonly kind: "builtin";
+ readonly providerId: "google" | "openai" | "openrouter" | (string & {});
+ readonly apiKey: string;
+};
+
+// @public (undocumented)
+export interface PreparedExecutionResource {
+ // (undocumented)
+ readonly environmentLayers: Readonly<Record<"base" | "hostStatic" | "identityProtected" | "platformProtected" | "runtimeProtected" | "networkProtected" | "credentialSensitive", Readonly<Record<string, string | undefined>>>>;
+ // (undocumented)
+ readonly executablePath?: string;
+ // (undocumented)
+ release(input: {
+ readonly reason: "normal" | "failed_start" | "crash" | "requested_stop" | "consumer_closed";
+ readonly signal: AbortSignal;
+ readonly deadlineAt: number;
+ }): Promise<void>;
+}
+
+// @public (undocumented)
+export interface PrepareExecutionInput {
+ // (undocumented)
+ readonly backend: string;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly workingDirectory: string;
+}
+
+// @public (undocumented)
+export type PrepareExecutionResult = {
+ readonly ok: true;
+ readonly resource: PreparedExecutionResource;
+} | {
+ readonly ok: false;
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface ProbeInput<Specs, Id extends BackendId<Specs>> {
+ // (undocumented)
+ readonly backend: Id;
+ // (undocumented)
+ readonly command?: string;
+}
+
+// @public (undocumented)
+export interface RawOutputEvent {
+ // (undocumented)
+ readonly backend: string;
+ // (undocumented)
+ readonly launchId: string;
+ // (undocumented)
+ readonly stream: "stdout" | "stderr";
+ // (undocumented)
+ readonly text: string;
+}
+
+// @public (undocumented)
+export type ReasoningEffort = "low" | "medium" | "high";
+
+// @public
+export function runAgentDriverConformance<Specs, Id extends BackendId<Specs>>(create: () => Promise<AgentDriverConformanceFixture<Specs, Id>> | AgentDriverConformanceFixture<Specs, Id>): Promise<AgentDriverConformanceResult>;
+
+// @public (undocumented)
+export interface StopInput {
+ // (undocumented)
+ readonly forceAfterMs: number;
+ // (undocumented)
+ readonly reason: "owner_request" | "idle_timeout" | "stalled" | "shutdown" | "reset";
+}
+
+// @public (undocumented)
+export type StopReceipt = {
+ readonly status: "accepted";
+ readonly requestId: string;
+} | {
+ readonly status: "already_stopping";
+ readonly requestId: string;
+} | {
+ readonly status: "closed";
+ readonly result: AgentSessionResult;
+} | {
+ readonly status: "failed";
+ readonly error: AgentDriverError;
+};
+
+// @public (undocumented)
+export interface TokenUsage {
+ // (undocumented)
+ readonly cachedInputTokens?: number;
+ // (undocumented)
+ readonly inputTokens?: number;
+ // (undocumented)
+ readonly outputTokens?: number;
+ // (undocumented)
+ readonly reasoningTokens?: number;
+ // (undocumented)
+ readonly totalTokens?: number;
+}
+
+// (No @packageDocumentation comment for this package)
+
+```
diff --git a/src/daemon/agent-driver/knip.json b/src/daemon/agent-driver/knip.json
new file mode 100644
index 000000000..0dc7a3777
--- /dev/null
+++ b/src/daemon/agent-driver/knip.json
@@ -0,0 +1,6 @@
+{
+ "$schema": "https://unpkg.com/knip@5/schema.json",
+ "entry": ["src/index.ts", "src/host.ts", "src/adapter-author.ts", "src/testing/index.ts", "src/**/*.test.ts"],
+ "project": ["src/**/*.ts"],
+ "ignoreDependencies": ["typescript-eslint"]
+}
diff --git a/src/daemon/agent-driver/package.json b/src/daemon/agent-driver/package.json
new file mode 100644
index 000000000..3683bba66
--- /dev/null
+++ b/src/daemon/agent-driver/package.json
@@ -0,0 +1,61 @@
+{
+ "name": "@alook/agent-driver",
+ "version": "0.1.14",
+ "private": true,
+ "description": "Private workspace logical-session drivers for supported AI coding agents.",
+ "license": "Apache-2.0",
+ "type": "module",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ },
+ "./testing": {
+ "types": "./dist/testing/index.d.ts",
+ "import": "./dist/testing/index.js"
+ },
+ "./host": {
+ "types": "./dist/host.d.ts",
+ "import": "./dist/host.js"
+ },
+ "./adapter-author": {
+ "types": "./dist/adapter-author.d.ts",
+ "import": "./dist/adapter-author.js"
+ }
+ },
+ "files": [
+ "dist",
+ "README.md",
+ "RELEASE_NOTES.md",
+ "LICENSE"
+ ],
+ "engines": {
+ "node": ">=20.9"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/alookai/alook.git",
+ "directory": "src/daemon/agent-driver"
+ },
+ "scripts": {
+ "build": "tsc -p tsconfig.build.json && node scripts/prune-dist.mjs && node scripts/prepare-dist.mjs",
+ "prepack": "pnpm run build",
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run",
+ "lint": "eslint .",
+ "knip": "knip",
+ "api:check": "pnpm run build && node scripts/api-reports.mjs check",
+ "api:update": "pnpm run build && node scripts/api-reports.mjs update"
+ },
+ "devDependencies": {
+ "@microsoft/api-extractor": "^7.58.13",
+ "@types/node": "^20.0.0",
+ "eslint": "^9.39.5",
+ "knip": "^5.85.0",
+ "typescript": "^6.0.3",
+ "typescript-eslint": "^8.67.0",
+ "vitest": "^4.1.10"
+ }
+}
diff --git a/src/daemon/agent-driver/scripts/api-reports.mjs b/src/daemon/agent-driver/scripts/api-reports.mjs
new file mode 100644
index 000000000..cb09c3b1b
--- /dev/null
+++ b/src/daemon/agent-driver/scripts/api-reports.mjs
@@ -0,0 +1,24 @@
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { Extractor, ExtractorConfig } from "@microsoft/api-extractor";
+
+const packageRoot = resolve(fileURLToPath(new URL("..", import.meta.url)));
+const mode = process.argv[2];
+if (mode !== "check" && mode !== "update") {
+ throw new Error("Usage: node scripts/api-reports.mjs <check|update>");
+}
+
+const reports = ["root", "host", "adapter-author", "testing"];
+let failed = false;
+for (const report of reports) {
+ const configPath = resolve(packageRoot, `api-extractor.${report}.json`);
+ const config = ExtractorConfig.loadFileAndPrepare(configPath);
+ const result = Extractor.invoke(config, {
+ localBuild: mode === "update",
+ showDiagnostics: false,
+ showVerboseMessages: false,
+ });
+ if (!result.succeeded) failed = true;
+}
+
+if (failed) process.exitCode = 1;
diff --git a/src/daemon/agent-driver/scripts/prepare-dist.mjs b/src/daemon/agent-driver/scripts/prepare-dist.mjs
new file mode 100644
index 000000000..3ee41ca42
--- /dev/null
+++ b/src/daemon/agent-driver/scripts/prepare-dist.mjs
@@ -0,0 +1,4 @@
+import { copyFileSync } from "node:fs";
+import { resolve } from "node:path";
+
+copyFileSync(resolve("../../../LICENSE"), resolve("LICENSE"));
diff --git a/src/daemon/agent-driver/scripts/prune-dist.mjs b/src/daemon/agent-driver/scripts/prune-dist.mjs
new file mode 100644
index 000000000..16fb9cb31
--- /dev/null
+++ b/src/daemon/agent-driver/scripts/prune-dist.mjs
@@ -0,0 +1,36 @@
+import { readdirSync, rmSync } from "node:fs";
+import { relative, resolve } from "node:path";
+
+const sourceRoot = resolve("src");
+const distRoot = resolve("dist");
+
+function filesUnder(root) {
+ const files = [];
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
+ const path = resolve(root, entry.name);
+ if (entry.isDirectory()) files.push(...filesUnder(path));
+ else if (entry.isFile()) files.push(path);
+ }
+ return files;
+}
+
+const expected = new Set();
+for (const source of filesUnder(sourceRoot)) {
+ const rel = relative(sourceRoot, source);
+ if (!rel.endsWith(".ts") || rel.endsWith(".test.ts") || rel.endsWith(".spec.ts")) continue;
+ const stem = rel.slice(0, -3);
+ for (const suffix of [".js", ".js.map", ".d.ts", ".d.ts.map"]) expected.add(stem + suffix);
+}
+
+for (const output of filesUnder(distRoot)) {
+ if (!expected.has(relative(distRoot, output))) rmSync(output, { force: true });
+}
+
+function removeEmptyDirectories(root) {
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
+ if (entry.isDirectory()) removeEmptyDirectories(resolve(root, entry.name));
+ }
+ if (root !== distRoot && readdirSync(root).length === 0) rmSync(root, { recursive: true });
+}
+
+removeEmptyDirectories(distRoot);
diff --git a/src/daemon/agent-driver/src/adapter-author.ts b/src/daemon/agent-driver/src/adapter-author.ts
new file mode 100644
index 000000000..65c557086
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapter-author.ts
@@ -0,0 +1,21 @@
+/** Explicit extension boundary for adapter authors; not part of the consumer root API. */
+export const ADAPTER_AUTHOR_CONTRACT_VERSION = 1 as const;
+
+export type * from "./public-contract.js";
+export {
+ createAgentDriverSdkWithRegistry,
+} from "./sdk.js";
+export { createAgentDriverRegistry, createBuiltinAgentDriverRegistry } from "./registry.js";
+export type { AgentBackendRegistration, AgentBackendRegistrationOf, AgentDriverRegistry } from "./registry.js";
+export type {
+ AdapterEvent, AdapterLaunchConfig, AdapterLaunchContext, AdapterRuntimeContext, BackendAdapter, BackendConfig,
+ AdapterTransport, BackendExecution, EncodeMessageOptions, InputMode, LaneAdmission,
+ LaneInterruptInput, LaneSendInput, LaneStartInput, LaneStopInput, ProbeResult,
+ RuntimeLane, RuntimeLaneEventMap, RuntimeLaneExit, RuntimeLaneOpenOptions,
+ TerminalOwnership, WellKnownTransportKind,
+ SpawnedProcess, SpawnedProcessHandle, VendorSessionHandle,
+} from "./internal/adapter.js";
+export type {
+ AgentDriverHost, CreateAgentDriverSdkOptions, DefaultAgentDriverHostOptions,
+ PrepareExecutionInput, PrepareExecutionResult, PreparedExecutionResource, RawOutputEvent,
+} from "./contract.js";
diff --git a/src/daemon/agent-driver/src/adapters/claude/index.test.ts b/src/daemon/agent-driver/src/adapters/claude/index.test.ts
new file mode 100644
index 000000000..d727a641e
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/claude/index.test.ts
@@ -0,0 +1,83 @@
+import { EventEmitter } from "node:events";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { PassThrough } from "node:stream";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
+import { ClaudeDriver } from "./index.js";
+
+const spawnAgentProcess = vi.hoisted(() => vi.fn());
+vi.mock("../../internal/killTree.js", async () => ({
+ ...(await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js")),
+ spawnAgentProcess,
+}));
+
+const directories: string[] = [];
+afterEach(() => {
+ spawnAgentProcess.mockReset();
+ for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
+});
+
+describe("ClaudeDriver", () => {
+ it("reports an explicit missing command as unhealthy", () => {
+ expect(new ClaudeDriver().probe("/definitely/missing/alook-claude")).toMatchObject({
+ status: "unhealthy",
+ lastError: expect.any(String),
+ });
+ });
+
+ it("encodes same-turn safe-boundary input with the active resumed session", () => {
+ const driver = new ClaudeDriver();
+ expect(driver.currentSessionId).toBeNull();
+ const rootReceipt = driver.beginTurn();
+ const idle = JSON.parse(driver.encodeMessage("first", "session-1", { mode: "idle" }));
+ const busy = JSON.parse(driver.encodeMessage("follow up", "session-1", { mode: "busy" }));
+ expect(idle).toEqual({
+ type: "user",
+ message: { role: "user", content: [{ type: "text", text: "first" }] },
+ uuid: rootReceipt.slice("claude:".length),
+ session_id: "session-1",
+ });
+ expect(busy).toEqual({
+ type: "user",
+ message: { role: "user", content: [{ type: "text", text: "follow up" }] },
+ uuid: expect.stringMatching(/^[0-9a-f-]{36}$/),
+ priority: "now",
+ session_id: "session-1",
+ });
+ expect(busy.uuid).not.toBe(idle.uuid);
+ });
+
+ it("spawns the configured command and writes the initial stream-json message", async () => {
+ const stdin = new PassThrough();
+ const write = vi.spyOn(stdin, "write");
+ const process = Object.assign(new EventEmitter(), { stdin });
+ spawnAgentProcess.mockReturnValue(process);
+ const workingDirectory = mkdtempSync(join(tmpdir(), "claude-driver-"));
+ directories.push(workingDirectory);
+ const ctx = fakeLaunchContext("claude", workingDirectory, {
+ prompt: "hello",
+ config: {
+ sessionId: "session-1",
+ runtimeConfig: {
+ model: { kind: "default" },
+ provider: { kind: "default" },
+ mode: "default",
+ command: "/custom/claude",
+ },
+ },
+ });
+
+ const driver = new ClaudeDriver();
+ const receipt = driver.beginTurn();
+ await expect(driver.spawn(ctx)).resolves.toEqual({ process });
+ expect(spawnAgentProcess).toHaveBeenCalledWith(
+ "/custom/claude",
+ expect.any(Array),
+ expect.objectContaining({ cwd: workingDirectory }),
+ );
+ expect(write).toHaveBeenCalledWith(expect.stringContaining('"text":"hello"'));
+ expect(write).toHaveBeenCalledWith(expect.stringContaining(`"uuid":"${receipt.slice("claude:".length)}"`));
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/claude/index.ts b/src/daemon/agent-driver/src/adapters/claude/index.ts
new file mode 100644
index 000000000..39290fc97
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/claude/index.ts
@@ -0,0 +1,119 @@
+/**
+ * Claude Code driver — persistent stream-json process with gated steering.
+ *
+ * Claude's stdin protocol accepts a stable UUID on every user frame and its
+ * terminal `result` reports the root `user_message_uuid`. That provider-owned
+ * receipt, rather than payload content or a process restart, binds a terminal
+ * to the logical turn that initiated it. Safe-boundary steering frames use
+ * fresh UUIDs while Claude keeps the root UUID on the eventual result.
+ */
+import type {
+ BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, RuntimeLane,
+ RuntimeLaneOpenOptions, SpawnedProcess,
+} from "../../internal/adapter.js";
+import { createProcessLane } from "../../controller/process-host.js";
+import { prepareCliTransport } from "../../internal/cliTransport.js";
+import { buildClaudeProviderIsolationEnv } from "./providerIsolation.js";
+import { buildClaudeArgs } from "./launch.js";
+import { ClaudeEventNormalizer } from "./normalizer.js";
+import { probeClaude, probeCommandVersion, resolveSpawnSpec, resolveClaudeCommand } from "../../internal/probe.js";
+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
+import { spawnAgentProcess } from "../../internal/killTree.js";
+import { ClaudeTurnProtocol } from "./turnProtocol.js";
+
+export class ClaudeDriver implements BackendAdapter {
+ readonly id = "claude";
+ readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
+ readonly execution = {
+ lifetime: "session",
+ transport: { kind: "stdio_stream", protocol: "claude.stream-json.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "vendor_message",
+ } as const;
+
+ private readonly turnProtocol = new ClaudeTurnProtocol();
+ private readonly eventNormalizer = new ClaudeEventNormalizer(this.turnProtocol);
+
+ beginTurn(): string {
+ return this.turnProtocol.beginTurn();
+ }
+
+ probe(command?: string) {
+ const explicit = command?.trim();
+ if (!explicit) return probeClaude();
+ const result = probeCommandVersion(explicit);
+ return result.ok
+ ? { status: "healthy" as const, version: result.version }
+ : { status: "unhealthy" as const, lastError: result.error };
+ }
+
+ async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {
+ return createProcessLane(this, ctx, { onRawStdoutLine: options?.onRawStdoutLine });
+ }
+
+ async spawn(ctx: AdapterLaunchContext): Promise<SpawnedProcess> {
+ // The core materializes AGENTS.md (+ CLAUDE.md symlink) before opening the
+ // lane; Claude Code auto-reads CLAUDE.md from cwd, so no CLI flag is needed.
+ const { spawnEnv } = await prepareCliTransport(ctx, buildClaudeProviderIsolationEnv(ctx));
+ const args = buildClaudeArgs(ctx.config);
+
+ // Let Claude detect it is NOT nested in another Claude Code session.
+ delete spawnEnv.CLAUDECODE;
+
+ // Claude has an extra bespoke discovery step (macOS `.app` bundle
+ // fallback via `resolveClaudeCommand`) that no other driver needs, but
+ // the spawn spec itself is the same as everyone else's. `runtimeConfig.command`
+ // wins over the discovered path when set (uniform across drivers).
+ //
+ // The discovery probe stays lazy: `resolveClaudeCommand` shells out to
+ // `which`/`where` (up to PROBE_TIMEOUT_MS), so when the user pinned an
+ // explicit `command` we must not pay for — or block on — a lookup whose
+ // result `resolveSpawnSpec` would immediately discard.
+ //
+ // Both branches feed the chosen path through `resolveSpawnSpec`'s override
+ // slot, whose "already looks like a path → don't re-resolve" rule keeps us
+ // from PATH-probing a path `resolveClaudeCommand` just resolved.
+ const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command?.trim();
+ const claudeCommand = override || resolveClaudeCommand() || "claude";
+ const spec = resolveSpawnSpec("claude", args, claudeCommand);
+ const proc = spawnAgentProcess(spec.command, spec.args, {
+ cwd: ctx.workingDirectory,
+ env: spawnEnv,
+ shell: spec.shell,
+ });
+
+ // Deliver the initial prompt as the first stream-json line.
+ const stdinMsg = JSON.stringify({
+ type: "user",
+ message: { role: "user", content: [{ type: "text", text: ctx.prompt }] },
+ uuid: this.turnProtocol.rootInputUuid(),
+ ...(ctx.config.sessionId ? { session_id: ctx.config.sessionId } : {}),
+ });
+ proc.stdin?.write(stdinMsg + "\n");
+
+ return { process: proc };
+ }
+
+ normalizeLine(line: string): AdapterEvent[] {
+ return this.eventNormalizer.normalizeLine(line);
+ }
+
+ get currentSessionId(): string | null {
+ return this.eventNormalizer.currentSessionId;
+ }
+
+ /** Both idle and busy messages use the same stream-json user-message shape. */
+ encodeMessage(text: string, sessionId: string | null, opts?: EncodeMessageOptions): string {
+ const uuid = opts?.mode === "idle"
+ ? this.turnProtocol.rootInputUuid()
+ : this.turnProtocol.steeringInputUuid();
+ return JSON.stringify({
+ type: "user",
+ message: { role: "user", content: [{ type: "text", text }] },
+ uuid,
+ ...(opts?.mode === "busy" ? { priority: "now" } : {}),
+ ...(sessionId ? { session_id: sessionId } : {}),
+ });
+ }
+
+}
diff --git a/src/daemon/src/drivers/claudeLaunch.test.ts b/src/daemon/agent-driver/src/adapters/claude/launch.test.ts
similarity index 53%
rename from src/daemon/src/drivers/claudeLaunch.test.ts
rename to src/daemon/agent-driver/src/adapters/claude/launch.test.ts
index 8c1618970..9b1b9f607 100644
--- a/src/daemon/src/drivers/claudeLaunch.test.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/launch.test.ts
@@ -1,7 +1,17 @@
import { describe, it, expect } from "vitest";
-import { buildClaudeArgs } from "./claudeLaunch";
-import { makeRuntimeConfig } from "../runtimeConfig";
-import type { LaunchConfig } from "../types";
+import { buildClaudeArgs } from "./launch.js";
+import type { AdapterLaunchConfig } from "../../internal/adapter.js";
+import type { ClaudeConfig } from "../../contract.js";
+
+function makeRuntimeConfig(overrides: Partial<ClaudeConfig> = {}): ClaudeConfig {
+ return {
+ model: { kind: "default" },
+ provider: { kind: "default" },
+ mode: "default",
+ environment: {},
+ ...overrides,
+ };
+}
/**
* Consistent-drivers plan: Claude no longer hard-codes `--model sonnet` when
@@ -9,15 +19,19 @@ import type { LaunchConfig } from "../types";
* decide" across every driver, matching every non-claude driver's behavior.
*/
describe("buildClaudeArgs — model flag is conditional", () => {
+ it("requests provider user-message acknowledgements for persistent turn ownership", () => {
+ expect(buildClaudeArgs({ runtimeConfig: makeRuntimeConfig() })).toContain("--replay-user-messages");
+ });
+
it("omits --model when runtimeConfig.model.kind === 'default'", () => {
- const config: LaunchConfig = { runtimeConfig: makeRuntimeConfig({ runtime: "claude" }) };
+ const config: AdapterLaunchConfig = { runtimeConfig: makeRuntimeConfig() };
const args = buildClaudeArgs(config);
expect(args).not.toContain("--model");
});
it("emits --model <name> when a named model is set", () => {
- const config: LaunchConfig = {
- runtimeConfig: makeRuntimeConfig({ runtime: "claude", model: { kind: "named", name: "opus" } }),
+ const config: AdapterLaunchConfig = {
+ runtimeConfig: makeRuntimeConfig({ model: { kind: "named", name: "opus" } }),
};
const args = buildClaudeArgs(config);
const modelIdx = args.indexOf("--model");
@@ -26,9 +40,9 @@ describe("buildClaudeArgs — model flag is conditional", () => {
});
it("passes --resume <sessionId> when resuming", () => {
- const config: LaunchConfig = {
+ const config: AdapterLaunchConfig = {
sessionId: "sess-42",
- runtimeConfig: makeRuntimeConfig({ runtime: "claude" }),
+ runtimeConfig: makeRuntimeConfig(),
};
const args = buildClaudeArgs(config);
const idx = args.indexOf("--resume");
diff --git a/src/daemon/src/drivers/claudeLaunch.ts b/src/daemon/agent-driver/src/adapters/claude/launch.ts
similarity index 84%
rename from src/daemon/src/drivers/claudeLaunch.ts
rename to src/daemon/agent-driver/src/adapters/claude/launch.ts
index ef8ebfa5e..5c3812e02 100644
--- a/src/daemon/src/drivers/claudeLaunch.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/launch.ts
@@ -6,15 +6,15 @@
* what makes same-turn steering possible: stdin is a long-lived NDJSON channel
* onto which new user messages can be appended at safe boundaries.
*/
-import type { LaunchConfig } from "../types.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
+import type { AdapterLaunchConfig } from "../../internal/adapter.js";
+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
/** Tools the host disables by default — runtime-native scheduling/plan tools that
* would bypass the host's reminder/task model. Overridable via
* `launchRuntimeFields.disallowedTools`. */
const CLAUDE_DISALLOWED_TOOLS = "EnterPlanMode,ExitPlanMode,ScheduleWakeup,CronCreate,CronList,CronDelete";
-export function buildClaudeArgs(config: LaunchConfig): string[] {
+export function buildClaudeArgs(config: AdapterLaunchConfig): string[] {
const f = resolveLaunchFieldsOrDefault(config.runtimeConfig);
const args = [
"--allow-dangerously-skip-permissions",
@@ -26,6 +26,7 @@ export function buildClaudeArgs(config: LaunchConfig): string[] {
"stream-json",
"--input-format",
"stream-json",
+ "--replay-user-messages",
"--include-partial-messages",
"--disallowed-tools",
f.disallowedTools || CLAUDE_DISALLOWED_TOOLS,
@@ -36,4 +37,3 @@ export function buildClaudeArgs(config: LaunchConfig): string[] {
if (config.sessionId) args.push("--resume", config.sessionId);
return args;
}
-
diff --git a/src/daemon/src/drivers/claudeEventNormalizer.test.ts b/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
similarity index 80%
rename from src/daemon/src/drivers/claudeEventNormalizer.test.ts
rename to src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
index b4e34d378..8601a878e 100644
--- a/src/daemon/src/drivers/claudeEventNormalizer.test.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { ClaudeEventNormalizer } from "./claudeEventNormalizer";
+import { ClaudeEventNormalizer } from "./normalizer.js";
const J = (o: unknown) => JSON.stringify(o);
@@ -59,11 +59,12 @@ describe("ClaudeEventNormalizer.normalizeLine", () => {
it("result → telemetry + turn_end", () => {
const out = new ClaudeEventNormalizer().normalizeLine(
- J({ type: "result", subtype: "success", session_id: "s1", usage: { input_tokens: 3, output_tokens: 5 } }),
+ J({ type: "result", subtype: "success", session_id: "s1", user_message_uuid: "root-1", usage: { input_tokens: 3, output_tokens: 5 } }),
);
const kinds = out.map((e) => e.kind);
expect(kinds).toContain("turn_end");
expect(kinds).toContain("telemetry");
+ expect(out).toContainEqual({ kind: "turn_end", sessionId: "s1", turnOwner: "claude:root-1" });
});
it("result with is_error → error + turn_end", () => {
@@ -86,4 +87,12 @@ describe("ClaudeEventNormalizer.normalizeLine", () => {
expect(kinds.indexOf("error")).toBeGreaterThanOrEqual(0);
expect(kinds.indexOf("error")).toBeLessThan(kinds.indexOf("turn_end"));
});
+
+ it("binds terminals to provider user-message UUIDs rather than payload content", () => {
+ const n = new ClaudeEventNormalizer();
+ const first = J({ type: "result", subtype: "success", session_id: "s1", user_message_uuid: "first" });
+ const second = J({ type: "result", subtype: "success", session_id: "s1", user_message_uuid: "second" });
+ expect(n.normalizeLine(first)).toEqual([{ kind: "turn_end", sessionId: "s1", turnOwner: "claude:first" }]);
+ expect(n.normalizeLine(second)).toEqual([{ kind: "turn_end", sessionId: "s1", turnOwner: "claude:second" }]);
+ });
});
diff --git a/src/daemon/src/drivers/claudeEventNormalizer.ts b/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
similarity index 71%
rename from src/daemon/src/drivers/claudeEventNormalizer.ts
rename to src/daemon/agent-driver/src/adapters/claude/normalizer.ts
index a4aaad1c2..988fca297 100644
--- a/src/daemon/src/drivers/claudeEventNormalizer.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
@@ -1,6 +1,6 @@
/**
* ClaudeEventNormalizer — turns Claude Code's stream-json output into the
- * uniform `ParsedEvent` vocabulary.
+ * uniform `AdapterEvent` vocabulary.
*
* Claude emits one JSON object per line. The shapes we care about:
* - `{type:"system", subtype:"init", session_id}` → session_init
@@ -13,30 +13,33 @@
*
* The `session_id` on any line keeps `currentSessionId` fresh for resume.
*/
-import type { ParsedEvent } from "../types.js";
-import { tryParseJsonLine } from "./utils.js";
+import type { AdapterEvent } from "../../internal/adapter.js";
+import { tryParseJsonLine } from "../../internal/utils.js";
+import type { ClaudeTurnProtocol } from "./turnProtocol.js";
const API_ERROR_RE = /API Error:.*(?:Connection error|\b[45]\d{2}\b)/i;
export class ClaudeEventNormalizer {
private currentSession: string | null = null;
+ constructor(private readonly turnProtocol?: ClaudeTurnProtocol) {}
+
get currentSessionId(): string | null {
return this.currentSession;
}
- normalizeLine(line: string): ParsedEvent[] {
+ normalizeLine(line: string): AdapterEvent[] {
const event = tryParseJsonLine(line) as any;
if (!event) return [];
if (event?.session_id) this.currentSession = event.session_id;
- const out: ParsedEvent[] = [];
+ const out: AdapterEvent[] = [];
switch (event?.type) {
case "system":
- this.handleSystem(event, out);
+ if (event.subtype === "init" || this.acceptsTurnWork()) this.handleSystem(event, out);
break;
case "assistant":
- this.handleAssistant(event, out);
+ if (this.acceptsTurnWork()) this.handleAssistant(event, out);
break;
case "user":
this.handleUser(event, out);
@@ -48,7 +51,7 @@ export class ClaudeEventNormalizer {
return out;
}
- private handleSystem(event: any, out: ParsedEvent[]): void {
+ private handleSystem(event: any, out: AdapterEvent[]): void {
if (event.subtype === "init") {
out.push({ kind: "session_init", sessionId: event.session_id ?? this.currentSession ?? "" });
return;
@@ -71,7 +74,7 @@ export class ClaudeEventNormalizer {
}
}
- private handleAssistant(event: any, out: ParsedEvent[]): void {
+ private handleAssistant(event: any, out: AdapterEvent[]): void {
const content = event?.message?.content;
if (!Array.isArray(content)) return;
for (const block of content) {
@@ -87,7 +90,11 @@ export class ClaudeEventNormalizer {
}
}
- private handleUser(event: any, out: ParsedEvent[]): void {
+ private handleUser(event: any, out: AdapterEvent[]): void {
+ if (event.isReplay === true && typeof event.uuid === "string") {
+ this.turnProtocol?.acknowledge(event.uuid);
+ }
+ if (!this.acceptsTurnWork()) return;
const content = event?.message?.content;
if (!Array.isArray(content)) return;
for (const block of content) {
@@ -95,16 +102,31 @@ export class ClaudeEventNormalizer {
}
}
- private handleResult(event: any, out: ParsedEvent[]): void {
+ private handleResult(event: any, out: AdapterEvent[]): void {
+ const rawOwner = typeof event.user_message_uuid === "string" && event.user_message_uuid.length > 0
+ ? event.user_message_uuid
+ : null;
+ const turnOwner = rawOwner
+ ? this.turnProtocol?.claimResult(rawOwner) ?? (this.turnProtocol ? null : `claude:${rawOwner}`)
+ : null;
+ if (this.turnProtocol && !turnOwner) return;
const usage = this.buildUsageTelemetry(event);
if (usage) out.push(usage);
if (event.is_error || event.subtype === "error_during_execution") {
out.push({ kind: "error", message: String(event.result ?? "Claude runtime error") });
}
- out.push({ kind: "turn_end", sessionId: event.session_id ?? this.currentSession ?? undefined });
+ out.push({
+ kind: "turn_end",
+ sessionId: event.session_id ?? this.currentSession ?? undefined,
+ ...(turnOwner ? { turnOwner } : {}),
+ });
+ }
+
+ private acceptsTurnWork(): boolean {
+ return this.turnProtocol?.acceptsTurnWork() ?? true;
}
- private buildUsageTelemetry(event: any): ParsedEvent | null {
+ private buildUsageTelemetry(event: any): AdapterEvent | null {
const u = event?.usage;
if (!u && event?.total_cost_usd == null) return null;
return {
diff --git a/src/daemon/agent-driver/src/adapters/claude/providerIsolation.test.ts b/src/daemon/agent-driver/src/adapters/claude/providerIsolation.test.ts
new file mode 100644
index 000000000..645d2e85d
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/claude/providerIsolation.test.ts
@@ -0,0 +1,47 @@
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
+import { buildClaudeProviderIsolationEnv } from "./providerIsolation.js";
+
+describe("buildClaudeProviderIsolationEnv", () => {
+ it("does not isolate when runtime config has no provider", async () => {
+ const ctx = fakeLaunchContext("claude", process.cwd());
+ expect(buildClaudeProviderIsolationEnv(ctx)).toEqual({});
+ await expect(ctx.prepared.release({
+ reason: "normal",
+ signal: new AbortController().signal,
+ deadlineAt: Date.now() + 1_000,
+ })).resolves.toBeUndefined();
+ });
+
+ it("does not isolate a default provider", () => {
+ const ctx = fakeLaunchContext("claude", process.cwd(), {
+ config: { runtimeConfig: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default" } },
+ });
+ expect(buildClaudeProviderIsolationEnv(ctx)).toEqual({});
+ });
+
+ it("creates a workspace-local home for a custom provider", () => {
+ const workingDirectory = mkdtempSync(join(tmpdir(), "claude-provider-isolation-"));
+ try {
+ const ctx = fakeLaunchContext("claude", workingDirectory, {
+ config: {
+ runtimeConfig: {
+ model: { kind: "default" },
+ provider: { kind: "custom_endpoint", apiUrl: "https://example.invalid", apiKey: "test-key" },
+ mode: "default",
+ },
+ },
+ });
+ const env = buildClaudeProviderIsolationEnv(ctx);
+ expect(env.HOME).toBe(join(workingDirectory, ".alook", "claude-provider", "home"));
+ expect(env.CLAUDE_CONFIG_DIR).toBe(join(env.HOME!, ".claude"));
+ expect(env.CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST).toBe("1");
+ expect(existsSync(env.CLAUDE_CONFIG_DIR!)).toBe(true);
+ } finally {
+ rmSync(workingDirectory, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/src/daemon/src/drivers/claudeProviderIsolation.ts b/src/daemon/agent-driver/src/adapters/claude/providerIsolation.ts
similarity index 78%
rename from src/daemon/src/drivers/claudeProviderIsolation.ts
rename to src/daemon/agent-driver/src/adapters/claude/providerIsolation.ts
index 8bd792a8c..b6b003e20 100644
--- a/src/daemon/src/drivers/claudeProviderIsolation.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/providerIsolation.ts
@@ -11,10 +11,13 @@
*/
import * as fs from "fs";
import * as path from "path";
-import type { LaunchContext } from "../types.js";
+import type { AdapterLaunchContext } from "../../internal/adapter.js";
-export function buildClaudeProviderIsolationEnv(ctx: LaunchContext): NodeJS.ProcessEnv {
- const hasCustomProvider = Boolean(process.env.ANTHROPIC_BASE_URL && process.env.ANTHROPIC_API_KEY);
+export function buildClaudeProviderIsolationEnv(ctx: AdapterLaunchContext): NodeJS.ProcessEnv {
+ const provider = ctx.config.runtimeConfig && "provider" in ctx.config.runtimeConfig
+ ? ctx.config.runtimeConfig.provider
+ : undefined;
+ const hasCustomProvider = provider?.kind === "custom_endpoint";
if (!hasCustomProvider) return {};
const root = path.join(ctx.workingDirectory, ".alook", "claude-provider");
diff --git a/src/daemon/agent-driver/src/adapters/claude/turnProtocol.test.ts b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.test.ts
new file mode 100644
index 000000000..f4bfe8b41
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+import { ClaudeTurnProtocol } from "./turnProtocol.js";
+
+const uuidOf = (receipt: string) => receipt.slice("claude:".length);
+
+describe("ClaudeTurnProtocol", () => {
+ it("does not admit provider work for a new turn before its root replay acknowledgement", () => {
+ const protocol = new ClaudeTurnProtocol();
+ const root = uuidOf(protocol.beginTurn());
+ expect(protocol.acceptsTurnWork()).toBe(false);
+ protocol.acknowledge(root);
+ expect(protocol.acceptsTurnWork()).toBe(true);
+ });
+
+ it("claims a root result after its provider acknowledgement", () => {
+ const protocol = new ClaudeTurnProtocol();
+ const receipt = protocol.beginTurn();
+ const root = uuidOf(receipt);
+ protocol.acknowledge(root);
+ expect(protocol.claimResult(root)).toBe(receipt);
+ });
+
+ it("defers a root result until unacknowledged steering finishes a follow-on segment", () => {
+ const protocol = new ClaudeTurnProtocol();
+ const receipt = protocol.beginTurn();
+ const root = uuidOf(receipt);
+ const first = protocol.steeringInputUuid();
+ const second = protocol.steeringInputUuid();
+ protocol.acknowledge(root);
+
+ expect(protocol.claimResult(root)).toBeNull();
+ protocol.acknowledge(first);
+ protocol.acknowledge(second);
+ expect(protocol.claimResult(first)).toBeNull();
+ expect(protocol.claimResult(second)).toBe(receipt);
+ });
+
+ it("keeps steering acknowledged before the root result inside that provider segment", () => {
+ const protocol = new ClaudeTurnProtocol();
+ const receipt = protocol.beginTurn();
+ const root = uuidOf(receipt);
+ const steering = protocol.steeringInputUuid();
+ protocol.acknowledge(root);
+ protocol.acknowledge(steering);
+ expect(protocol.claimResult(root)).toBe(receipt);
+ });
+
+ it("suppresses a stale prior-turn result after the next logical turn begins", () => {
+ const protocol = new ClaudeTurnProtocol();
+ const first = uuidOf(protocol.beginTurn());
+ const secondReceipt = protocol.beginTurn();
+ const second = uuidOf(secondReceipt);
+ expect(protocol.claimResult(first)).toBeNull();
+ protocol.acknowledge(second);
+ expect(protocol.claimResult(second)).toBe(secondReceipt);
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts
new file mode 100644
index 000000000..98501a019
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/claude/turnProtocol.ts
@@ -0,0 +1,76 @@
+import { randomUUID } from "node:crypto";
+
+interface DeliveredInput {
+ acknowledged: boolean;
+ followOn: boolean;
+}
+
+/**
+ * Tracks the provider segments that together implement one logical Claude turn.
+ *
+ * Claude may emit a result before every stdin steering frame has been replayed
+ * to stdout. Those not-yet-acknowledged frames become a follow-on provider
+ * segment in the same persistent process. Only the result for the latest
+ * acknowledged follow-on UUID is the logical terminal.
+ */
+export class ClaudeTurnProtocol {
+ private rootUuid: string | null = null;
+ private segmentOwnerUuid: string | null = null;
+ private readonly delivered = new Map<string, DeliveredInput>();
+ private awaitingFollowOn = false;
+ private finalized = false;
+
+ beginTurn(): string {
+ const uuid = randomUUID();
+ this.rootUuid = uuid;
+ this.segmentOwnerUuid = uuid;
+ this.delivered.clear();
+ this.delivered.set(uuid, { acknowledged: false, followOn: false });
+ this.awaitingFollowOn = false;
+ this.finalized = false;
+ return this.receipt(uuid);
+ }
+
+ rootInputUuid(): string {
+ if (!this.rootUuid) this.beginTurn();
+ return this.rootUuid!;
+ }
+
+ steeringInputUuid(): string {
+ const uuid = randomUUID();
+ this.delivered.set(uuid, { acknowledged: false, followOn: this.awaitingFollowOn });
+ return uuid;
+ }
+
+ acknowledge(uuid: string): void {
+ const input = this.delivered.get(uuid);
+ if (!input || this.finalized) return;
+ input.acknowledged = true;
+ if (input.followOn) this.segmentOwnerUuid = uuid;
+ }
+
+ acceptsTurnWork(): boolean {
+ if (!this.rootUuid || this.finalized) return false;
+ return this.delivered.get(this.rootUuid)?.acknowledged === true;
+ }
+
+ /** Returns the logical root receipt only when this is the final provider segment. */
+ claimResult(userMessageUuid: string): string | null {
+ if (this.finalized || !this.rootUuid || userMessageUuid !== this.segmentOwnerUuid) return null;
+ const owner = this.delivered.get(userMessageUuid);
+ if (owner) owner.acknowledged = true;
+ const unacknowledged = [...this.delivered.entries()]
+ .filter(([, input]) => !input.acknowledged);
+ if (unacknowledged.length > 0) {
+ this.awaitingFollowOn = true;
+ for (const [, input] of unacknowledged) input.followOn = true;
+ return null;
+ }
+ this.finalized = true;
+ return this.receipt(this.rootUuid);
+ }
+
+ private receipt(uuid: string): string {
+ return `claude:${uuid}`;
+ }
+}
diff --git a/src/daemon/src/drivers/codexHome.ts b/src/daemon/agent-driver/src/adapters/codex/home.ts
similarity index 55%
rename from src/daemon/src/drivers/codexHome.ts
rename to src/daemon/agent-driver/src/adapters/codex/home.ts
index 688281623..d82a34763 100644
--- a/src/daemon/src/drivers/codexHome.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/home.ts
@@ -12,7 +12,7 @@
import * as os from "os";
import * as path from "path";
-export function readConfiguredCodexHome(env: NodeJS.ProcessEnv): string | null {
+function readConfiguredCodexHome(env: NodeJS.ProcessEnv): string | null {
const raw = env.CODEX_HOME;
return typeof raw === "string" && raw.trim().length > 0 ? raw : null;
}
@@ -25,17 +25,3 @@ export function resolveCodexHomeRootFromEnv(
if (raw) return path.resolve(opts.cwd ?? process.cwd(), raw);
return path.join(opts.defaultHomeDir ?? os.homedir(), ".codex");
}
-
-export function hasConfiguredCodexHome(env: NodeJS.ProcessEnv = process.env): boolean {
- return Boolean(readConfiguredCodexHome(env));
-}
-
-/** Candidate state roots: the home root itself, and a nested `.codex/`. */
-export function codexStateRootCandidates(homeDirOrCodexRoot: string): string[] {
- return [homeDirOrCodexRoot, path.join(homeDirOrCodexRoot, ".codex")];
-}
-
-/** Candidate session roots: `<stateRoot>/sessions` for each state-root candidate. */
-export function codexSessionRootCandidates(homeDirOrCodexRoot: string): string[] {
- return codexStateRootCandidates(homeDirOrCodexRoot).map((root) => path.join(root, "sessions"));
-}
diff --git a/src/daemon/src/drivers/codex.test.ts b/src/daemon/agent-driver/src/adapters/codex/index.test.ts
similarity index 75%
rename from src/daemon/src/drivers/codex.test.ts
rename to src/daemon/agent-driver/src/adapters/codex/index.test.ts
index 3a1bec5fb..c5e9a0a28 100644
--- a/src/daemon/src/drivers/codex.test.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.test.ts
@@ -3,13 +3,12 @@ import { EventEmitter } from "events";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
-import { CodexDriver } from "./codex";
-import type { LaunchContext } from "../types";
-import { CredentialBroker } from "../credentials/credentialProxy";
-import { readDaemonVersion } from "../version";
+import { CodexDriver } from "./index.js";
+import type { AdapterLaunchContext } from "../../internal/adapter.js";
+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
-vi.mock("../runtime/killTree", async () => {
- const actual = await vi.importActual<typeof import("../runtime/killTree")>("../runtime/killTree");
+vi.mock("../../internal/killTree.js", async () => {
+ const actual = await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js");
return {
...actual,
spawnAgentProcess: () => {
@@ -24,23 +23,12 @@ function mkTmp(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), "codex-test-"));
}
-function baseCtx(): LaunchContext {
+function baseCtx(): AdapterLaunchContext {
const tmp = mkTmp();
- return {
- agentId: "agent_1",
- launchId: "launch_1",
- workingDirectory: tmp,
+ return fakeLaunchContext("codex", tmp, {
standingPrompt: "You are Codex.",
prompt: "hi",
- credentialProxy: {
- broker: new CredentialBroker({ upstreamBaseUrl: "https://u.test", voucherDir: mkTmp() }),
- proxyUrl: "http://127.0.0.1:9/proxy",
- runnerKey: "sk_agent_test",
- capabilities: ["send", "read"],
- },
- config: {},
- mockCliTransport: true,
- };
+ });
}
describe("CodexDriver initialize payload", () => {
@@ -57,17 +45,17 @@ describe("CodexDriver initialize payload", () => {
expect(initPayload.jsonrpc).toBe("2.0");
expect(initPayload.method).toBe("initialize");
- expect(initPayload.params.clientInfo).toEqual({ name: "alook-daemon", version: readDaemonVersion() });
+ expect(initPayload.params.clientInfo).toEqual({ name: "alook-agent-driver", version: "0.1.14" });
});
});
// The `thread/start` (or resume) RESULT line carries the new thread id and is
-// what the normalizer adopts as the session — feeding it to parseLine is what
+// what the normalizer adopts as the session — feeding it to normalizeLine is what
// triggers the deferred initial-prompt delivery.
function threadStartResult(threadId: string): string {
return JSON.stringify({ jsonrpc: "2.0", id: 2, result: { thread: { id: threadId } } });
}
-// The `thread/started` NOTIFICATION — Codex emits this too, so parseLine sees a
+// The `thread/started` NOTIFICATION — Codex emits this too, so normalizeLine sees a
// SECOND session_init for the same thread.
function threadStartedNotif(threadId: string): string {
return JSON.stringify({ jsonrpc: "2.0", method: "thread/started", params: { thread: { id: threadId } } });
@@ -94,7 +82,7 @@ describe("CodexDriver initial-prompt delivery", () => {
expect(turnStarts(stdinWrites(proc))).toHaveLength(0);
// Feed the thread/start result → thread adopted → prompt delivered.
- driver.parseLine(threadStartResult("th_abc"));
+ driver.normalizeLine(threadStartResult("th_abc"));
const turns = turnStarts(stdinWrites(proc));
expect(turns).toHaveLength(1);
@@ -107,8 +95,8 @@ describe("CodexDriver initial-prompt delivery", () => {
const { process: proc } = await driver.spawn(baseCtx());
await Promise.resolve();
- driver.parseLine(threadStartResult("th_abc")); // session_init #1
- driver.parseLine(threadStartedNotif("th_abc")); // session_init #2 (same thread)
+ driver.normalizeLine(threadStartResult("th_abc")); // session_init #1
+ driver.normalizeLine(threadStartedNotif("th_abc")); // session_init #2 (same thread)
expect(turnStarts(stdinWrites(proc))).toHaveLength(1);
});
@@ -121,7 +109,7 @@ describe("CodexDriver initial-prompt delivery", () => {
await Promise.resolve();
// resume result carries the (same) thread id.
- driver.parseLine(threadStartResult("th_prior"));
+ driver.normalizeLine(threadStartResult("th_prior"));
const turns = turnStarts(stdinWrites(proc));
expect(turns).toHaveLength(1);
@@ -136,15 +124,15 @@ describe("CodexDriver initial-prompt delivery", () => {
const { process: proc } = await driver.spawn(ctx);
await Promise.resolve();
- driver.parseLine(threadStartResult("th_abc"));
+ driver.normalizeLine(threadStartResult("th_abc"));
expect(turnStarts(stdinWrites(proc))).toHaveLength(0);
});
});
// A JSON-RPC error response to thread/resume — the prior thread's rollout is gone.
-function missingRolloutError(): string {
- return JSON.stringify({ jsonrpc: "2.0", id: 2, error: { message: "no rollout found for thread id th_prior" } });
+function missingRolloutError(message = "no rollout found for thread id th_prior"): string {
+ return JSON.stringify({ jsonrpc: "2.0", id: 2, error: { message } });
}
function threadStarts(writes: string[]): any[] {
return writes.map((w) => JSON.parse(w.trim())).filter((m) => m.method === "thread/start");
@@ -158,7 +146,7 @@ describe("CodexDriver missing-rollout resume recovery", () => {
const { process: proc } = await driver.spawn(ctx);
await Promise.resolve(); // flush handshake (writes thread/resume)
- const returned = driver.parseLine(missingRolloutError());
+ const returned = driver.normalizeLine(missingRolloutError());
// The resume error is swallowed — not surfaced to the manager as a fault.
expect(returned.some((e: any) => e.kind === "error")).toBe(false);
@@ -175,8 +163,8 @@ describe("CodexDriver missing-rollout resume recovery", () => {
const { process: proc } = await driver.spawn(ctx);
await Promise.resolve();
- driver.parseLine(missingRolloutError()); // → fresh thread/start, prompt still pending
- driver.parseLine(threadStartResult("th_fresh")); // fresh thread adopted
+ driver.normalizeLine(missingRolloutError()); // → fresh thread/start, prompt still pending
+ driver.normalizeLine(threadStartResult("th_fresh")); // fresh thread adopted
const turns = turnStarts(stdinWrites(proc));
expect(turns).toHaveLength(1);
@@ -184,6 +172,17 @@ describe("CodexDriver missing-rollout resume recovery", () => {
expect(turns[0].params.input).toEqual([{ type: "text", text: "hi" }]);
});
+ it("recognizes a missing rollout when the error leads with not-found", async () => {
+ const driver = new CodexDriver();
+ const ctx = baseCtx();
+ ctx.config = { sessionId: "th_prior" };
+ const { process: proc } = await driver.spawn(ctx);
+ await Promise.resolve();
+
+ expect(driver.normalizeLine(missingRolloutError("not found for requested rollout"))).toEqual([]);
+ expect(threadStarts(stdinWrites(proc))).toHaveLength(1);
+ });
+
it("a successful resume does NOT trigger the fallback (no spurious fresh thread/start)", async () => {
const driver = new CodexDriver();
const ctx = baseCtx();
@@ -192,7 +191,7 @@ describe("CodexDriver missing-rollout resume recovery", () => {
await Promise.resolve();
// Resume succeeds → session_init for the resumed thread.
- driver.parseLine(threadStartResult("th_prior"));
+ driver.normalizeLine(threadStartResult("th_prior"));
// No fallback thread/start — only the handshake's thread/resume happened.
expect(threadStarts(stdinWrites(proc))).toHaveLength(0);
@@ -201,14 +200,14 @@ describe("CodexDriver missing-rollout resume recovery", () => {
});
});
-describe("CodexDriver encodeStdinMessage — turn/steer expectedTurnId", () => {
+describe("CodexDriver encodeMessage — turn/steer expectedTurnId", () => {
it("busy steer includes expectedTurnId = the active turn id (codex requires it)", () => {
const driver = new CodexDriver();
// Adopt a thread + observe a turn/started so the normalizer has both ids.
- driver.parseLine(threadStartResult("th_1"));
- driver.parseLine(JSON.stringify({ jsonrpc: "2.0", method: "turn/started", params: { threadId: "th_1", turn: { id: "turn_9" } } }));
+ driver.normalizeLine(threadStartResult("th_1"));
+ driver.normalizeLine(JSON.stringify({ jsonrpc: "2.0", method: "turn/started", params: { threadId: "th_1", turn: { id: "turn_9" } } }));
- const encoded = driver.encodeStdinMessage("hang on", "th_1", { mode: "busy" });
+ const encoded = driver.encodeMessage("hang on", "th_1", { mode: "busy" });
const msg = JSON.parse(encoded!);
expect(msg.method).toBe("turn/steer");
expect(msg.params.threadId).toBe("th_1");
@@ -218,8 +217,8 @@ describe("CodexDriver encodeStdinMessage — turn/steer expectedTurnId", () => {
it("falls back to a fresh turn/start when there is no live turn to steer", () => {
const driver = new CodexDriver();
- driver.parseLine(threadStartResult("th_1")); // thread but no active turn
- const encoded = driver.encodeStdinMessage("hi", "th_1", { mode: "busy" });
+ driver.normalizeLine(threadStartResult("th_1")); // thread but no active turn
+ const encoded = driver.encodeMessage("hi", "th_1", { mode: "busy" });
const msg = JSON.parse(encoded!);
// No turn id → don't send an invalid steer; start a fresh turn instead.
expect(msg.method).toBe("turn/start");
@@ -228,9 +227,9 @@ describe("CodexDriver encodeStdinMessage — turn/steer expectedTurnId", () => {
it("idle message is always a fresh turn/start (no expectedTurnId)", () => {
const driver = new CodexDriver();
- driver.parseLine(threadStartResult("th_1"));
- driver.parseLine(JSON.stringify({ jsonrpc: "2.0", method: "turn/started", params: { threadId: "th_1", turn: { id: "turn_9" } } }));
- const encoded = driver.encodeStdinMessage("new topic", "th_1", { mode: "idle" });
+ driver.normalizeLine(threadStartResult("th_1"));
+ driver.normalizeLine(JSON.stringify({ jsonrpc: "2.0", method: "turn/started", params: { threadId: "th_1", turn: { id: "turn_9" } } }));
+ const encoded = driver.encodeMessage("new topic", "th_1", { mode: "idle" });
const msg = JSON.parse(encoded!);
expect(msg.method).toBe("turn/start");
expect(msg.params.expectedTurnId).toBeUndefined();
diff --git a/src/daemon/src/drivers/codex.ts b/src/daemon/agent-driver/src/adapters/codex/index.ts
similarity index 77%
rename from src/daemon/src/drivers/codex.ts
rename to src/daemon/agent-driver/src/adapters/codex/index.ts
index 752958e77..e54d85871 100644
--- a/src/daemon/src/drivers/codex.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.ts
@@ -13,56 +13,37 @@
* Handshake (queued on spawn): `initialize` → then `thread/start` (or
* `thread/resume` with the prior threadId). The thread id is the session id.
*/
-import type { Driver, EncodeOpts, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
-import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { CodexEventNormalizer } from "./codexEventNormalizer.js";
-import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
-import { resolveCodexHomeRootFromEnv } from "./codexHome.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { spawnAgentProcess } from "../runtime/killTree.js";
-import { jsonRpcRequest } from "./utils.js";
-import { getDaemonClientInfo } from "../version.js";
-
-/** True if a resume error means the prior thread rollout is gone. */
-export function isCodexMissingRolloutError(message: string): boolean {
+import type {
+ BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, RuntimeLane,
+ RuntimeLaneOpenOptions, SpawnedProcess,
+} from "../../internal/adapter.js";
+import { createProcessLane } from "../../controller/process-host.js";
+import { prepareCliTransport } from "../../internal/cliTransport.js";
+import { CodexEventNormalizer } from "./normalizer.js";
+import { probeCliRuntime, resolveSpawnSpec } from "../../internal/probe.js";
+import { resolveCodexHomeRootFromEnv } from "./home.js";
+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
+import { spawnAgentProcess } from "../../internal/killTree.js";
+import { jsonRpcRequest } from "../../internal/utils.js";
+
+/** True when Codex cannot resume because the prior thread rollout is gone. */
+function isCodexMissingRolloutError(message: string): boolean {
return (
/\bno\s+rollout\s+found\b/i.test(message) ||
/\bmissing\s+rollout\b/i.test(message) ||
/\brollout\b.*\b(not found|missing)\b/i.test(message) ||
- /\bthread\b.*\b(not found|missing)\b/i.test(message) ||
- /\bmissing\s+thread\b/i.test(message)
+ /\b(not found|missing)\b.*\brollout\b/i.test(message)
);
}
-/**
- * Classify a Codex resume failure. A missing rollout is recoverable: fall back
- * to a fresh thread (the host should prepend a recovery notice to the prompt).
- */
-export function classifyCodexResumeError(
- message: string,
-): { kind: "missing_rollout"; recoveryAction: "fallback_fresh_thread" } | { kind: "other" } {
- return isCodexMissingRolloutError(message)
- ? { kind: "missing_rollout", recoveryAction: "fallback_fresh_thread" }
- : { kind: "other" };
-}
-
-export class CodexDriver implements Driver {
+export class CodexDriver implements BackendAdapter {
readonly id = "codex";
- readonly lifecycle = { kind: "persistent", stdin: "gated", inFlightWake: "queue" } as const;
- readonly session = { recovery: "resume_or_fresh" } as const;
- readonly model = {
- detectedModelsVerifiedAs: "launchable",
- toLaunchSpec: (modelId: string) => ({ params: { model: modelId } }),
- } as const;
-
- readonly supportsNativeStandingPrompt = true;
-
- readonly capabilities = {
- reasoningEffort: true,
- fastMode: true,
- disallowedTools: false,
- command: true,
- sessionResumeMode: "by-id",
+ readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
+ readonly execution = {
+ lifetime: "session",
+ transport: { kind: "stdio_rpc", protocol: "codex.app-server.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
} as const;
private readonly eventNormalizer = new CodexEventNormalizer();
@@ -71,9 +52,9 @@ export class CodexDriver implements Driver {
private codexHomeRoot: string | null = null;
/**
* The spawned process, retained so the initial-prompt `turn/start` can be
- * written once the thread id is adopted (see `parseLine`). Null until spawn.
+ * written once the thread id is adopted (see `normalizeLine`). Null until spawn.
*/
- private proc: SpawnResult["process"] | null = null;
+ private proc: SpawnedProcess["process"] | null = null;
/**
* The initial user message drained into `ctx.prompt` at spawn, held until the
* first `session_init` (thread adopted) lets us submit it as a `turn/start`.
@@ -87,7 +68,7 @@ export class CodexDriver implements Driver {
* When spawn issued a `thread/resume`, the `thread/start` params to fall back
* to if that resume fails with "no rollout found" (the prior thread's rollout
* is gone). Null once we're not resuming, or once the fallback has fired. This
- * powers the missing-rollout recovery in `parseLine`: re-issue a FRESH
+ * powers the missing-rollout recovery in `normalizeLine`: re-issue a FRESH
* `thread/start` (no threadId) on the same live process, keeping
* `pendingInitialPrompt` so the fresh thread's `session_init` still delivers it.
*/
@@ -101,15 +82,19 @@ export class CodexDriver implements Driver {
return this.codexHomeRoot;
}
- probe() {
+ probe(command?: string) {
// probeCliRuntime spawns `--version` — a missing vendored binary (npm
// package resolves but the aarch64 blob is absent) fails there even
// though resolveCommandOnPath returned a JS wrapper. See
// plans/community-machine-presence-fix.md.
- return probeCliRuntime("codex");
+ return probeCliRuntime("codex", {}, command);
}
- async spawn(ctx: LaunchContext): Promise<SpawnResult> {
+ async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {
+ return createProcessLane(this, ctx, { onRawStdoutLine: options?.onRawStdoutLine });
+ }
+
+ async spawn(ctx: AdapterLaunchContext): Promise<SpawnedProcess> {
const { spawnEnv } = await prepareCliTransport(ctx);
// Resolve the Codex home so resume can find its session rollout (and so a
// host could surface "missing rollout" recovery — see classifyCodexResumeError).
@@ -123,22 +108,22 @@ export class CodexDriver implements Driver {
shell: spec.shell,
});
this.proc = proc;
- // Hold the initial user message until the thread id is adopted; `parseLine`
+ // Hold the initial user message until the thread id is adopted; `normalizeLine`
// submits it as a `turn/start` on the first `session_init`. Empty/whitespace
// (a bare wake with no message) → no pending prompt, so no empty turn.
const initialPrompt = ctx.prompt?.trim() ? ctx.prompt : null;
this.pendingInitialPrompt = initialPrompt;
// Async handshake: initialize, then thread/start|resume. This ONLY sets up
- // the thread — the user prompt is delivered later (see `parseLine`), because
+ // the thread — the user prompt is delivered later (see `normalizeLine`), because
// `turn/start` needs the threadId that arrives in this call's response. (The
- // standing/system prompt is separate: it reaches Codex via the AGENTS.md
- // that prepareCliTransport writes into the workdir, auto-read from cwd.)
+ // standing/system prompt is separate: it reaches Codex via the
+ // core-materialized AGENTS.md, auto-read from cwd.)
queueMicrotask(() => {
proc.stdin?.write(
jsonRpcRequest(
"initialize",
- { clientInfo: getDaemonClientInfo(), capabilities: { experimentalApi: true } },
+ { clientInfo: { name: "alook-agent-driver", version: "0.1.14" }, capabilities: { experimentalApi: true } },
this.nextRequestId(),
) + "\n",
);
@@ -147,7 +132,7 @@ export class CodexDriver implements Driver {
const resuming = Boolean(ctx.config.sessionId);
// Fresh-thread params (no threadId) — used directly for a fresh spawn, and
// stashed as the resume fallback so a "no rollout found" resume can retry
- // as a fresh thread (see parseLine).
+ // as a fresh thread (see normalizeLine).
const freshParams: Record<string, unknown> = {
cwd: ctx.workingDirectory,
approvalPolicy: "never",
@@ -192,7 +177,7 @@ export class CodexDriver implements Driver {
* `session_init` delivers it via the latch above. Without this, a stale
* sessionId wedges the bot: resume errors out, no turn ever runs.
*/
- parseLine(line: string): ParsedEvent[] {
+ normalizeLine(line: string): AdapterEvent[] {
const events = this.eventNormalizer.normalizeLine(line);
// Missing-rollout resume recovery — before any session_init is adopted.
@@ -239,7 +224,7 @@ export class CodexDriver implements Driver {
}
/** busy → `turn/steer` against the active turn; idle → fresh `turn/start`. */
- encodeStdinMessage(text: string, sessionId: string | null, opts?: EncodeOpts): string | null {
+ encodeMessage(text: string, sessionId: string | null, opts?: EncodeMessageOptions): string | null {
const threadId = sessionId ?? this.eventNormalizer.currentSessionId;
if (!threadId) return null;
if (opts?.mode === "idle") return this.buildTurnStart(threadId, text);
@@ -257,7 +242,4 @@ export class CodexDriver implements Driver {
);
}
- buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config);
- }
}
diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
new file mode 100644
index 000000000..053c55dce
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
@@ -0,0 +1,333 @@
+/**
+ * Tests for `CodexEventNormalizer` — in particular the tool_call/tool_output
+ * symmetry fix from plans/wire-gated-busy-steering-daemon.md (§9c): before
+ * this fix, `handleItemCompleted` had no case for `fileChange`, `webSearch`,
+ * or `collabAgentToolCall`, so `outstandingToolUses` (tracked by the manager
+ * via these `AdapterEvent`s) would permanently increment on the first such
+ * item of a turn and never come back down.
+ */
+import { describe, it, expect } from "vitest";
+import { CodexEventNormalizer } from "./normalizer.js";
+
+function notify(method: string, params: unknown): string {
+ return JSON.stringify({ jsonrpc: "2.0", method, params });
+}
+
+function adoptRootTurn(n: CodexEventNormalizer, threadId: string, turnId: string): void {
+ n.normalizeLine(notify("thread/started", { thread: { id: threadId } }));
+ n.normalizeLine(notify("turn/started", { threadId, turn: { id: turnId, status: "inProgress" } }));
+}
+
+describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
+ it("fileChange: item/started then item/completed emits tool_call then tool_output", () => {
+ const n = new CodexEventNormalizer();
+ const started = n.normalizeLine(notify("item/started", { item: { type: "fileChange" } }));
+ expect(started).toEqual([{ kind: "tool_call", name: "file_change", input: {} }]);
+
+ const completed = n.normalizeLine(notify("item/completed", { item: { type: "fileChange" } }));
+ expect(completed).toEqual([{ kind: "tool_output", name: "file_change" }]);
+ });
+
+ it("fileChange consumes raw changes at the adapter boundary and emits only an ordered-unique flat path", () => {
+ const n = new CodexEventNormalizer();
+ const started = n.normalizeLine(notify("item/started", {
+ item: {
+ type: "fileChange",
+ changes: [
+ { path: " a.ts ", diff: "secret-a" },
+ { path: "" },
+ { path: 42 },
+ { path: "b.ts", content: "secret-b" },
+ { path: "a.ts" },
+ ],
+ path: "ignored-fallback.ts",
+ diff: "top-secret",
+ content: "top-secret-content",
+ },
+ }));
+
+ expect(started).toEqual([
+ { kind: "tool_call", name: "file_change", input: { path: "a.ts, b.ts" } },
+ ]);
+ expect(JSON.stringify(started)).not.toContain("changes");
+ expect(JSON.stringify(started)).not.toContain("secret");
+
+ const completed = n.normalizeLine(notify("item/completed", { item: { type: "fileChange" } }));
+ expect(completed).toEqual([{ kind: "tool_output", name: "file_change" }]);
+ });
+
+ it("fileChange flattens a legacy top-level path when changes are absent", () => {
+ const started = new CodexEventNormalizer().normalizeLine(notify("item/started", {
+ item: { type: "fileChange", path: " legacy.ts ", diff: "secret" },
+ }));
+
+ expect(started).toEqual([
+ { kind: "tool_call", name: "file_change", input: { path: "legacy.ts" } },
+ ]);
+ });
+
+ it("fileChange falls back to a valid top-level path when changes contain no valid paths", () => {
+ const started = new CodexEventNormalizer().normalizeLine(notify("item/started", {
+ item: {
+ type: "fileChange",
+ changes: [{ path: " " }, { path: 42 }, { diff: "secret" }],
+ path: "fallback.ts",
+ },
+ }));
+
+ expect(started).toEqual([
+ { kind: "tool_call", name: "file_change", input: { path: "fallback.ts" } },
+ ]);
+ });
+
+ it("webSearch: item/started then item/completed emits tool_call then tool_output", () => {
+ const n = new CodexEventNormalizer();
+ const started = n.normalizeLine(notify("item/started", { item: { type: "webSearch" } }));
+ expect(started).toEqual([{ kind: "tool_call", name: "web_search", input: { type: "webSearch" } }]);
+
+ const completed = n.normalizeLine(notify("item/completed", { item: { type: "webSearch" } }));
+ expect(completed).toEqual([{ kind: "tool_output", name: "web_search" }]);
+ });
+
+ it("collabAgentToolCall: item/started then item/completed emits tool_call then tool_output", () => {
+ const n = new CodexEventNormalizer();
+ const started = n.normalizeLine(notify("item/started", { item: { type: "collabAgentToolCall" } }));
+ expect(started).toEqual([{ kind: "tool_call", name: "collab_tool_call", input: { type: "collabAgentToolCall" } }]);
+
+ const completed = n.normalizeLine(notify("item/completed", { item: { type: "collabAgentToolCall" } }));
+ expect(completed).toEqual([{ kind: "tool_output", name: "collab_tool_call" }]);
+ });
+
+ it("commandExecution: item/started then item/completed still pairs correctly (regression — 9b removed markProgress from this handler)", () => {
+ const n = new CodexEventNormalizer();
+ const started = n.normalizeLine(notify("item/started", { item: { type: "commandExecution" } }));
+ expect(started).toEqual([{ kind: "tool_call", name: "shell", input: { type: "commandExecution" } }]);
+
+ const completed = n.normalizeLine(notify("item/completed", { item: { type: "commandExecution" } }));
+ expect(completed).toEqual([{ kind: "tool_output", name: "shell" }]);
+ });
+
+ it("mcpToolCall: item/started then item/completed still pairs correctly (regression — 9b removed markProgress from this handler)", () => {
+ const n = new CodexEventNormalizer();
+ const started = n.normalizeLine(notify("item/started", { item: { type: "mcpToolCall", name: "search" } }));
+ expect(started).toEqual([
+ { kind: "tool_call", name: "mcp_search", input: { type: "mcpToolCall", name: "search" } },
+ ]);
+
+ const completed = n.normalizeLine(notify("item/completed", { item: { type: "mcpToolCall", name: "search" } }));
+ expect(completed).toEqual([{ kind: "tool_output", name: "mcp_search" }]);
+ });
+
+ it("does not expose canSteerBusy or a turnState field (dead/redundant driver-level gate must not silently reappear)", () => {
+ const n = new CodexEventNormalizer();
+ expect((n as unknown as { canSteerBusy?: unknown }).canSteerBusy).toBeUndefined();
+ expect((n as unknown as { turnState?: unknown }).turnState).toBeUndefined();
+ });
+});
+
+describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurnId)", () => {
+ it("captures params.turn.id on turn/started and exposes it via currentTurnId", () => {
+ const n = new CodexEventNormalizer();
+ expect(n.currentTurnId).toBeNull();
+ adoptRootTurn(n, "th_1", "turn_abc");
+ expect(n.currentTurnId).toBe("turn_abc");
+ });
+
+ it("clears the turn id on turn/completed (no live turn to steer after)", () => {
+ const n = new CodexEventNormalizer();
+ adoptRootTurn(n, "th_1", "turn_abc");
+ expect(n.currentTurnId).toBe("turn_abc");
+ n.normalizeLine(notify("turn/completed", { threadId: "th_1", turn: { id: "turn_abc", status: "completed" } }));
+ expect(n.currentTurnId).toBeNull();
+ });
+
+ it("clears the turn id on an interrupted/failed turn too", () => {
+ const n = new CodexEventNormalizer();
+ adoptRootTurn(n, "th_1", "turn_x");
+ n.normalizeLine(notify("turn/completed", { threadId: "th_1", turn: { id: "turn_x", status: "failed" } }));
+ expect(n.currentTurnId).toBeNull();
+ });
+
+ it("ignores child and unknown completions without clearing or terminating the active root turn", () => {
+ const n = new CodexEventNormalizer();
+ adoptRootTurn(n, "root-thread", "root-turn");
+
+ expect(n.normalizeLine(notify("turn/completed", {
+ threadId: "child-thread-1",
+ turn: { id: "child-turn-1", status: "completed" },
+ }))).toEqual([]);
+ expect(n.normalizeLine(notify("turn/completed", {
+ threadId: "root-thread",
+ turn: { id: "unknown-turn", status: "completed" },
+ }))).toEqual([]);
+ expect(n.currentSessionId).toBe("root-thread");
+ expect(n.currentTurnId).toBe("root-turn");
+
+ expect(n.normalizeLine(notify("turn/completed", {
+ threadId: "root-thread",
+ turn: { id: "root-turn", status: "completed" },
+ }))).toEqual([{ kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:root-turn" }]);
+ expect(n.currentTurnId).toBeNull();
+ });
+
+ it("reopens and re-closes only the matching completed root vendor turn", () => {
+ const n = new CodexEventNormalizer();
+ adoptRootTurn(n, "root-thread", "root-turn");
+ const completed = notify("turn/completed", {
+ threadId: "root-thread",
+ turn: { id: "root-turn", status: "completed" },
+ });
+
+ expect(n.normalizeLine(completed)).toEqual([{ kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:root-turn" }]);
+ expect(n.currentTurnId).toBeNull();
+ expect(n.normalizeLine(completed)).toEqual([]);
+ expect(n.normalizeLine(notify("rawResponseItem/completed", {
+ threadId: "child-thread",
+ turnId: "root-turn",
+ }))).toEqual([]);
+ expect(n.normalizeLine(notify("rawResponseItem/completed", {
+ threadId: "root-thread",
+ turnId: "stale-turn",
+ }))).toEqual([]);
+
+ expect(n.normalizeLine(notify("rawResponseItem/completed", {
+ threadId: "root-thread",
+ turnId: "root-turn",
+ }))).toEqual([{ kind: "internal_progress", source: "codex_raw_item", itemType: "rawResponseItem" }]);
+ expect(n.normalizeLine(completed)).toEqual([{ kind: "turn_end", sessionId: "root-thread", turnOwner: "codex:root-thread:root-turn" }]);
+ expect(n.normalizeLine(completed)).toEqual([]);
+
+ expect(n.normalizeLine(notify("turn/started", {
+ threadId: "root-thread",
+ turn: { id: "next-turn", status: "inProgress" },
+ }))).toEqual([
+ { kind: "turn_owner", receipt: "codex:root-thread:next-turn" },
+ { kind: "thinking", text: "" },
+ ]);
+ expect(n.normalizeLine(completed)).toEqual([]);
+ expect(n.currentTurnId).toBe("next-turn");
+ });
+
+ it("clears terminal ownership when a new thread is explicitly adopted and rejects an unowned terminal", () => {
+ const n = new CodexEventNormalizer();
+ adoptRootTurn(n, "old-thread", "old-turn");
+ n.normalizeLine(notify("turn/completed", {
+ threadId: "old-thread",
+ turn: { id: "old-turn", status: "completed" },
+ }));
+
+ n.adoptThreadId("new-thread");
+ expect(n.currentSessionId).toBe("new-thread");
+ expect(n.currentTurnId).toBeNull();
+ expect(n.normalizeLine(notify("rawResponseItem/completed", {
+ threadId: "old-thread",
+ turnId: "old-turn",
+ }))).toEqual([]);
+ expect(n.normalizeLine(notify("turn/completed", {
+ threadId: "new-thread",
+ turn: { status: "completed" },
+ }))).toEqual([]);
+ });
+
+ it("ignores child thread and turn announcements after the root is adopted", () => {
+ const n = new CodexEventNormalizer();
+ adoptRootTurn(n, "root-thread", "root-turn");
+
+ expect(n.normalizeLine(notify("thread/started", { thread: { id: "child-thread" } }))).toEqual([]);
+ expect(n.normalizeLine(notify("turn/started", {
+ threadId: "child-thread",
+ turn: { id: "child-turn", status: "inProgress" },
+ }))).toEqual([]);
+ expect(n.currentSessionId).toBe("root-thread");
+ expect(n.currentTurnId).toBe("root-turn");
+ });
+
+ it("filters child output and tool events from the root event stream", () => {
+ const n = new CodexEventNormalizer();
+ adoptRootTurn(n, "root-thread", "root-turn");
+
+ expect(n.normalizeLine(notify("item/agentMessage/delta", {
+ threadId: "child-thread",
+ turnId: "child-turn",
+ delta: "child leak",
+ }))).toEqual([]);
+ expect(n.normalizeLine(notify("item/started", {
+ threadId: "child-thread",
+ turnId: "child-turn",
+ item: { type: "commandExecution", command: "secret" },
+ }))).toEqual([]);
+ expect(n.currentSessionId).toBe("root-thread");
+ expect(n.currentTurnId).toBe("root-turn");
+ });
+});
+
+describe("CodexEventNormalizer — session_init dedup (result + thread/started notification)", () => {
+ function result(id: string): string {
+ return JSON.stringify({ jsonrpc: "2.0", id: 2, result: { thread: { id } } });
+ }
+ it("emits session_init ONCE for a thread announced twice (result then notification)", () => {
+ const n = new CodexEventNormalizer();
+ const a = n.normalizeLine(result("th_1"));
+ const b = n.normalizeLine(notify("thread/started", { thread: { id: "th_1" } }));
+ expect(a.filter((e) => e.kind === "session_init")).toHaveLength(1);
+ expect(b.filter((e) => e.kind === "session_init")).toHaveLength(0); // deduped
+ // but the id is still adopted regardless of which arrived.
+ expect(n.currentSessionId).toBe("th_1");
+ });
+ it("does not let a later child thread result replace the adopted root thread", () => {
+ const n = new CodexEventNormalizer();
+ n.normalizeLine(result("th_1"));
+ const child = n.normalizeLine(result("th_2"));
+ expect(child.filter((e) => e.kind === "session_init")).toHaveLength(0);
+ expect(n.currentSessionId).toBe("th_1");
+ });
+ it("adopts the id from the notification even when the result never emitted it (notification first)", () => {
+ const n = new CodexEventNormalizer();
+ const b = n.normalizeLine(notify("thread/started", { thread: { id: "th_x" } }));
+ expect(b.filter((e) => e.kind === "session_init")).toHaveLength(1);
+ expect(n.currentSessionId).toBe("th_x");
+ });
+});
+
+describe("CodexEventNormalizer — complete owned event family", () => {
+ it("normalizes diagnostics, telemetry, lifecycle boundaries, fallbacks, and invalid envelopes", () => {
+ const n = new CodexEventNormalizer();
+ expect(n.normalizeLine(JSON.stringify({ jsonrpc: "2.0", result: {} }))).toEqual([]);
+ n.normalizeLine(notify("thread/started", { thread: { id: "root" } }));
+ expect(n.normalizeLine(notify("turn/started", { threadId: "root", turn: {} }))).toEqual([]);
+ n.normalizeLine(notify("turn/started", { threadId: "root", turn: { id: "turn" } }));
+ expect(n.normalizeLine(notify("item/reasoning/textDelta", { threadId: "root", turnId: "turn", delta: "why-now" }))).toEqual([
+ { kind: "thinking", text: "why-now" },
+ ]);
+ expect(n.normalizeLine(notify("item/reasoning/summaryTextDelta", { threadId: "root", turnId: "turn", delta: "why" }))).toEqual([
+ { kind: "thinking", text: "why" },
+ ]);
+ expect(n.normalizeLine(notify("item/agentMessage/delta", { threadId: "root", turnId: "turn", delta: "answer" }))).toEqual([
+ { kind: "text", text: "answer" },
+ ]);
+ expect(n.normalizeLine(notify("warning", { threadId: "root", message: "careful" }))).toEqual([
+ { kind: "runtime_diagnostic", severity: "warning", source: "warning", message: "careful" },
+ ]);
+ expect(n.normalizeLine(notify("configWarning", { threadId: "root", message: "config" }))).toEqual([
+ { kind: "runtime_diagnostic", severity: "warning", source: "configWarning", message: "config" },
+ ]);
+ expect(n.normalizeLine(notify("error", { threadId: "root", message: "failed" }))).toEqual([
+ { kind: "error", message: "failed" },
+ ]);
+ expect(n.normalizeLine(notify("unknown", { threadId: "root" }))).toEqual([]);
+ expect(n.normalizeLine(notify("item/started", { threadId: "root", turnId: "turn", item: { type: "contextCompaction" } }))).toEqual([{ kind: "compaction_started" }]);
+ expect(n.normalizeLine(notify("item/started", { threadId: "root", turnId: "turn", item: { type: "enteredReviewMode" } }))).toEqual([{ kind: "review_started" }]);
+ expect(n.normalizeLine(notify("item/started", { threadId: "root", turnId: "turn", item: { type: "unknown" } }))).toEqual([]);
+ expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "contextCompaction" } }))).toEqual([{ kind: "compaction_finished" }]);
+ expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "exitedReviewMode" } }))).toEqual([{ kind: "review_finished" }]);
+ expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "agentMessage", text: "final" } }))).toEqual([{ kind: "text", text: "final" }]);
+ expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "reasoning", text: "thought" } }))).toEqual([{ kind: "thinking", text: "thought" }]);
+ expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "unknown" } }))).toEqual([]);
+ expect(n.normalizeLine(notify("thread/tokenUsage/updated", { threadId: "root", tokenUsage: {} }))).toHaveLength(1);
+ expect(n.normalizeLine(notify("account/rateLimits/updated", { threadId: "root", rateLimits: {} }))).toHaveLength(1);
+ expect(n.normalizeLine(notify("turn/completed", { threadId: "root", turn: { id: "turn", status: "interrupted" } }))).toEqual([
+ { kind: "error", message: "Codex turn interrupted" },
+ { kind: "turn_end", sessionId: "root", turnOwner: "codex:root:turn" },
+ ]);
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
new file mode 100644
index 000000000..ef96b1907
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
@@ -0,0 +1,276 @@
+import type { AdapterEvent } from "../../internal/adapter.js";
+import { mapCodexTelemetry } from "./telemetry.js";
+import { tryParseJsonLine } from "../../internal/utils.js";
+
+function normalizeFileChangeInput(item: any): { path?: string } {
+ const paths: string[] = [];
+ const seen = new Set<string>();
+ const changePaths = Array.isArray(item?.changes)
+ ? item.changes.map((change: any) => change?.path)
+ : [];
+ for (const candidate of changePaths) {
+ if (typeof candidate !== "string") continue;
+ const path = candidate.trim();
+ if (!path || seen.has(path)) continue;
+ seen.add(path);
+ paths.push(path);
+ }
+ if (paths.length === 0 && typeof item?.path === "string") {
+ const path = item.path.trim();
+ if (path) paths.push(path);
+ }
+ return paths.length > 0 ? { path: paths.join(", ") } : {};
+}
+
+export class CodexEventNormalizer {
+ private threadId: string | null = null;
+ private turnId: string | null = null;
+ /**
+ * A completed root vendor turn remains an ownership fence until Codex starts
+ * another root turn. Codex can rarely report proven work after its first
+ * terminal notification. In that consistency-recovery case the matching
+ * work reopens this tombstone and one matching terminal may close it again.
+ * Keeping this separate from `turnId` is intentional: there is no live turn
+ * to steer after the first completion.
+ */
+ private terminalTurn: {
+ threadId: string;
+ turnId: string;
+ state: "closed" | "reopened_after_terminal";
+ } | null = null;
+ private sessionInitEmittedFor: string | null = null;
+
+ get currentSessionId(): string | null {
+ return this.threadId;
+ }
+
+ get currentTurnId(): string | null {
+ return this.turnId;
+ }
+
+ adoptThreadId(threadId: string | null): void {
+ if (threadId !== this.threadId) {
+ this.turnId = null;
+ this.terminalTurn = null;
+ }
+ this.threadId = threadId;
+ }
+
+ private adoptAndInit(threadId: string): AdapterEvent[] {
+ if (this.threadId !== null && threadId !== this.threadId) return [];
+ const firstSight = threadId !== this.sessionInitEmittedFor;
+ this.threadId = threadId;
+ if (!firstSight) return [];
+ this.sessionInitEmittedFor = threadId;
+ return [{ kind: "session_init", sessionId: threadId }];
+ }
+
+ normalizeLine(line: string): AdapterEvent[] {
+ const msg = tryParseJsonLine(line) as any;
+ if (!msg) return [];
+
+ if (msg?.error && msg.id !== undefined) {
+ return [{ kind: "error", message: msg.error?.message ?? "Codex RPC error" }];
+ }
+
+ if (msg?.result?.thread?.id) {
+ return this.adoptAndInit(msg.result.thread.id);
+ }
+
+ if (msg?.method) return this.handleNotification(msg.method, msg.params ?? {});
+ return [];
+ }
+
+ private handleNotification(method: string, params: any): AdapterEvent[] {
+ const notificationThreadId = typeof params?.threadId === "string" ? params.threadId : null;
+ if (
+ this.threadId !== null &&
+ notificationThreadId !== null &&
+ notificationThreadId !== this.threadId
+ ) return [];
+ if (this.isRootWorkNotification(method) && !this.acceptRootWork(params)) return [];
+
+ switch (method) {
+ case "thread/started":
+ return params?.thread?.id ? this.adoptAndInit(params.thread.id) : [];
+
+ case "turn/started":
+ if (
+ typeof params?.threadId !== "string" ||
+ params.threadId !== this.threadId ||
+ typeof params?.turn?.id !== "string"
+ ) return [];
+ this.turnId = params.turn.id;
+ this.terminalTurn = null;
+ return [
+ { kind: "turn_owner", receipt: this.turnReceipt(params.threadId, params.turn.id) },
+ { kind: "thinking", text: "" },
+ ];
+
+ case "item/reasoning/textDelta":
+ case "item/reasoning/summaryTextDelta":
+ return [{ kind: "thinking", text: params?.delta ?? "" }];
+
+ case "item/agentMessage/delta":
+ return [{ kind: "text", text: params?.delta ?? "" }];
+
+ case "item/started":
+ return this.handleItemStarted(params);
+
+ case "item/completed":
+ return this.handleItemCompleted(params);
+
+ case "rawResponseItem/completed":
+ return [{ kind: "internal_progress", source: "codex_raw_item", itemType: "rawResponseItem" }];
+
+ case "configWarning":
+ case "warning":
+ case "guardianWarning":
+ case "deprecationNotice":
+ return [
+ { kind: "runtime_diagnostic", severity: "warning", source: method, message: params?.message ?? method },
+ ];
+
+ case "turn/completed":
+ if (!this.acceptRootTerminal(params)) return [];
+ if (params.turn.status === "failed") {
+ return [
+ { kind: "error", message: "Codex turn failed" },
+ { kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) },
+ ];
+ }
+ if (params.turn.status === "interrupted") {
+ return [{ kind: "error", message: "Codex turn interrupted" }, { kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) }];
+ }
+ return [{ kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) }];
+
+ case "error":
+ return [{ kind: "error", message: params?.message ?? "Codex error" }];
+
+ case "thread/tokenUsage/updated":
+ case "account/rateLimits/updated":
+ return mapCodexTelemetry(method, params);
+
+ default:
+ return [];
+ }
+ }
+
+ private isRootWorkNotification(method: string): boolean {
+ return method === "item/reasoning/textDelta"
+ || method === "item/reasoning/summaryTextDelta"
+ || method === "item/agentMessage/delta"
+ || method === "item/started"
+ || method === "item/completed"
+ || method === "rawResponseItem/completed";
+ }
+
+ private notificationTurnId(params: any): string | null {
+ if (typeof params?.turnId === "string") return params.turnId;
+ return typeof params?.turn?.id === "string" ? params.turn.id : null;
+ }
+
+ private turnReceipt(threadId: string, turnId: string): string {
+ return `codex:${threadId}:${turnId}`;
+ }
+
+ private acceptRootWork(params: any): boolean {
+ const notificationThreadId = typeof params?.threadId === "string" ? params.threadId : null;
+ const notificationTurnId = this.notificationTurnId(params);
+ if (this.turnId !== null) {
+ return (notificationThreadId === null || notificationThreadId === this.threadId)
+ && (notificationTurnId === null || notificationTurnId === this.turnId);
+ }
+ if (this.terminalTurn) {
+ if (
+ notificationThreadId !== this.terminalTurn.threadId
+ || notificationTurnId !== this.terminalTurn.turnId
+ ) return false;
+ this.terminalTurn.state = "reopened_after_terminal";
+ return true;
+ }
+ // Parser-only callers may normalize isolated fixture lines before a root
+ // thread is adopted. Once ownership exists, work without a live or closed
+ // root turn is not attributable and must not cross the adapter boundary.
+ return this.threadId === null;
+ }
+
+ private acceptRootTerminal(params: any): boolean {
+ const notificationThreadId = typeof params?.threadId === "string" ? params.threadId : null;
+ const notificationTurnId = this.notificationTurnId(params);
+ if (
+ notificationThreadId === null
+ || notificationThreadId !== this.threadId
+ || notificationTurnId === null
+ ) return false;
+ if (notificationTurnId === this.turnId) {
+ this.turnId = null;
+ this.terminalTurn = {
+ threadId: notificationThreadId,
+ turnId: notificationTurnId,
+ state: "closed",
+ };
+ return true;
+ }
+ const terminalTurn = this.terminalTurn;
+ if (
+ this.turnId === null
+ && terminalTurn !== null
+ && terminalTurn.threadId === notificationThreadId
+ && terminalTurn.turnId === notificationTurnId
+ && terminalTurn.state === "reopened_after_terminal"
+ ) {
+ terminalTurn.state = "closed";
+ return true;
+ }
+ return false;
+ }
+
+ private handleItemStarted(params: any): AdapterEvent[] {
+ const t = params?.item?.type ?? params?.type;
+ switch (t) {
+ case "commandExecution":
+ return [{ kind: "tool_call", name: "shell", input: params?.item }];
+ case "contextCompaction":
+ return [{ kind: "compaction_started" }];
+ case "enteredReviewMode":
+ return [{ kind: "review_started" }];
+ case "fileChange":
+ return [{ kind: "tool_call", name: "file_change", input: normalizeFileChangeInput(params?.item) }];
+ case "mcpToolCall":
+ return [{ kind: "tool_call", name: `mcp_${params?.item?.name ?? "tool"}`, input: params?.item }];
+ case "webSearch":
+ return [{ kind: "tool_call", name: "web_search", input: params?.item }];
+ case "collabAgentToolCall":
+ return [{ kind: "tool_call", name: "collab_tool_call", input: params?.item }];
+ default:
+ return [];
+ }
+ }
+
+ private handleItemCompleted(params: any): AdapterEvent[] {
+ const t = params?.item?.type ?? params?.type;
+ switch (t) {
+ case "commandExecution":
+ return [{ kind: "tool_output", name: "shell" }];
+ case "contextCompaction":
+ return [{ kind: "compaction_finished" }];
+ case "exitedReviewMode":
+ return [{ kind: "review_finished" }];
+ case "fileChange":
+ return [{ kind: "tool_output", name: "file_change" }];
+ case "mcpToolCall":
+ return [{ kind: "tool_output", name: `mcp_${params?.item?.name ?? "tool"}` }];
+ case "webSearch":
+ return [{ kind: "tool_output", name: "web_search" }];
+ case "collabAgentToolCall":
+ return [{ kind: "tool_output", name: "collab_tool_call" }];
+ case "agentMessage":
+ return [{ kind: "text", text: params?.item?.text ?? "" }];
+ case "reasoning":
+ return [{ kind: "thinking", text: params?.item?.text ?? "" }];
+ default:
+ return [];
+ }
+ }
+}
diff --git a/src/daemon/src/drivers/codexTelemetrySidecar.ts b/src/daemon/agent-driver/src/adapters/codex/telemetry.ts
similarity index 90%
rename from src/daemon/src/drivers/codexTelemetrySidecar.ts
rename to src/daemon/agent-driver/src/adapters/codex/telemetry.ts
index 808bef6c9..b53bb9506 100644
--- a/src/daemon/src/drivers/codexTelemetrySidecar.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/telemetry.ts
@@ -1,11 +1,11 @@
/**
* Codex telemetry sidecar — maps Codex's two telemetry notifications into
- * `telemetry` ParsedEvents. Kept separate from the main event flow because it
+ * `telemetry` adapter events. Kept separate from the main event flow because it
* is purely observability (token accounting + rate limits), not turn content.
*/
-import type { ParsedEvent } from "../types.js";
+import type { AdapterEvent } from "../../internal/adapter.js";
-export function mapCodexTelemetry(method: string, params: any): ParsedEvent[] {
+export function mapCodexTelemetry(method: string, params: any): AdapterEvent[] {
if (method === "thread/tokenUsage/updated") {
const u = params?.usage ?? params ?? {};
return [
diff --git a/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
new file mode 100644
index 000000000..18ac71915
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
@@ -0,0 +1,706 @@
+import { EventEmitter } from "node:events";
+import type {
+ AdapterEvent,
+ AdapterLaunchContext,
+ LaneAdmission,
+ LaneInterruptInput,
+ LaneSendInput,
+ LaneStartInput,
+ LaneStopInput,
+ RuntimeLane,
+ RuntimeLaneEventMap,
+ SpawnedProcess,
+ SpawnedProcessHandle,
+} from "../../internal/adapter.js";
+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
+import { killProcessTree, SESSION_STOP_GRACE_MS } from "../../internal/killTree.js";
+
+const ACP_PROTOCOL_VERSION = 1;
+const HANDSHAKE_TIMEOUT_MS = 15_000;
+const AUTH_METHOD_ID = "cursor_login";
+const PROMPT_STOP_REASONS = new Set([
+ "end_turn",
+ "max_tokens",
+ "max_turn_requests",
+ "refusal",
+ "cancelled",
+]);
+
+type JsonRpcId = number | string;
+type JsonRecord = Record<string, unknown>;
+
+interface PendingCall {
+ readonly kind: "call";
+ readonly method: string;
+ readonly resolve: (result: unknown) => void;
+ readonly reject: (error: Error) => void;
+ readonly timer?: ReturnType<typeof setTimeout>;
+}
+
+interface PendingPrompt {
+ readonly kind: "prompt";
+ readonly method: "session/prompt";
+ readonly active: ActivePrompt;
+}
+
+type PendingRequest = PendingCall | PendingPrompt;
+
+interface RpcRequest {
+ readonly id: number;
+ readonly promise: Promise<unknown>;
+}
+
+interface ActivePrompt {
+ readonly requestId: number;
+ readonly receipt: string;
+}
+
+export interface CursorAcpProcessFactory {
+ spawn(ctx: AdapterLaunchContext): Promise<SpawnedProcess>;
+}
+
+interface CursorAcpLaneOptions {
+ readonly onRawStdoutLine?: (line: string) => void;
+ readonly handshakeTimeoutMs?: number;
+}
+
+class CursorAcpResetRequiredError extends Error {}
+class CursorAcpIncompatibleError extends Error {}
+
+class CursorAcpRpcError extends Error {
+ constructor(
+ readonly method: string,
+ readonly code: number | undefined,
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+function record(value: unknown): JsonRecord | null {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? value as JsonRecord
+ : null;
+}
+
+function safeLabel(value: unknown): string {
+ return typeof value === "string" && /^[a-z0-9_-]{1,64}$/i.test(value) ? value : "unknown";
+}
+
+function rpcErrorMessage(error: unknown): string {
+ const payload = record(error);
+ const message = typeof payload?.message === "string" && payload.message.trim()
+ ? payload.message
+ : "Cursor ACP request failed";
+ const data = record(payload?.data);
+ const detail = typeof data?.message === "string" && data.message.trim() ? data.message : undefined;
+ return detail ? `${message}: ${detail}` : message;
+}
+
+function isMissingSessionError(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String(error);
+ return /\bsession\b.*\b(not found|missing|unknown|invalid)\b/i.test(message)
+ || /\b(not found|missing|unknown|invalid)\b.*\bsession\b/i.test(message);
+}
+
+function flattenSelectOptions(value: unknown): Array<{ value: string; name?: string }> {
+ if (!Array.isArray(value)) return [];
+ const out: Array<{ value: string; name?: string }> = [];
+ for (const item of value) {
+ if (Array.isArray(item)) {
+ out.push(...flattenSelectOptions(item));
+ continue;
+ }
+ const candidate = record(item);
+ if (!candidate) continue;
+ if (typeof candidate.value === "string") {
+ out.push({ value: candidate.value, ...(typeof candidate.name === "string" ? { name: candidate.name } : {}) });
+ }
+ if (Array.isArray(candidate.options)) out.push(...flattenSelectOptions(candidate.options));
+ }
+ return out;
+}
+
+export class CursorAcpLane implements RuntimeLane {
+ private readonly events = new EventEmitter();
+ private readonly pending = new Map<number, PendingRequest>();
+ private readonly openToolCalls = new Set<string>();
+ private process: SpawnedProcessHandle | null = null;
+ private stdoutBuffer = "";
+ private requestSequence = 0;
+ private started = false;
+ private ready = false;
+ private sessionId: string | null = null;
+ private activePrompt: ActivePrompt | null = null;
+ private requestedStopReason?: string;
+ private spawnPromise?: Promise<SpawnedProcess>;
+ private stopPromise?: Promise<void>;
+ private suppressExit = false;
+ private processTerminal = false;
+ private processActivated = false;
+ private processStartError: Error | null = null;
+
+ constructor(
+ private readonly factory: CursorAcpProcessFactory,
+ private readonly ctx: AdapterLaunchContext,
+ private readonly options: CursorAcpLaneOptions = {},
+ ) {}
+
+ get currentSessionId(): string | null {
+ return this.sessionId;
+ }
+
+ on<K extends keyof RuntimeLaneEventMap>(
+ event: K,
+ listener: (value: RuntimeLaneEventMap[K]) => void,
+ ): void {
+ this.events.on(event, listener);
+ }
+
+ async start(input: LaneStartInput): Promise<LaneAdmission> {
+ if (this.started) {
+ return { ok: false, reason: "runtime_error", error: "Cursor ACP session already started" };
+ }
+ this.started = true;
+ const launchCtx: AdapterLaunchContext = {
+ ...this.ctx,
+ prompt: input.text,
+ config: { ...this.ctx.config, sessionId: input.sessionId ?? this.ctx.config.sessionId },
+ };
+ try {
+ this.spawnPromise = this.factory.spawn(launchCtx).then((spawned) => {
+ this.process = spawned.process;
+ this.attachProcess(spawned.process);
+ return spawned;
+ });
+ await this.spawnPromise;
+ if (this.requestedStopReason) {
+ await this.stop({ reason: this.requestedStopReason, forceAfterMs: 0 });
+ throw new Error("Cursor ACP start was cancelled");
+ }
+ await this.handshake(launchCtx);
+ if (this.requestedStopReason) {
+ await this.stop({ reason: this.requestedStopReason, forceAfterMs: 0 });
+ throw new Error("Cursor ACP start was cancelled");
+ }
+ if (this.processStartError) throw this.processStartError;
+ if (this.processTerminal || this.isClosed()) {
+ throw new Error("Cursor ACP process exited during startup");
+ }
+ const sessionId = this.sessionId;
+ if (!sessionId) throw new Error("Cursor ACP handshake completed without a session id");
+ this.processActivated = true;
+ this.ready = true;
+ this.events.emit("runtime_event", { kind: "session_init", sessionId } satisfies AdapterEvent);
+ return this.admitPrompt(input.text);
+ } catch (error) {
+ // LogicalAgentSession owns failed-start settlement. Do not let the child
+ // exit caused by this cleanup race that admission into a false crash.
+ this.suppressExit = true;
+ await this.stop({ reason: "failed_start", forceAfterMs: 0 }).catch(() => {});
+ if (error instanceof CursorAcpResetRequiredError) {
+ return { ok: false, reason: "reset_required", error: error.message };
+ }
+ if (error instanceof CursorAcpIncompatibleError) {
+ return { ok: false, reason: "incompatible_configuration", error: error.message };
+ }
+ throw error;
+ }
+ }
+
+ async send(input: LaneSendInput): Promise<LaneAdmission> {
+ if (!this.ready || !this.process || this.isClosed()) return { ok: false, reason: "closed" };
+ if (input.mode !== "idle") {
+ return { ok: false, reason: "unsupported", error: "Cursor ACP does not support mid-turn steering" };
+ }
+ if (this.activePrompt) {
+ return { ok: false, reason: "runtime_busy", error: "Cursor ACP prompt is still active" };
+ }
+ return this.admitPrompt(input.text);
+ }
+
+ async interrupt(_input: LaneInterruptInput): Promise<boolean> {
+ if (!this.ready || !this.sessionId || !this.activePrompt || this.isClosed()) return false;
+ this.write({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: this.sessionId } });
+ return true;
+ }
+
+ stop(input: LaneStopInput = {}): Promise<void> {
+ this.requestedStopReason ??= input.reason ?? "requested_stop";
+ this.ready = false;
+ this.activePrompt = null;
+ this.openToolCalls.clear();
+ this.rejectAllPending(new Error("Cursor ACP lane stopped"));
+ this.stopPromise ??= this.stopPhysicalOnce(input);
+ return this.stopPromise;
+ }
+
+ private async stopPhysicalOnce(input: LaneStopInput): Promise<void> {
+ await this.spawnPromise?.catch(() => undefined);
+ const proc = this.process;
+ if (!proc) return;
+ if (proc.pid) {
+ await killProcessTree(proc.pid, { graceMs: input.forceAfterMs ?? SESSION_STOP_GRACE_MS });
+ } else if (!this.isClosed()) {
+ proc.kill(input.signal ?? "SIGTERM");
+ }
+ }
+
+ private async handshake(ctx: AdapterLaunchContext): Promise<void> {
+ const initialize = record(await this.call("initialize", {
+ protocolVersion: ACP_PROTOCOL_VERSION,
+ clientCapabilities: {
+ fs: { readTextFile: false, writeTextFile: false },
+ terminal: false,
+ },
+ clientInfo: { name: "alook-agent-driver", version: "0.1.14" },
+ }));
+ if (initialize?.protocolVersion !== ACP_PROTOCOL_VERSION) {
+ throw new CursorAcpIncompatibleError("Installed Cursor ACP does not support protocol version 1");
+ }
+ const capabilities = record(initialize.agentCapabilities);
+ if (capabilities?.loadSession !== true) {
+ throw new CursorAcpIncompatibleError("Installed Cursor ACP does not support persistent session loading");
+ }
+ const authMethods = Array.isArray(initialize.authMethods) ? initialize.authMethods : [];
+ if (!authMethods.some((method) => record(method)?.id === AUTH_METHOD_ID)) {
+ throw new CursorAcpIncompatibleError("Installed Cursor ACP does not expose Cursor login authentication");
+ }
+ await this.call("authenticate", { methodId: AUTH_METHOD_ID });
+
+ let session: JsonRecord | null;
+ if (ctx.config.sessionId) {
+ try {
+ session = record(await this.call("session/load", {
+ sessionId: ctx.config.sessionId,
+ cwd: ctx.workingDirectory,
+ mcpServers: [],
+ }));
+ } catch (error) {
+ if (isMissingSessionError(error)) {
+ throw new CursorAcpResetRequiredError(
+ "Cursor session cannot be loaded through ACP; reset this agent to start a new ACP session",
+ );
+ }
+ throw error;
+ }
+ } else {
+ session = record(await this.call("session/new", { cwd: ctx.workingDirectory, mcpServers: [] }));
+ }
+ if (!session || typeof session.sessionId !== "string" || !session.sessionId.trim()) {
+ throw new Error("Cursor ACP did not return a valid session id");
+ }
+ if (ctx.config.sessionId && session.sessionId !== ctx.config.sessionId) {
+ throw new CursorAcpResetRequiredError(
+ "Cursor ACP loaded a different session; reset this agent before continuing",
+ );
+ }
+ this.sessionId = session.sessionId;
+ await this.configureModel(session, ctx);
+ }
+
+ private async configureModel(session: JsonRecord, ctx: AdapterLaunchContext): Promise<void> {
+ const requestedModel = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).model;
+ if (!requestedModel) return;
+ const configOptions = Array.isArray(session.configOptions) ? session.configOptions : [];
+ const modelConfig = configOptions.map(record).find((option) => option?.id === "model") ?? null;
+ if (!modelConfig) {
+ throw new CursorAcpIncompatibleError("Installed Cursor ACP does not support model configuration");
+ }
+ const options = flattenSelectOptions(modelConfig.options);
+ const match = options.find((option) => option.value === requestedModel)
+ ?? options.find((option) => option.name === requestedModel);
+ if (!match) {
+ throw new CursorAcpIncompatibleError(`Configured Cursor model is unavailable through ACP: ${requestedModel}`);
+ }
+ try {
+ await this.call("session/set_config_option", {
+ sessionId: this.sessionId,
+ configId: "model",
+ value: match.value,
+ });
+ } catch {
+ throw new CursorAcpIncompatibleError("Installed Cursor ACP rejected model configuration");
+ }
+ }
+
+ private admitPrompt(text: string): LaneAdmission {
+ if (!this.sessionId) return { ok: false, reason: "not_ready", error: "Cursor ACP session is not ready" };
+ if (this.activePrompt) return { ok: false, reason: "runtime_busy", error: "Cursor ACP prompt is still active" };
+ const requestId = ++this.requestSequence;
+ const active: ActivePrompt = {
+ requestId,
+ receipt: `cursor:acp:${requestId}`,
+ };
+ this.openToolCalls.clear();
+ this.activePrompt = active;
+ this.pending.set(requestId, { kind: "prompt", method: "session/prompt", active });
+ try {
+ this.write({
+ jsonrpc: "2.0",
+ id: requestId,
+ method: "session/prompt",
+ params: {
+ sessionId: this.sessionId,
+ prompt: [{ type: "text", text }],
+ },
+ });
+ } catch (error) {
+ this.pending.delete(requestId);
+ if (this.activePrompt?.requestId === requestId) this.activePrompt = null;
+ throw error;
+ }
+ return { ok: true, acceptedAs: "prompt", receipt: active.receipt };
+ }
+
+ private completePrompt(active: ActivePrompt, value: unknown): void {
+ if (this.activePrompt?.requestId !== active.requestId) return;
+ const result = record(value);
+ if (!result || typeof result.stopReason !== "string" || !PROMPT_STOP_REASONS.has(result.stopReason)) {
+ this.failPrompt(active, new Error("Cursor ACP prompt response did not contain a supported stopReason"));
+ return;
+ }
+ this.activePrompt = null;
+ this.openToolCalls.clear();
+ const usage = record(result.usage);
+ if (usage) {
+ this.events.emit("runtime_event", {
+ kind: "telemetry",
+ name: "token_usage",
+ source: "cursor.acp",
+ attrs: usage,
+ } satisfies AdapterEvent);
+ }
+ this.events.emit("runtime_event", {
+ kind: "turn_end",
+ sessionId: this.sessionId ?? undefined,
+ turnOwner: active.receipt,
+ } satisfies AdapterEvent);
+ }
+
+ private failPrompt(active: ActivePrompt, error: unknown): void {
+ if (this.activePrompt?.requestId !== active.requestId) return;
+ this.activePrompt = null;
+ this.openToolCalls.clear();
+ this.events.emit("runtime_event", {
+ kind: "error",
+ message: error instanceof Error ? error.message : String(error),
+ } satisfies AdapterEvent);
+ this.events.emit("runtime_event", {
+ kind: "turn_end",
+ sessionId: this.sessionId ?? undefined,
+ turnOwner: active.receipt,
+ } satisfies AdapterEvent);
+ }
+
+ private call(method: string, params: JsonRecord): Promise<unknown> {
+ return this.request(method, params, this.options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS).promise;
+ }
+
+ private request(method: string, params: JsonRecord, timeoutMs?: number): RpcRequest {
+ const id = ++this.requestSequence;
+ let resolve!: (result: unknown) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<unknown>((accept, decline) => {
+ resolve = accept;
+ reject = decline;
+ });
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
+ const pending = this.pending.get(id);
+ if (!pending || pending.kind !== "call") return;
+ this.pending.delete(id);
+ pending.reject(new Error(`Cursor ACP ${method} timed out`));
+ }, timeoutMs);
+ timer?.unref?.();
+ this.pending.set(id, { kind: "call", method, resolve, reject, ...(timer ? { timer } : {}) });
+ try {
+ this.write({ jsonrpc: "2.0", id, method, params });
+ } catch (error) {
+ const pending = this.pending.get(id);
+ this.pending.delete(id);
+ if (pending?.kind === "call" && pending.timer) clearTimeout(pending.timer);
+ throw error instanceof Error ? error : new Error(String(error));
+ }
+ return { id, promise };
+ }
+
+ private write(message: JsonRecord): void {
+ const stdin = this.process?.stdin;
+ if (!stdin || stdin.destroyed || stdin.writableEnded || stdin.writable === false) {
+ throw new Error("Cursor ACP stdin is not writable");
+ }
+ stdin.write(`${JSON.stringify(message)}\n`);
+ }
+
+ private attachProcess(proc: SpawnedProcessHandle): void {
+ proc.stdout?.on("data", (chunk) => {
+ this.stdoutBuffer += chunk.toString();
+ const lines = this.stdoutBuffer.split("\n");
+ this.stdoutBuffer = lines.pop() ?? "";
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ try {
+ this.options.onRawStdoutLine?.(line);
+ } catch {
+ // Observability must not affect protocol handling.
+ }
+ let message: unknown;
+ try {
+ message = JSON.parse(line);
+ } catch {
+ this.protocolFailure("Cursor ACP emitted malformed JSON");
+ continue;
+ }
+ try {
+ this.handleMessage(message);
+ } catch {
+ this.protocolFailure("Cursor ACP could not answer a client-side protocol request");
+ }
+ }
+ });
+ proc.stderr?.on("data", (chunk) => {
+ const text = chunk.toString().trim();
+ if (text) this.events.emit("stderr", text);
+ });
+ proc.on("error", (error) => {
+ if (this.process !== proc || this.processTerminal) return;
+ const normalized = error instanceof Error ? error : new Error(String(error));
+ this.rejectAllPending(normalized);
+ if (!this.processActivated || this.requestedStopReason) {
+ if (!this.processActivated) this.processStartError ??= normalized;
+ this.events.emit("error", normalized);
+ return;
+ }
+ this.processTerminal = true;
+ this.ready = false;
+ this.activePrompt = null;
+ this.openToolCalls.clear();
+ this.stopPromise ??= this.stopPhysicalOnce({ reason: "runtime_error", forceAfterMs: 0 });
+ void this.stopPromise.catch(() => {});
+ this.events.emit("error", normalized);
+ if (this.suppressExit) return;
+ this.events.emit("exit", {
+ code: null,
+ signal: null,
+ reason: "runtime_exit",
+ });
+ });
+ proc.on("exit", (code, signal) => {
+ if (this.processTerminal || this.process !== proc) return;
+ this.processTerminal = true;
+ this.ready = false;
+ this.activePrompt = null;
+ this.openToolCalls.clear();
+ this.rejectAllPending(new Error("Cursor ACP process exited"));
+ if (this.suppressExit || !this.processActivated) return;
+ this.events.emit("exit", {
+ code,
+ signal,
+ reason: this.requestedStopReason ? "requested" : "runtime_exit",
+ });
+ });
+ }
+
+ private handleMessage(value: unknown): void {
+ const message = record(value);
+ if (!message || message.jsonrpc !== "2.0") {
+ this.protocolFailure("Cursor ACP emitted an invalid JSON-RPC message");
+ return;
+ }
+ if ((typeof message.id === "number" || typeof message.id === "string") && typeof message.method !== "string") {
+ this.handleResponse(message.id, message);
+ return;
+ }
+ if (typeof message.method === "string") {
+ if (message.id !== undefined) {
+ this.handleRequest(message.id as JsonRpcId, message.method, message.params);
+ } else {
+ this.handleNotification(message.method, message.params);
+ }
+ return;
+ }
+ this.protocolFailure("Cursor ACP emitted an unrecognized JSON-RPC message");
+ }
+
+ private handleResponse(id: JsonRpcId, message: JsonRecord): void {
+ const pending = typeof id === "number" ? this.pending.get(id) : undefined;
+ if (typeof id !== "number" || !pending) {
+ this.diagnostic("warning", "Cursor ACP emitted a duplicate or unknown response id");
+ return;
+ }
+ if (pending.kind === "prompt") {
+ this.pending.delete(id);
+ if (message.error !== undefined) {
+ const payload = record(message.error);
+ this.failPrompt(pending.active, new CursorAcpRpcError(
+ pending.method,
+ typeof payload?.code === "number" ? payload.code : undefined,
+ rpcErrorMessage(message.error),
+ ));
+ } else if (!("result" in message)) {
+ this.failPrompt(pending.active, new Error("Cursor ACP response omitted result"));
+ } else {
+ this.completePrompt(pending.active, message.result);
+ }
+ return;
+ }
+ if (message.error !== undefined) {
+ const payload = record(message.error);
+ this.settleRequest(id, false, new CursorAcpRpcError(
+ pending.method,
+ typeof payload?.code === "number" ? payload.code : undefined,
+ rpcErrorMessage(message.error),
+ ));
+ return;
+ }
+ if (!("result" in message)) {
+ this.settleRequest(id, false, new Error("Cursor ACP response omitted result"));
+ return;
+ }
+ this.settleRequest(id, true, message.result);
+ }
+
+ private settleRequest(id: number, ok: boolean, value: unknown): void {
+ const pending = this.pending.get(id);
+ if (!pending || pending.kind !== "call") return;
+ this.pending.delete(id);
+ if (pending.timer) clearTimeout(pending.timer);
+ if (ok) pending.resolve(value);
+ else pending.reject(value instanceof Error ? value : new Error(String(value)));
+ }
+
+ private handleRequest(id: JsonRpcId, method: string, params: unknown): void {
+ if (method !== "session/request_permission") {
+ this.write({
+ jsonrpc: "2.0",
+ id,
+ error: { code: -32601, message: "Unsupported Cursor ACP client request" },
+ });
+ this.diagnostic("warning", `Unsupported Cursor ACP client request: ${safeLabel(method)}`);
+ return;
+ }
+ const payload = record(params);
+ const sameSession = payload?.sessionId === this.sessionId;
+ const options = Array.isArray(payload?.options) ? payload.options.map(record).filter(Boolean) as JsonRecord[] : [];
+ const allowOnce = options.find((option) => (
+ option.kind === "allow_once"
+ && typeof option.optionId === "string"
+ && option.optionId.trim().length > 0
+ ));
+ if (!this.ready || !this.activePrompt || !sameSession || !allowOnce) {
+ this.write({ jsonrpc: "2.0", id, result: { outcome: { outcome: "cancelled" } } });
+ this.diagnostic("error", "Cursor ACP permission request was not allowed for the active prompt");
+ return;
+ }
+ this.write({
+ jsonrpc: "2.0",
+ id,
+ result: { outcome: { outcome: "selected", optionId: allowOnce.optionId } },
+ });
+ }
+
+ private handleNotification(method: string, params: unknown): void {
+ if (method === "session/update") {
+ this.handleSessionUpdate(params);
+ return;
+ }
+ this.diagnostic("warning", `Unsupported Cursor ACP notification: ${safeLabel(method)}`);
+ }
+
+ private handleSessionUpdate(params: unknown): void {
+ const payload = record(params);
+ if (!payload || payload.sessionId !== this.sessionId) {
+ this.diagnostic("warning", "Cursor ACP emitted an update for a different session");
+ return;
+ }
+ if (!this.ready || !this.activePrompt) {
+ this.diagnostic("warning", "Cursor ACP emitted a session update without an active prompt");
+ return;
+ }
+ const update = record(payload.update) ?? {};
+ const updateType = update?.sessionUpdate;
+ switch (updateType) {
+ case "agent_message_chunk": {
+ const content = record(update.content);
+ if (content?.type === "text" && typeof content.text === "string") {
+ this.events.emit("runtime_event", { kind: "text", text: content.text } satisfies AdapterEvent);
+ }
+ return;
+ }
+ case "agent_thought_chunk": {
+ const content = record(update.content);
+ if (content?.type === "text" && typeof content.text === "string") {
+ this.events.emit("runtime_event", { kind: "thinking", text: content.text } satisfies AdapterEvent);
+ }
+ return;
+ }
+ case "user_message_chunk":
+ return;
+ case "tool_call": {
+ if (typeof update.toolCallId !== "string" || typeof update.title !== "string") {
+ this.diagnostic("warning", "Cursor ACP emitted a malformed tool_call update");
+ return;
+ }
+ this.openToolCalls.add(update.toolCallId);
+ this.events.emit("runtime_event", {
+ kind: "tool_call",
+ name: update.title,
+ input: update.rawInput,
+ } satisfies AdapterEvent);
+ return;
+ }
+ case "tool_call_update": {
+ if (
+ typeof update.toolCallId === "string"
+ && (update.status === "completed" || update.status === "failed")
+ && this.openToolCalls.delete(update.toolCallId)
+ ) {
+ this.events.emit("runtime_event", {
+ kind: "tool_output",
+ name: typeof update.title === "string" ? update.title : "Cursor tool",
+ } satisfies AdapterEvent);
+ }
+ return;
+ }
+ case "plan":
+ this.events.emit("runtime_event", {
+ kind: "internal_progress",
+ source: "cursor.acp",
+ itemType: "plan",
+ } satisfies AdapterEvent);
+ return;
+ default:
+ this.diagnostic("warning", `Unsupported Cursor ACP session update: ${safeLabel(updateType)}`);
+ }
+ }
+
+ private diagnostic(severity: "error" | "warning", message: string): void {
+ this.events.emit("runtime_event", {
+ kind: "runtime_diagnostic",
+ severity,
+ source: "cursor.acp",
+ message,
+ } satisfies AdapterEvent);
+ }
+
+ private protocolFailure(message: string): void {
+ const error = new Error(message);
+ this.rejectAllPending(error);
+ this.events.emit("error", error);
+ void this.stop({ reason: "protocol_error", forceAfterMs: 0 }).catch(() => {});
+ }
+
+ private rejectAllPending(error: Error): void {
+ for (const [id, pending] of [...this.pending]) {
+ this.pending.delete(id);
+ if (pending.kind === "call") {
+ if (pending.timer) clearTimeout(pending.timer);
+ pending.reject(error);
+ }
+ }
+ }
+
+ private isClosed(): boolean {
+ return this.process ? this.process.exitCode !== null || this.process.signalCode !== null : false;
+ }
+}
diff --git a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
new file mode 100644
index 000000000..f559072a2
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
@@ -0,0 +1,1209 @@
+import { EventEmitter } from "node:events";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { PassThrough } from "node:stream";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { AdapterEvent, AdapterLaunchContext, RuntimeLane, SpawnedProcessHandle } from "../../internal/adapter.js";
+import { createAgentDriverSdk } from "../../sdk.js";
+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
+import { createFakeAgentDriverHost } from "../../testing/fake-host.js";
+import { CursorAcpLane } from "./acp-lane.js";
+import { CursorDriver } from "./index.js";
+
+type RpcMessage = Record<string, unknown>;
+type FakeProcess = SpawnedProcessHandle & {
+ stdout: PassThrough;
+ stderr: PassThrough;
+ stdin: PassThrough;
+ emit(event: string, ...args: unknown[]): boolean;
+ finish(code?: number | null, signal?: NodeJS.Signals | null): void;
+};
+
+let lastSpawn: { command: string; args: string[]; opts: unknown } | null = null;
+let spawned: FakeProcess[] = [];
+let onClientMessage: (process: FakeProcess, message: RpcMessage) => void = () => {};
+let killEmitsExit = false;
+const killProcessTree = vi.hoisted(() => vi.fn());
+
+function fakeProcess(): FakeProcess {
+ const process = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ stdin: new PassThrough(),
+ pid: undefined,
+ exitCode: null as number | null,
+ signalCode: null as NodeJS.Signals | null,
+ kill: vi.fn((signal: NodeJS.Signals = "SIGTERM") => {
+ if (killEmitsExit) {
+ process.signalCode = signal;
+ process.emit("exit", null, signal);
+ }
+ return true;
+ }),
+ finish(code: number | null = 0, signal: NodeJS.Signals | null = null) {
+ process.exitCode = code;
+ process.signalCode = signal;
+ process.emit("exit", code, signal);
+ },
+ });
+ let buffer = "";
+ process.stdin.on("data", (chunk) => {
+ buffer += chunk.toString();
+ const lines = buffer.split("\n");
+ buffer = lines.pop() ?? "";
+ for (const line of lines) if (line.trim()) onClientMessage(process as FakeProcess, JSON.parse(line));
+ });
+ return process as unknown as FakeProcess;
+}
+
+vi.mock("../../internal/killTree.js", async () => {
+ const actual = await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js");
+ return {
+ ...actual,
+ killProcessTree,
+ spawnAgentProcess: (command: string, args: string[], opts: unknown) => {
+ lastSpawn = { command, args, opts };
+ const process = fakeProcess();
+ spawned.push(process);
+ return process as never;
+ },
+ };
+});
+
+const temporaryDirectories: string[] = [];
+
+function baseCtx(overrides: Partial<AdapterLaunchContext> = {}): AdapterLaunchContext {
+ const workingDirectory = mkdtempSync(join(tmpdir(), "cursor-acp-test-"));
+ temporaryDirectories.push(workingDirectory);
+ return fakeLaunchContext("cursor", workingDirectory, {
+ standingPrompt: "You are Cursor.",
+ prompt: "say hi",
+ config: { runtimeConfig: { model: { kind: "default" } } },
+ ...overrides,
+ });
+}
+
+function respond(process: FakeProcess, request: RpcMessage, result: unknown): void {
+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: request.id, result })}\n`);
+}
+
+function fail(process: FakeProcess, request: RpcMessage, message: string, data?: unknown): void {
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: request.id,
+ error: { code: -32000, message, ...(data === undefined ? {} : { data }) },
+ })}\n`);
+}
+
+interface FakeServer {
+ readonly messages: RpcMessage[];
+ readonly prompts: RpcMessage[];
+}
+
+function installServer(options: {
+ sessionId?: string;
+ loadError?: string;
+ modelOptions?: Array<{ value: string; name: string }>;
+} = {}): FakeServer {
+ const messages: RpcMessage[] = [];
+ const prompts: RpcMessage[] = [];
+ const sessionId = options.sessionId ?? "cursor-acp-session";
+ onClientMessage = (process, message) => {
+ messages.push(message);
+ switch (message.method) {
+ case "initialize":
+ respond(process, message, {
+ protocolVersion: 1,
+ agentCapabilities: { loadSession: true },
+ authMethods: [{ id: "cursor_login", name: "Cursor Login" }],
+ });
+ break;
+ case "authenticate":
+ respond(process, message, {});
+ break;
+ case "session/new":
+ respond(process, message, {
+ sessionId,
+ configOptions: options.modelOptions ? [{ id: "model", options: options.modelOptions }] : [],
+ });
+ break;
+ case "session/load":
+ if (options.loadError) fail(process, message, "Invalid params", { message: options.loadError });
+ else respond(process, message, {
+ sessionId,
+ configOptions: options.modelOptions ? [{ id: "model", options: options.modelOptions }] : [],
+ });
+ break;
+ case "session/set_config_option":
+ respond(process, message, { configOptions: [] });
+ break;
+ case "session/prompt":
+ prompts.push(message);
+ break;
+ }
+ };
+ return { messages, prompts };
+}
+
+function eventsFrom(lane: RuntimeLane): AdapterEvent[] {
+ const events: AdapterEvent[] = [];
+ lane.on("runtime_event", (event) => events.push(event));
+ lane.on("error", () => {});
+ return events;
+}
+
+function completePrompt(process: FakeProcess, prompt: RpcMessage, stopReason = "end_turn"): void {
+ respond(process, prompt, { stopReason });
+}
+
+async function settle(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((accept, decline) => {
+ resolve = accept;
+ reject = decline;
+ });
+ return { promise, resolve, reject };
+}
+
+beforeEach(() => {
+ lastSpawn = null;
+ spawned = [];
+ onClientMessage = () => {};
+ killEmitsExit = false;
+ killProcessTree.mockReset();
+ killProcessTree.mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const directory of temporaryDirectories.splice(0)) rmSync(directory, { recursive: true, force: true });
+});
+
+describe("CursorDriver persistent ACP transport", () => {
+ it("spawns cursor-agent acp once with piped stdin and performs the strict handshake before prompt", async () => {
+ const server = installServer();
+ const driver = new CursorDriver();
+ const lane = await driver.openLane(baseCtx());
+ const events = eventsFrom(lane);
+
+ await expect(lane.start({ text: "say hi" })).resolves.toEqual({
+ ok: true,
+ acceptedAs: "prompt",
+ receipt: "cursor:acp:4",
+ });
+ expect(lane.currentSessionId).toBe("cursor-acp-session");
+ await expect(lane.start({ text: "again" })).resolves.toEqual({
+ ok: false,
+ reason: "runtime_error",
+ error: "Cursor ACP session already started",
+ });
+ await expect(lane.send({ text: "busy", mode: "busy" })).resolves.toEqual({
+ ok: false,
+ reason: "unsupported",
+ error: "Cursor ACP does not support mid-turn steering",
+ });
+ await expect(lane.send({ text: "idle", mode: "idle" })).resolves.toEqual({
+ ok: false,
+ reason: "runtime_busy",
+ error: "Cursor ACP prompt is still active",
+ });
+
+ expect(lastSpawn).toMatchObject({ args: ["acp"] });
+ expect(lastSpawn!.args).not.toContain("--print");
+ expect(lastSpawn!.args).not.toContain("--resume");
+ expect(lastSpawn!.opts).not.toMatchObject({ stdin: "ignore" });
+ expect(server.messages.map((message) => message.method)).toEqual([
+ "initialize",
+ "authenticate",
+ "session/new",
+ "session/prompt",
+ ]);
+ expect(server.messages[0]!.params).toMatchObject({
+ protocolVersion: 1,
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
+ });
+ expect(server.prompts[0]!.params).toEqual({
+ sessionId: "cursor-acp-session",
+ prompt: [{ type: "text", text: "say hi" }],
+ });
+ expect(events).toEqual([{ kind: "session_init", sessionId: "cursor-acp-session" }]);
+ });
+
+ it("loads an ACP session without a fresh fallback and returns reset_required for an old incompatible id", async () => {
+ killEmitsExit = true;
+ const server = installServer({ sessionId: "legacy-print-id", loadError: "Session not found" });
+ const lane = await new CursorDriver().openLane(baseCtx({ config: {
+ sessionId: "legacy-print-id",
+ runtimeConfig: { model: { kind: "default" } },
+ } }));
+ eventsFrom(lane);
+ const exits: unknown[] = [];
+ lane.on("exit", (exit) => exits.push(exit));
+
+ await expect(lane.start({ text: "resume", sessionId: "legacy-print-id" })).resolves.toEqual({
+ ok: false,
+ reason: "reset_required",
+ error: "Cursor session cannot be loaded through ACP; reset this agent to start a new ACP session",
+ });
+ expect(server.messages.map((message) => message.method)).toEqual([
+ "initialize",
+ "authenticate",
+ "session/load",
+ ]);
+ expect(server.messages.some((message) => message.method === "session/new")).toBe(false);
+ expect(exits).toEqual([]);
+ });
+
+ it("rejects non-missing load failures, invalid new ids, and mismatched resumed ids", async () => {
+ installServer({ sessionId: "legacy", loadError: "Permission denied" });
+ const loadFailure = await new CursorDriver().openLane(baseCtx({ config: {
+ sessionId: "legacy",
+ runtimeConfig: { model: { kind: "default" } },
+ } }));
+ eventsFrom(loadFailure);
+ await expect(loadFailure.start({ text: "resume", sessionId: "legacy" }))
+ .rejects.toThrow("Permission denied");
+
+ installServer({ sessionId: "" });
+ const invalid = await new CursorDriver().openLane(baseCtx());
+ eventsFrom(invalid);
+ await expect(invalid.start({ text: "new" })).rejects.toThrow("valid session id");
+
+ installServer({ sessionId: "different" });
+ const mismatched = await new CursorDriver().openLane(baseCtx({ config: {
+ sessionId: "requested",
+ runtimeConfig: { model: { kind: "default" } },
+ } }));
+ eventsFrom(mismatched);
+ await expect(mismatched.start({ text: "resume", sessionId: "requested" })).resolves.toMatchObject({
+ ok: false,
+ reason: "reset_required",
+ error: expect.stringContaining("loaded a different session"),
+ });
+ });
+
+ it("times out an unanswered handshake call", async () => {
+ const process = fakeProcess();
+ const lane = new CursorAcpLane(
+ { spawn: async () => ({ process }) },
+ baseCtx(),
+ { handshakeTimeoutMs: 10 },
+ );
+ lane.on("runtime_event", () => {});
+ lane.on("error", () => {});
+ onClientMessage = () => {};
+
+ await expect(lane.start({ text: "timeout" })).rejects.toThrow("Cursor ACP initialize timed out");
+ });
+
+ it("cleans request and prompt ownership when stdin becomes unwritable", async () => {
+ const requestProcess = fakeProcess();
+ requestProcess.stdin.end();
+ const requestLane = new CursorAcpLane({ spawn: async () => ({ process: requestProcess }) }, baseCtx());
+ requestLane.on("runtime_event", () => {});
+ requestLane.on("error", () => {});
+ await expect(requestLane.start({ text: "request write" })).rejects.toThrow("stdin is not writable");
+
+ installServer();
+ const original = onClientMessage;
+ onClientMessage = (process, message) => {
+ original(process, message);
+ if (message.method === "session/new") process.stdin.end();
+ };
+ const promptLane = await new CursorDriver().openLane(baseCtx());
+ eventsFrom(promptLane);
+ await expect(promptLane.start({ text: "prompt write" })).rejects.toThrow("stdin is not writable");
+ });
+
+ it("fails a handshake response that omits both result and error", async () => {
+ onClientMessage = (process, message) => {
+ if (message.method === "initialize") {
+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id })}\n`);
+ }
+ };
+ const lane = await new CursorDriver().openLane(baseCtx());
+ eventsFrom(lane);
+ await expect(lane.start({ text: "missing result" })).rejects.toThrow("response omitted result");
+ });
+
+ it("uses the safe fallback for a JSON-RPC error without a message", async () => {
+ onClientMessage = (process, message) => {
+ if (message.method === "initialize") {
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: message.id,
+ error: { code: -32000 },
+ })}\n`);
+ }
+ };
+ const lane = await new CursorDriver().openLane(baseCtx());
+ eventsFrom(lane);
+ await expect(lane.start({ text: "missing error message" })).rejects.toThrow("Cursor ACP request failed");
+ });
+
+ it.each([
+ {
+ name: "protocol version 1",
+ initialize: {
+ protocolVersion: 2,
+ agentCapabilities: { loadSession: true },
+ authMethods: [{ id: "cursor_login" }],
+ },
+ error: "protocol version 1",
+ },
+ {
+ name: "loadSession capability",
+ initialize: {
+ protocolVersion: 1,
+ agentCapabilities: { loadSession: false },
+ authMethods: [{ id: "cursor_login" }],
+ },
+ error: "persistent session loading",
+ },
+ {
+ name: "Cursor login auth method",
+ initialize: {
+ protocolVersion: 1,
+ agentCapabilities: { loadSession: true },
+ authMethods: [],
+ },
+ error: "Cursor login authentication",
+ },
+ ])("fails the strict handshake closed without $name", async ({ initialize, error }) => {
+ const messages: RpcMessage[] = [];
+ onClientMessage = (process, message) => {
+ messages.push(message);
+ if (message.method === "initialize") respond(process, message, initialize);
+ };
+ const lane = await new CursorDriver().openLane(baseCtx());
+ eventsFrom(lane);
+ await expect(lane.start({ text: "strict" })).resolves.toMatchObject({
+ ok: false,
+ reason: "incompatible_configuration",
+ error: expect.stringContaining(error),
+ });
+ expect(messages.map((message) => message.method)).toEqual(["initialize"]);
+ });
+
+ it("maps a configured model through ACP config options and fails closed when unavailable", async () => {
+ const server = installServer({
+ modelOptions: [[{ value: "gpt-5.6-sol[reasoning=medium]", name: "gpt-5.6-sol" }]] as never,
+ });
+ const lane = await new CursorDriver().openLane(baseCtx({
+ config: { runtimeConfig: { model: { kind: "named", name: "gpt-5.6-sol" } } },
+ }));
+ eventsFrom(lane);
+ await expect(lane.start({ text: "configured" })).resolves.toMatchObject({ ok: true });
+ expect(server.messages.find((message) => message.method === "session/set_config_option")?.params).toEqual({
+ sessionId: "cursor-acp-session",
+ configId: "model",
+ value: "gpt-5.6-sol[reasoning=medium]",
+ });
+
+ installServer({ modelOptions: [{ value: "default[]", name: "Auto" }] });
+ const incompatible = await new CursorDriver().openLane(baseCtx({
+ config: { runtimeConfig: { model: { kind: "named", name: "missing-model" } } },
+ }));
+ eventsFrom(incompatible);
+ await expect(incompatible.start({ text: "configured" })).resolves.toMatchObject({
+ ok: false,
+ reason: "incompatible_configuration",
+ error: expect.stringContaining("missing-model"),
+ });
+ });
+
+ it("fails closed when requested model configuration is absent or rejected", async () => {
+ installServer();
+ const absent = await new CursorDriver().openLane(baseCtx({
+ config: { runtimeConfig: { model: { kind: "named", name: "gpt-5.6-sol" } } },
+ }));
+ eventsFrom(absent);
+ await expect(absent.start({ text: "configured" })).resolves.toMatchObject({
+ ok: false,
+ reason: "incompatible_configuration",
+ error: expect.stringContaining("does not support model configuration"),
+ });
+
+ installServer({ modelOptions: [{ value: "gpt-5.6-sol", name: "gpt-5.6-sol" }] });
+ const original = onClientMessage;
+ onClientMessage = (process, message) => {
+ if (message.method === "session/set_config_option") fail(process, message, "rejected");
+ else original(process, message);
+ };
+ const rejected = await new CursorDriver().openLane(baseCtx({
+ config: { runtimeConfig: { model: { kind: "named", name: "gpt-5.6-sol" } } },
+ }));
+ eventsFrom(rejected);
+ await expect(rejected.start({ text: "configured" })).resolves.toMatchObject({
+ ok: false,
+ reason: "incompatible_configuration",
+ error: expect.stringContaining("rejected model configuration"),
+ });
+ });
+
+ it("settles malformed and failed prompt responses without leaking ownership", async () => {
+ const server = installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ await lane.start({ text: "first" });
+ const process = spawned[0]!;
+
+ fail(process, server.prompts[0]!, "Prompt failed", { message: "private vendor detail" });
+ await settle();
+ expect(events).toContainEqual({ kind: "error", message: "Prompt failed: private vendor detail" });
+
+ await lane.send({ text: "second", mode: "idle" });
+ respond(process, server.prompts[1]!, { stopReason: "unknown" });
+ await settle();
+ expect(events).toContainEqual({
+ kind: "error",
+ message: "Cursor ACP prompt response did not contain a supported stopReason",
+ });
+
+ await lane.send({ text: "third", mode: "idle" });
+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: server.prompts[2]!.id })}\n`);
+ await settle();
+ expect(events).toContainEqual({ kind: "error", message: "Cursor ACP response omitted result" });
+
+ await lane.send({ text: "fourth", mode: "idle" });
+ respond(process, server.prompts[3]!, { stopReason: "end_turn", usage: { inputTokens: 2, outputTokens: 3 } });
+ await settle();
+ expect(events).toContainEqual({
+ kind: "telemetry",
+ name: "token_usage",
+ source: "cursor.acp",
+ attrs: { inputTokens: 2, outputTokens: 3 },
+ });
+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(4);
+ });
+
+ it("keeps ten identical root turns on one ACP process and correlates terminals by request id", async () => {
+ const server = installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ for (let turn = 0; turn < 10; turn += 1) {
+ const admission = turn === 0
+ ? await lane.start({ text: "same" })
+ : await lane.send({ text: "same", mode: "idle" });
+ expect(admission).toMatchObject({ ok: true, acceptedAs: "prompt" });
+ const prompt = server.prompts[turn]!;
+ completePrompt(spawned[0]!, prompt);
+ await settle();
+ }
+ expect(spawned).toHaveLength(1);
+ expect(server.messages.filter((message) => message.method === "session/new")).toHaveLength(1);
+ expect(new Set(server.prompts.map((prompt) => prompt.id)).size).toBe(10);
+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(10);
+ });
+
+ it("ignores duplicate and late prompt responses instead of ending the next turn", async () => {
+ const server = installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ await lane.start({ text: "same" });
+ const first = server.prompts[0]!;
+ completePrompt(spawned[0]!, first);
+ await settle();
+ await lane.send({ text: "same", mode: "idle" });
+ completePrompt(spawned[0]!, first);
+ await settle();
+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(1);
+ expect(events).toContainEqual(expect.objectContaining({ kind: "runtime_diagnostic", severity: "warning" }));
+ completePrompt(spawned[0]!, server.prompts[1]!);
+ await settle();
+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(2);
+ });
+
+ it("settles a prompt synchronously before dropping a later update in the same stdout chunk", async () => {
+ const server = installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ await lane.start({ text: "wire order" });
+ const process = spawned[0]!;
+ const prompt = server.prompts[0]!;
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "cursor-acp-session",
+ update: { sessionUpdate: "tool_call", toolCallId: "old-tool", title: "Old tool" },
+ },
+ })}\n`);
+ process.stdout.write([
+ JSON.stringify({ jsonrpc: "2.0", id: prompt.id, result: { stopReason: "end_turn" } }),
+ JSON.stringify({
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "cursor-acp-session",
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "must-not-project" },
+ },
+ },
+ }),
+ "",
+ ].join("\n"));
+
+ expect(events.findIndex((event) => event.kind === "turn_end")).toBeGreaterThanOrEqual(0);
+ expect(events.some((event) => event.kind === "text")).toBe(false);
+ expect(events.at(-1)).toMatchObject({
+ kind: "runtime_diagnostic",
+ severity: "warning",
+ message: "Cursor ACP emitted a session update without an active prompt",
+ });
+ await expect(lane.send({ text: "next", mode: "idle" })).resolves.toMatchObject({ ok: true });
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "cursor-acp-session",
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "old-tool",
+ title: "Old tool",
+ status: "completed",
+ },
+ },
+ })}\n`);
+ expect(events.some((event) => event.kind === "tool_output")).toBe(false);
+ });
+
+ it("drops a next-tick same-session update after the prompt terminal", async () => {
+ const server = installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ await lane.start({ text: "late update" });
+ completePrompt(spawned[0]!, server.prompts[0]!);
+ await settle();
+ spawned[0]!.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "cursor-acp-session",
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "must-not-project" },
+ },
+ },
+ })}\n`);
+
+ expect(events.some((event) => event.kind === "text")).toBe(false);
+ expect(events).toContainEqual(expect.objectContaining({
+ kind: "runtime_diagnostic",
+ message: "Cursor ACP emitted a session update without an active prompt",
+ }));
+ });
+
+ it("answers only allow_once permissions, fails unknown permission types closed, and cancels without killing", async () => {
+ const server = installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ await lane.start({ text: "permissions" });
+ const process = spawned[0]!;
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: "permission-1",
+ method: "session/request_permission",
+ params: {
+ sessionId: "cursor-acp-session",
+ options: [{ optionId: "vendor-choice-7", kind: "allow_once", name: "Allow once" }],
+ },
+ })}\n`);
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: "permission-2",
+ method: "session/request_permission",
+ params: {
+ sessionId: "cursor-acp-session",
+ options: [{ optionId: "allow-always", kind: "allow_always", name: "Allow always" }],
+ },
+ })}\n`);
+ await expect(lane.interrupt({ requestId: "cancel-1" })).resolves.toBe(true);
+
+ expect(server.messages).toContainEqual({
+ jsonrpc: "2.0",
+ id: "permission-1",
+ result: { outcome: { outcome: "selected", optionId: "vendor-choice-7" } },
+ });
+ expect(server.messages).toContainEqual({
+ jsonrpc: "2.0",
+ id: "permission-2",
+ result: { outcome: { outcome: "cancelled" } },
+ });
+ expect(server.messages).toContainEqual({
+ jsonrpc: "2.0",
+ method: "session/cancel",
+ params: { sessionId: "cursor-acp-session" },
+ });
+ expect(process.kill).not.toHaveBeenCalled();
+ expect(JSON.stringify(events)).not.toContain("vendor-choice-7");
+ completePrompt(process, server.prompts[0]!, "cancelled");
+ await settle();
+ expect(events).toContainEqual(expect.objectContaining({ kind: "turn_end" }));
+ });
+
+ it("answers unsupported client requests and diagnoses unknown notifications", async () => {
+ const server = installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ await lane.start({ text: "protocol extensions" });
+ const process = spawned[0]!;
+
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: "client-request",
+ method: "terminal_create",
+ params: {},
+ })}\n`);
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ method: "vendor_secret",
+ params: {},
+ })}\n`);
+
+ expect(server.messages).toContainEqual({
+ jsonrpc: "2.0",
+ id: "client-request",
+ error: { code: -32601, message: "Unsupported Cursor ACP client request" },
+ });
+ expect(events).toContainEqual(expect.objectContaining({
+ kind: "runtime_diagnostic",
+ message: "Unsupported Cursor ACP client request: terminal_create",
+ }));
+ expect(events).toContainEqual(expect.objectContaining({
+ kind: "runtime_diagnostic",
+ message: "Unsupported Cursor ACP notification: vendor_secret",
+ }));
+ const stderr: string[] = [];
+ lane.on("stderr", (text) => stderr.push(text));
+ process.stderr.write(" warning from cursor \n");
+ expect(stderr).toEqual(["warning from cursor"]);
+ });
+
+ it("fails closed when a client request cannot be written back", async () => {
+ installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const errors: Error[] = [];
+ lane.on("runtime_event", () => {});
+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));
+ await lane.start({ text: "broken response pipe" });
+ const process = spawned[0]!;
+ process.stdin.end();
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: "client-request",
+ method: "terminal_create",
+ params: {},
+ })}\n`);
+
+ await vi.waitFor(() => expect(errors).toContainEqual(
+ new Error("Cursor ACP could not answer a client-side protocol request"),
+ ));
+ });
+
+ it.each([
+ { wire: { jsonrpc: "1.0" }, message: "invalid JSON-RPC message" },
+ { wire: { jsonrpc: "2.0" }, message: "unrecognized JSON-RPC message" },
+ ])("fails closed on an $message", async ({ wire, message }) => {
+ installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const errors: Error[] = [];
+ lane.on("runtime_event", () => {});
+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));
+ await lane.start({ text: "invalid protocol" });
+
+ spawned.at(-1)!.stdout.write(`${JSON.stringify(wire)}\n`);
+ await vi.waitFor(() => expect(errors).toContainEqual(new Error(`Cursor ACP emitted an ${message}`)));
+ });
+
+ it("cancels permissions outside the active root prompt, including after a same-chunk terminal", async () => {
+ const messages: RpcMessage[] = [];
+ const prompts: RpcMessage[] = [];
+ onClientMessage = (process, message) => {
+ messages.push(message);
+ if (message.method === "initialize") {
+ respond(process, message, {
+ protocolVersion: 1,
+ agentCapabilities: { loadSession: true },
+ authMethods: [{ id: "cursor_login" }],
+ });
+ } else if (message.method === "authenticate") {
+ respond(process, message, {});
+ } else if (message.method === "session/new") {
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: "permission-before-prompt",
+ method: "session/request_permission",
+ params: {
+ sessionId: "cursor-acp-session",
+ options: [{ optionId: "allow-once", kind: "allow_once" }],
+ },
+ })}\n`);
+ respond(process, message, { sessionId: "cursor-acp-session", configOptions: [] });
+ } else if (message.method === "session/prompt") {
+ prompts.push(message);
+ }
+ };
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ await lane.start({ text: "permission fence" });
+ const process = spawned[0]!;
+
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: "permission-cross-session",
+ method: "session/request_permission",
+ params: {
+ sessionId: "other-session",
+ options: [{ optionId: "allow-once", kind: "allow_once" }],
+ },
+ })}\n`);
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: "permission-unknown-type",
+ method: "session/request_permission",
+ params: {
+ sessionId: "cursor-acp-session",
+ options: [{ optionId: "allow-always", kind: "allow_always" }],
+ },
+ })}\n`);
+ process.stdout.write([
+ JSON.stringify({ jsonrpc: "2.0", id: prompts[0]!.id, result: { stopReason: "end_turn" } }),
+ JSON.stringify({
+ jsonrpc: "2.0",
+ id: "permission-after-terminal",
+ method: "session/request_permission",
+ params: {
+ sessionId: "cursor-acp-session",
+ options: [{ optionId: "allow-once", kind: "allow_once" }],
+ },
+ }),
+ "",
+ ].join("\n"));
+
+ for (const id of [
+ "permission-before-prompt",
+ "permission-cross-session",
+ "permission-unknown-type",
+ "permission-after-terminal",
+ ]) {
+ expect(messages).toContainEqual({
+ jsonrpc: "2.0",
+ id,
+ result: { outcome: { outcome: "cancelled" } },
+ });
+ }
+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(1);
+ });
+
+ it("rejects malformed allow_once option ids while a root prompt is active", async () => {
+ const server = installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ await lane.start({ text: "malformed permission ids" });
+ const process = spawned[0]!;
+ const malformed = [
+ { id: "permission-missing-id", option: { kind: "allow_once" } },
+ { id: "permission-empty-id", option: { optionId: "", kind: "allow_once" } },
+ { id: "permission-whitespace-id", option: { optionId: " ", kind: "allow_once" } },
+ { id: "permission-non-string-id", option: { optionId: 7, kind: "allow_once" } },
+ ];
+ for (const entry of malformed) {
+ process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: entry.id,
+ method: "session/request_permission",
+ params: { sessionId: "cursor-acp-session", options: [entry.option] },
+ })}\n`);
+ }
+
+ for (const entry of malformed) {
+ expect(server.messages).toContainEqual({
+ jsonrpc: "2.0",
+ id: entry.id,
+ result: { outcome: { outcome: "cancelled" } },
+ });
+ }
+ expect(events).toHaveLength(malformed.length + 1);
+ expect(events.slice(1)).toEqual(malformed.map(() => expect.objectContaining({
+ kind: "runtime_diagnostic",
+ severity: "error",
+ message: "Cursor ACP permission request was not allowed for the active prompt",
+ })));
+ });
+
+ it("fences a stop racing the final handshake response before ready or prompt admission", async () => {
+ const messages: RpcMessage[] = [];
+ let lane!: RuntimeLane;
+ onClientMessage = (process, message) => {
+ messages.push(message);
+ if (message.method === "initialize") {
+ respond(process, message, {
+ protocolVersion: 1,
+ agentCapabilities: { loadSession: true },
+ authMethods: [{ id: "cursor_login" }],
+ });
+ } else if (message.method === "authenticate") {
+ respond(process, message, {});
+ } else if (message.method === "session/new") {
+ respond(process, message, { sessionId: "cursor-acp-session", configOptions: [] });
+ void lane.stop({ reason: "race", forceAfterMs: 0 });
+ }
+ };
+ lane = await new CursorDriver().openLane(baseCtx());
+ eventsFrom(lane);
+
+ await expect(lane.start({ text: "must not admit" })).rejects.toThrow("start was cancelled");
+ expect(messages.some((message) => message.method === "session/prompt")).toBe(false);
+ expect(spawned[0]!.kill).toHaveBeenCalledOnce();
+ });
+
+ it("does not activate when the process exits with the final handshake response", async () => {
+ const messages: RpcMessage[] = [];
+ onClientMessage = (process, message) => {
+ messages.push(message);
+ if (message.method === "initialize") {
+ respond(process, message, {
+ protocolVersion: 1,
+ agentCapabilities: { loadSession: true },
+ authMethods: [{ id: "cursor_login" }],
+ });
+ } else if (message.method === "authenticate") {
+ respond(process, message, {});
+ } else if (message.method === "session/new") {
+ respond(process, message, { sessionId: "cursor-acp-session", configOptions: [] });
+ process.finish(17, null);
+ }
+ };
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const exits: unknown[] = [];
+ lane.on("error", () => {});
+ lane.on("runtime_event", () => {});
+ lane.on("exit", (exit) => exits.push(exit));
+
+ await expect(lane.start({ text: "must not admit" })).rejects.toThrow("process exited during startup");
+ expect(messages.some((message) => message.method === "session/prompt")).toBe(false);
+ expect(exits).toEqual([]);
+ expect(spawned[0]!.kill).not.toHaveBeenCalled();
+ });
+
+ it("keeps a pre-spawn stop durable and terminates the eventual process exactly once", async () => {
+ const spawnGate = deferred<{ process: FakeProcess }>();
+ const driver = new CursorDriver();
+ vi.spyOn(driver, "spawn").mockReturnValue(spawnGate.promise);
+ const lane = await driver.openLane(baseCtx());
+ eventsFrom(lane);
+ const starting = lane.start({ text: "must not admit" });
+ await settle();
+ const stopping = lane.stop({ reason: "race", forceAfterMs: 0 });
+ const process = fakeProcess();
+ spawnGate.resolve({ process });
+
+ await expect(stopping).resolves.toBeUndefined();
+ await expect(starting).rejects.toThrow("start was cancelled");
+ expect(process.kill).toHaveBeenCalledOnce();
+ });
+
+ it("keeps the public session idle when a late Cursor update follows the terminal", async () => {
+ const server = installServer();
+ const host = createFakeAgentDriverHost();
+ const workingDirectory = mkdtempSync(join(tmpdir(), "cursor-acp-public-test-"));
+ temporaryDirectories.push(workingDirectory);
+ const opened = await createAgentDriverSdk({ host }).open({
+ backend: "cursor",
+ config: { model: { kind: "default" } },
+ launch: {
+ workingDirectory,
+ instructions: { format: "markdown", content: "" },
+ launchId: "cursor-acp-public-late-update",
+ },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ await expect(opened.session.start({ id: "one", kind: "user", text: "public" }))
+ .resolves.toMatchObject({ status: "accepted" });
+ completePrompt(spawned[0]!, server.prompts[0]!);
+ await settle();
+ spawned[0]!.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "cursor-acp-session",
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "must-not-resurrect" },
+ },
+ },
+ })}\n`);
+ await settle();
+
+ expect(opened.session.snapshot()).toMatchObject({ state: "idle", activeTurn: undefined });
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 0 });
+ });
+
+ it("closes an active public session on process error without exit and deduplicates a later exit", async () => {
+ installServer();
+ const host = createFakeAgentDriverHost();
+ const workingDirectory = mkdtempSync(join(tmpdir(), "cursor-acp-public-error-test-"));
+ temporaryDirectories.push(workingDirectory);
+ const opened = await createAgentDriverSdk({ host }).open({
+ backend: "cursor",
+ config: { model: { kind: "default" } },
+ launch: {
+ workingDirectory,
+ instructions: { format: "markdown", content: "" },
+ launchId: "cursor-acp-public-error-only",
+ },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ await expect(opened.session.start({ id: "one", kind: "user", text: "public" }))
+ .resolves.toMatchObject({ status: "accepted" });
+ const process = spawned[0]!;
+
+ process.emit("error", new Error("EIO"));
+ process.emit("error", new Error("duplicate"));
+
+ await expect(opened.session.closed).resolves.toMatchObject({
+ outcome: "crashed",
+ exitCode: null,
+ signal: null,
+ });
+ expect(process.kill).toHaveBeenCalledOnce();
+ expect(host.releases).toHaveLength(1);
+
+ process.finish(17, null);
+ process.emit("error", new Error("late"));
+ await settle();
+ expect(process.kill).toHaveBeenCalledOnce();
+ expect(host.releases).toHaveLength(1);
+ });
+
+ it("projects same-session updates, scrubs unknown updates, and ignores cross-session content", async () => {
+ const server = installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const events = eventsFrom(lane);
+ await lane.start({ text: "updates" });
+ const process = spawned[0]!;
+ const update = (sessionId: string, body: RpcMessage) => process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: { sessionId, update: body },
+ })}\n`);
+ update("cursor-acp-session", {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "hello" },
+ });
+ update("cursor-acp-session", {
+ sessionUpdate: "agent_thought_chunk",
+ content: { type: "text", text: "thinking" },
+ });
+ update("cursor-acp-session", {
+ sessionUpdate: "user_message_chunk",
+ content: { type: "text", text: "echo" },
+ });
+ update("cursor-acp-session", {
+ sessionUpdate: "tool_call",
+ toolCallId: "tool-1",
+ title: "Read",
+ rawInput: { path: "README.md" },
+ });
+ update("cursor-acp-session", {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "tool-1",
+ title: "Read",
+ status: "completed",
+ });
+ update("cursor-acp-session", { sessionUpdate: "tool_call", toolCallId: 42, title: "bad" });
+ update("cursor-acp-session", { sessionUpdate: "plan" });
+ update("cursor-acp-session", { sessionUpdate: "secret=value" });
+ update("other-session", {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "must-not-project" },
+ });
+
+ expect(events).toContainEqual({ kind: "text", text: "hello" });
+ expect(events).toContainEqual({ kind: "thinking", text: "thinking" });
+ expect(events).toContainEqual({ kind: "tool_call", name: "Read", input: { path: "README.md" } });
+ expect(events).toContainEqual({ kind: "tool_output", name: "Read" });
+ expect(events).toContainEqual({ kind: "internal_progress", source: "cursor.acp", itemType: "plan" });
+ expect(events).toContainEqual(expect.objectContaining({
+ kind: "runtime_diagnostic",
+ message: "Cursor ACP emitted a malformed tool_call update",
+ }));
+ expect(JSON.stringify(events)).not.toContain("secret=value");
+ expect(JSON.stringify(events)).not.toContain("must-not-project");
+ });
+
+ it("turns an activated process error into one killed crash exit", async () => {
+ installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const errors: Error[] = [];
+ const exits: unknown[] = [];
+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));
+ lane.on("runtime_event", () => {});
+ lane.on("exit", (exit) => exits.push(exit));
+ await lane.start({ text: "crash" });
+ const process = spawned[0]!;
+
+ process.emit("error", new Error("EIO"));
+ process.emit("error", new Error("duplicate"));
+ await settle();
+
+ expect(errors).toEqual([new Error("EIO")]);
+ expect(exits).toEqual([{ code: null, signal: null, reason: "runtime_exit" }]);
+ expect(process.kill).toHaveBeenCalledOnce();
+
+ process.finish(17, null);
+ process.emit("error", new Error("late"));
+ expect(exits).toHaveLength(1);
+ expect(errors).toHaveLength(1);
+ expect(process.kill).toHaveBeenCalledOnce();
+ });
+
+ it("ignores a process error after an authoritative exit", async () => {
+ installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const errors: Error[] = [];
+ const exits: unknown[] = [];
+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));
+ lane.on("runtime_event", () => {});
+ lane.on("exit", (exit) => exits.push(exit));
+ await lane.start({ text: "crash" });
+ const process = spawned[0]!;
+
+ process.finish(17, null);
+ process.emit("error", new Error("late"));
+
+ expect(exits).toEqual([{ code: 17, signal: null, reason: "runtime_exit" }]);
+ expect(errors).toEqual([]);
+ expect(process.kill).not.toHaveBeenCalled();
+ });
+
+ it("keeps requested stop ownership when the process errors during cleanup", async () => {
+ installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const errors: Error[] = [];
+ const exits: unknown[] = [];
+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));
+ lane.on("runtime_event", () => {});
+ lane.on("exit", (exit) => exits.push(exit));
+ await lane.start({ text: "stop" });
+ const process = spawned[0]!;
+
+ const stopping = lane.stop({ reason: "test", forceAfterMs: 0 });
+ process.emit("error", new Error("EIO"));
+ await stopping;
+
+ expect(errors).toEqual([new Error("EIO")]);
+ expect(exits).toEqual([]);
+ expect(process.kill).toHaveBeenCalledOnce();
+ });
+
+ it("kills the detached ACP group even after its root handle is already terminal", async () => {
+ installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ eventsFrom(lane);
+ await lane.start({ text: "stop" });
+ const process = spawned[0]!;
+ Object.defineProperty(process, "pid", { value: 41_001, configurable: true });
+ process.finish(0, null);
+
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+
+ expect(killProcessTree).toHaveBeenCalledWith(41_001, { graceMs: 0 });
+ expect(process.kill).not.toHaveBeenCalled();
+ });
+
+ it("keeps a handshake process error under failed-start ownership", async () => {
+ const messages: RpcMessage[] = [];
+ onClientMessage = (_process, message) => { messages.push(message); };
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const errors: Error[] = [];
+ const exits: unknown[] = [];
+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));
+ lane.on("runtime_event", () => {});
+ lane.on("exit", (exit) => exits.push(exit));
+ const starting = lane.start({ text: "must not admit" });
+ await vi.waitFor(() => expect(messages.map((message) => message.method)).toEqual(["initialize"]));
+ const process = spawned[0]!;
+
+ process.emit("error", new Error("EIO"));
+
+ await expect(starting).rejects.toThrow("EIO");
+ expect(errors).toEqual([new Error("EIO")]);
+ expect(exits).toEqual([]);
+ expect(process.kill).toHaveBeenCalledOnce();
+ });
+
+ it("keeps same-tick handshake error then exit under failed-start ownership", async () => {
+ const messages: RpcMessage[] = [];
+ onClientMessage = (_process, message) => { messages.push(message); };
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const errors: Error[] = [];
+ const exits: unknown[] = [];
+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));
+ lane.on("runtime_event", () => {});
+ lane.on("exit", (exit) => exits.push(exit));
+ const starting = lane.start({ text: "must not admit" });
+ await vi.waitFor(() => expect(messages.map((message) => message.method)).toEqual(["initialize"]));
+ const process = spawned[0]!;
+
+ process.emit("error", new Error("EIO"));
+ process.finish(17, null);
+
+ await expect(starting).rejects.toThrow("EIO");
+ expect(errors).toEqual([new Error("EIO")]);
+ expect(exits).toEqual([]);
+ expect(process.kill).not.toHaveBeenCalled();
+ });
+
+ it("keeps a bare handshake exit under failed-start ownership", async () => {
+ const messages: RpcMessage[] = [];
+ onClientMessage = (_process, message) => { messages.push(message); };
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const errors: Error[] = [];
+ const exits: unknown[] = [];
+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));
+ lane.on("runtime_event", () => {});
+ lane.on("exit", (exit) => exits.push(exit));
+ const starting = lane.start({ text: "must not admit" });
+ await vi.waitFor(() => expect(messages.map((message) => message.method)).toEqual(["initialize"]));
+ const process = spawned[0]!;
+
+ process.finish(17, null);
+
+ await expect(starting).rejects.toThrow("Cursor ACP process exited");
+ expect(errors).toEqual([]);
+ expect(exits).toEqual([]);
+ expect(process.kill).not.toHaveBeenCalled();
+ });
+
+ it("fails malformed JSON and reports an unexpected ACP process exit", async () => {
+ installServer();
+ const lane = await new CursorDriver().openLane(baseCtx());
+ const errors: unknown[] = [];
+ const exits: unknown[] = [];
+ lane.on("error", (error) => errors.push(error));
+ lane.on("exit", (exit) => exits.push(exit));
+ lane.on("runtime_event", () => {});
+ await lane.start({ text: "bad protocol" });
+ spawned[0]!.stdout.write("{not-json}\n");
+ expect(errors).toHaveLength(1);
+
+ installServer();
+ const crashed = await new CursorDriver().openLane(baseCtx());
+ crashed.on("error", () => {});
+ crashed.on("runtime_event", () => {});
+ crashed.on("exit", (exit) => exits.push(exit));
+ await crashed.start({ text: "crash" });
+ spawned[1]!.finish(17, null);
+ expect(exits).toContainEqual({ code: 17, signal: null, reason: "runtime_exit" });
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/cursor/index.ts b/src/daemon/agent-driver/src/adapters/cursor/index.ts
new file mode 100644
index 000000000..7c7f5bd53
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.ts
@@ -0,0 +1,53 @@
+/**
+ * Cursor driver — persistent Agent Client Protocol (ACP) over stdio.
+ *
+ * One `cursor-agent acp` process owns one physical Cursor session. Root
+ * prompts are correlated by their JSON-RPC request ids; the matching
+ * `session/prompt` response is the only authoritative terminal for that turn.
+ * Cursor does not accept mid-turn steering here, so LogicalAgentSession keeps
+ * busy input in its next-turn FIFO until the active prompt settles.
+ */
+import type {
+ AdapterLaunchContext,
+ BackendAdapter,
+ RuntimeLane,
+ RuntimeLaneOpenOptions,
+ SpawnedProcess,
+} from "../../internal/adapter.js";
+import { prepareCliTransport } from "../../internal/cliTransport.js";
+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
+import { spawnAgentProcess } from "../../internal/killTree.js";
+import { probeCliRuntime, resolveSpawnSpec } from "../../internal/probe.js";
+import { CursorAcpLane, type CursorAcpProcessFactory } from "./acp-lane.js";
+
+export class CursorDriver implements BackendAdapter, CursorAcpProcessFactory {
+ readonly id = "cursor";
+ readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
+ readonly execution = {
+ lifetime: "session",
+ transport: { kind: "stdio_rpc", protocol: "cursor.acp.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ } as const;
+
+ probe(command?: string) {
+ return probeCliRuntime("cursor-agent", {}, command);
+ }
+
+ async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {
+ return new CursorAcpLane(this, ctx, { onRawStdoutLine: options?.onRawStdoutLine });
+ }
+
+ async spawn(ctx: AdapterLaunchContext): Promise<SpawnedProcess> {
+ const { spawnEnv } = await prepareCliTransport(ctx);
+ const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
+ const spec = resolveSpawnSpec("cursor-agent", ["acp"], override);
+ return {
+ process: spawnAgentProcess(spec.command, spec.args, {
+ cwd: ctx.workingDirectory,
+ env: spawnEnv,
+ shell: spec.shell,
+ }),
+ };
+ }
+}
diff --git a/src/daemon/agent-driver/src/adapters/opencode/allocate-port.test.ts b/src/daemon/agent-driver/src/adapters/opencode/allocate-port.test.ts
new file mode 100644
index 000000000..1050b8e78
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/opencode/allocate-port.test.ts
@@ -0,0 +1,29 @@
+import { EventEmitter } from "node:events";
+import { describe, expect, it, vi } from "vitest";
+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
+
+const createServer = vi.hoisted(() => vi.fn());
+
+vi.mock("node:net", () => ({ createServer }));
+
+describe("OpenCode loopback allocation", () => {
+ it("fails closed when the listener reports no TCP address", async () => {
+ createServer.mockReturnValue(Object.assign(new EventEmitter(), {
+ unref: vi.fn(),
+ listen: vi.fn((_options, ready: () => void) => ready()),
+ address: vi.fn(() => null),
+ close: vi.fn((done: () => void) => done()),
+ }));
+ const { OpenCodeServiceLane } = await import("./service-lane.js");
+ const spawnService = vi.fn();
+ const lane = new OpenCodeServiceLane(
+ { spawnService },
+ fakeLaunchContext("opencode", process.cwd()),
+ { password: "test-password", portAttempts: 1 },
+ );
+
+ await expect(lane.start({ text: "root", terminalOwner: "msg_root" }))
+ .rejects.toThrow("returned no TCP address");
+ expect(spawnService).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/opencode/index.test.ts b/src/daemon/agent-driver/src/adapters/opencode/index.test.ts
new file mode 100644
index 000000000..bcce85eca
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/opencode/index.test.ts
@@ -0,0 +1,84 @@
+import { EventEmitter } from "node:events";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
+import { OpenCodeDriver } from "./index.js";
+
+const spawnAgentProcess = vi.hoisted(() => vi.fn());
+vi.mock("../../internal/killTree.js", async () => ({
+ ...(await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js")),
+ spawnAgentProcess,
+}));
+
+const directories: string[] = [];
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
+});
+
+describe("OpenCodeDriver persistent v2 service", () => {
+ let driver: OpenCodeDriver;
+
+ beforeEach(() => {
+ driver = new OpenCodeDriver();
+ });
+
+ it("declares persistent HTTP/SSE steering with transport-owned terminal receipts", () => {
+ expect(driver.execution).toEqual({
+ lifetime: "session",
+ transport: { kind: "http_sse", protocol: "opencode.v2.service.1.17.20" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ });
+ expect("normalizeLine" in driver).toBe(false);
+ });
+
+ it("creates opaque caller message ids for root ownership", () => {
+ const first = driver.beginTurn();
+ const second = driver.beginTurn();
+ expect(first).toMatch(/^msg_[a-f0-9]{32}$/);
+ expect(second).toMatch(/^msg_[a-f0-9]{32}$/);
+ expect(second).not.toBe(first);
+ });
+
+ it("opens a persistent service lane without spawning before start", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "opencode-lane-"));
+ directories.push(directory);
+ await expect(driver.openLane(fakeLaunchContext("opencode", directory))).resolves.toMatchObject({
+ currentSessionId: null,
+ });
+ expect(spawnAgentProcess).not.toHaveBeenCalled();
+ });
+
+ it("spawns one loopback service without putting its password in argv", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "opencode-driver-"));
+ directories.push(directory);
+ const process = Object.assign(new EventEmitter(), {
+ pid: 1234,
+ stdout: null,
+ stderr: null,
+ stdin: null,
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn(() => true),
+ });
+ spawnAgentProcess.mockReturnValue(process);
+
+ await driver.spawnService(fakeLaunchContext("opencode", directory, {
+ config: { runtimeConfig: { model: { kind: "default" }, command: "opencode-custom" } },
+ }), 43123, "session-secret");
+
+ expect(spawnAgentProcess).toHaveBeenCalledOnce();
+ const [command, args, options] = spawnAgentProcess.mock.calls[0]!;
+ expect(command).toBe("opencode-custom");
+ expect(args).toEqual(["serve", "--pure", "--hostname", "127.0.0.1", "--port", "43123"]);
+ expect(JSON.stringify(args)).not.toContain("session-secret");
+ expect(options).toMatchObject({
+ cwd: directory,
+ env: { OPENCODE_SERVER_PASSWORD: "session-secret" },
+ });
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/opencode/index.ts b/src/daemon/agent-driver/src/adapters/opencode/index.ts
new file mode 100644
index 000000000..87fd93c8d
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/opencode/index.ts
@@ -0,0 +1,75 @@
+/**
+ * OpenCode driver — persistent v2 service over authenticated loopback HTTP/SSE.
+ *
+ * One `opencode serve` process owns one logical Alook session. The lane uses
+ * caller-generated message ids for durable prompt admission and an
+ * admission-frontier-bound `/api/session/active` query as the terminal owner.
+ */
+import { randomBytes } from "node:crypto";
+import type {
+ AdapterLaunchContext,
+ BackendAdapter,
+ RuntimeLane,
+ RuntimeLaneOpenOptions,
+ SpawnedProcess,
+} from "../../internal/adapter.js";
+import { prepareCliTransport } from "../../internal/cliTransport.js";
+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
+import { spawnAgentProcess } from "../../internal/killTree.js";
+import { probeCliRuntime, resolveSpawnSpec } from "../../internal/probe.js";
+import {
+ OpenCodeServiceLane,
+ type OpenCodeServiceProcessFactory,
+} from "./service-lane.js";
+
+function createOpenCodeMessageId(): string {
+ return `msg_${randomBytes(16).toString("hex")}`;
+}
+
+export class OpenCodeDriver implements BackendAdapter, OpenCodeServiceProcessFactory {
+ readonly id = "opencode";
+ readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
+ readonly execution = {
+ lifetime: "session",
+ transport: { kind: "http_sse", protocol: "opencode.v2.service.1.17.20" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ } as const;
+
+ probe(command?: string) {
+ return probeCliRuntime("opencode", {}, command);
+ }
+
+ beginTurn(): string {
+ return createOpenCodeMessageId();
+ }
+
+ async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {
+ return new OpenCodeServiceLane(this, ctx, {
+ onRawStdoutLine: options?.onRawStdoutLine,
+ });
+ }
+
+ async spawnService(ctx: AdapterLaunchContext, port: number, password: string): Promise<SpawnedProcess> {
+ const { spawnEnv } = await prepareCliTransport(ctx, {
+ OPENCODE_SERVER_PASSWORD: password,
+ });
+ const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
+ const args = [
+ "serve",
+ "--pure",
+ "--hostname",
+ "127.0.0.1",
+ "--port",
+ String(port),
+ ];
+ const spec = resolveSpawnSpec("opencode", args, override);
+ return {
+ process: spawnAgentProcess(spec.command, spec.args, {
+ cwd: ctx.workingDirectory,
+ env: spawnEnv,
+ shell: spec.shell,
+ }),
+ };
+ }
+}
diff --git a/src/daemon/agent-driver/src/adapters/opencode/service-lane.test.ts b/src/daemon/agent-driver/src/adapters/opencode/service-lane.test.ts
new file mode 100644
index 000000000..6a22f4405
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/opencode/service-lane.test.ts
@@ -0,0 +1,1718 @@
+import { EventEmitter } from "node:events";
+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
+import { PassThrough } from "node:stream";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type {
+ AdapterEvent,
+ LaneAdmission,
+ RuntimeLaneEventMap,
+ SpawnedProcessHandle,
+} from "../../internal/adapter.js";
+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
+import {
+ OpenCodeServiceLane,
+ type OpenCodeServiceProcessFactory,
+} from "./service-lane.js";
+
+const killProcessTree = vi.hoisted(() => vi.fn());
+vi.mock("../../internal/killTree.js", async () => ({
+ ...(await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js")),
+ killProcessTree,
+}));
+
+type MutableProcess = SpawnedProcessHandle & {
+ pid: number;
+ exitCode: number | null;
+ signalCode: string | null;
+ emit(event: string, ...args: unknown[]): boolean;
+};
+
+interface PendingResponse {
+ readonly respond: () => void;
+}
+
+const REQUIRED_PATHS = [
+ "/api/session",
+ "/api/session/active",
+ "/api/session/{sessionID}/prompt",
+ "/api/session/{sessionID}/event",
+ "/api/session/{sessionID}/history",
+ "/api/session/{sessionID}/interrupt",
+ "/api/session/{sessionID}/model",
+ "/api/session/{sessionID}/permission",
+ "/api/session/{sessionID}/permission/{requestID}/reply",
+ "/api/event",
+];
+
+async function requestBody(request: IncomingMessage): Promise<Record<string, unknown>> {
+ let body = "";
+ for await (const chunk of request) body += chunk.toString();
+ return body ? JSON.parse(body) as Record<string, unknown> : {};
+}
+
+function json(response: ServerResponse, status: number, body: unknown): void {
+ response.writeHead(status, { "content-type": "application/json" });
+ response.end(JSON.stringify(body));
+}
+
+class FakeOpenCodeService {
+ sessionId = "ses_fake";
+ readonly prompts: Record<string, unknown>[] = [];
+ readonly permissionReplies: Record<string, unknown>[] = [];
+ readonly authHeaders: string[] = [];
+ readonly durableEvents: Record<string, unknown>[] = [];
+ readonly pendingPromptResponses: PendingResponse[] = [];
+ readonly pendingActiveResponses: PendingResponse[] = [];
+ readonly pendingHistoryResponses: PendingResponse[] = [];
+ readonly durableClients = new Set<ServerResponse>();
+ readonly liveClients = new Set<ServerResponse>();
+ readonly heldDurableClients: ServerResponse[] = [];
+ readonly stalledStreamResponses = new Set<ServerResponse>();
+ readonly stalledJsonResponses = new Set<ServerResponse>();
+ readonly stallJsonBodies = new Set<"health" | "history" | "prompt" | "active">();
+ readonly pendingPermissions: Record<string, unknown>[] = [];
+ readonly existingSessions = new Set<string>();
+ active = false;
+ holdPromptResponses = false;
+ holdActiveResponses = false;
+ holdHistoryResponses = false;
+ holdDurableConnections = false;
+ releaseDurableOnPrompt = false;
+ failDurableConnections = 0;
+ failLiveConnections = 0;
+ stallDurableConnections = 0;
+ stallLiveConnections = 0;
+ malformedHistoryPage = false;
+ stalledHistoryCursor = false;
+ interruptStatus = 204;
+ permissionReplyStatus = 204;
+ resumeResponseId: string | undefined;
+ createdSessionId: string | undefined;
+ promptReceiptSeqOffset = 0;
+ requiredPaths = REQUIRED_PATHS;
+ durableConnectionAttempts = 0;
+ liveConnectionAttempts = 0;
+ malformedPromptReceipt = false;
+ malformedActiveResponse = false;
+ createCount = 0;
+ interruptCount = 0;
+ activeCount = 0;
+ private seq = 0;
+ private eventId = 0;
+ private server: Server;
+
+ constructor(
+ readonly port: number,
+ readonly password: string,
+ readonly process: MutableProcess,
+ readonly healthVersion = "1.17.20",
+ readonly healthStatus = 200,
+ ) {
+ this.server = createServer((request, response) => void this.handle(request, response));
+ }
+
+ async listen(): Promise<void> {
+ await new Promise<void>((resolve, reject) => {
+ this.server.once("error", reject);
+ this.server.listen(this.port, "127.0.0.1", resolve);
+ });
+ }
+
+ close(signal = "SIGTERM"): void {
+ if (this.process.exitCode !== null || this.process.signalCode !== null) return;
+ for (const response of [
+ ...this.durableClients,
+ ...this.liveClients,
+ ...this.heldDurableClients,
+ ...this.stalledStreamResponses,
+ ...this.stalledJsonResponses,
+ ]) response.destroy();
+ this.server.close();
+ this.process.signalCode = signal;
+ this.process.emit("exit", null, signal);
+ }
+
+ releasePrompt(): void {
+ this.pendingPromptResponses.shift()?.respond();
+ }
+
+ releaseActive(): void {
+ this.pendingActiveResponses.shift()?.respond();
+ }
+
+ releaseHistory(): void {
+ this.pendingHistoryResponses.shift()?.respond();
+ }
+
+ releaseDurableConnections(): void {
+ this.holdDurableConnections = false;
+ for (const response of this.heldDurableClients.splice(0)) this.openSse(response, this.durableClients);
+ }
+
+ disconnectDurable(): void {
+ for (const response of [...this.durableClients]) response.end();
+ this.durableClients.clear();
+ }
+
+ disconnectLive(): void {
+ for (const response of [...this.liveClients]) response.end();
+ this.liveClients.clear();
+ }
+
+ publish(type: string, data: Record<string, unknown>): number {
+ const event = this.appendHistoryOnly(type, data);
+ this.broadcast(this.durableClients, event);
+ return (event.durable as { seq: number }).seq;
+ }
+
+ appendHistoryOnly(type: string, data: Record<string, unknown>): Record<string, unknown> {
+ const seq = ++this.seq;
+ const event = {
+ id: `evt_${++this.eventId}`,
+ type,
+ durable: { aggregateID: this.sessionId, seq, version: 1 },
+ data: { sessionID: this.sessionId, ...data },
+ };
+ this.durableEvents.push(event);
+ return event;
+ }
+
+ replayDurable(event: Record<string, unknown>): void {
+ this.broadcast(this.durableClients, event);
+ }
+
+ finishSuccess(text = "done"): void {
+ this.publish("session.next.text.ended", {
+ assistantMessageID: `msg_assistant_${this.seq}`,
+ textID: `text_${this.seq}`,
+ text,
+ });
+ this.publish("session.next.step.ended", {
+ assistantMessageID: `msg_assistant_${this.seq}`,
+ finish: "stop",
+ cost: 0,
+ tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
+ });
+ this.active = false;
+ }
+
+ askPermission(id = "per_test"): void {
+ const permission = { id, sessionID: this.sessionId, action: "read", resources: ["file"] };
+ this.pendingPermissions.push(permission);
+ this.broadcast(this.liveClients, { id: `evt_live_${id}`, type: "permission.v2.asked", data: permission });
+ }
+
+ publishLive(value: unknown): void {
+ this.broadcast(this.liveClients, value);
+ }
+
+ publishRawDurable(data: string): void {
+ for (const response of this.durableClients) response.write(`data: ${data}\n\n`);
+ }
+
+ emitGlobalIdle(): void {
+ this.broadcast(this.liveClients, { id: "evt_idle", type: "session.idle", data: { sessionID: this.sessionId } });
+ }
+
+ private openSse(response: ServerResponse, collection: Set<ServerResponse>): void {
+ response.writeHead(200, {
+ "content-type": "text/event-stream",
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ });
+ response.flushHeaders();
+ collection.add(response);
+ response.on("close", () => collection.delete(response));
+ }
+
+ private broadcast(clients: Set<ServerResponse>, event: unknown): void {
+ for (const response of clients) response.write(`data: ${JSON.stringify(event)}\n\n`);
+ }
+
+ private stallJson(key: "health" | "history" | "prompt" | "active", response: ServerResponse): boolean {
+ if (!this.stallJsonBodies.has(key)) return false;
+ response.writeHead(200, { "content-type": "application/json" });
+ response.flushHeaders();
+ this.stalledJsonResponses.add(response);
+ response.on("close", () => this.stalledJsonResponses.delete(response));
+ return true;
+ }
+
+ private stallStream(response: ServerResponse): void {
+ this.stalledStreamResponses.add(response);
+ response.on("close", () => this.stalledStreamResponses.delete(response));
+ }
+
+ private authorized(request: IncomingMessage, response: ServerResponse): boolean {
+ const header = String(request.headers.authorization ?? "");
+ this.authHeaders.push(header);
+ const expected = `Basic ${Buffer.from(`opencode:${this.password}`).toString("base64")}`;
+ if (header === expected) return true;
+ json(response, 401, { error: "unauthorized" });
+ return false;
+ }
+
+ private async handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
+ if (!this.authorized(request, response)) return;
+ const url = new URL(request.url ?? "/", `http://127.0.0.1:${this.port}`);
+ const path = url.pathname;
+ if (request.method === "GET" && path === "/global/health") {
+ if (this.stallJson("health", response)) return;
+ json(response, this.healthStatus, { healthy: this.healthStatus === 200, version: this.healthVersion });
+ return;
+ }
+ if (request.method === "GET" && path === "/doc") {
+ json(response, 200, { paths: Object.fromEntries(this.requiredPaths.map((item) => [item, { get: {} }])) });
+ return;
+ }
+ if (request.method === "POST" && path === "/api/session") {
+ this.createCount += 1;
+ if (this.createdSessionId !== undefined) this.sessionId = this.createdSessionId;
+ this.existingSessions.add(this.sessionId);
+ json(response, 200, { data: { id: this.sessionId } });
+ return;
+ }
+ if (request.method === "GET" && path !== "/api/session/active" && /^\/api\/session\/[^/]+$/.test(path)) {
+ const id = decodeURIComponent(path.slice("/api/session/".length));
+ if (!this.existingSessions.has(id)) json(response, 404, { error: "missing" });
+ else {
+ this.sessionId = id;
+ json(response, 200, { data: { id: this.resumeResponseId ?? id } });
+ }
+ return;
+ }
+ if (request.method === "POST" && /\/model$/.test(path)) {
+ response.writeHead(204).end();
+ return;
+ }
+ if (request.method === "GET" && path === `/api/session/${this.sessionId}/event`) {
+ this.durableConnectionAttempts += 1;
+ if (this.stallDurableConnections > 0) {
+ this.stallDurableConnections -= 1;
+ this.stallStream(response);
+ return;
+ }
+ if (this.failDurableConnections > 0) {
+ this.failDurableConnections -= 1;
+ json(response, 503, { error: "durable unavailable" });
+ return;
+ }
+ if (this.holdDurableConnections) this.heldDurableClients.push(response);
+ else this.openSse(response, this.durableClients);
+ return;
+ }
+ if (request.method === "GET" && path === "/api/event") {
+ this.liveConnectionAttempts += 1;
+ if (this.stallLiveConnections > 0) {
+ this.stallLiveConnections -= 1;
+ this.stallStream(response);
+ return;
+ }
+ if (this.failLiveConnections > 0) {
+ this.failLiveConnections -= 1;
+ json(response, 503, { error: "live unavailable" });
+ return;
+ }
+ this.openSse(response, this.liveClients);
+ return;
+ }
+ if (request.method === "GET" && path === `/api/session/${this.sessionId}/history`) {
+ if (this.stallJson("history", response)) return;
+ const after = Number(url.searchParams.get("after") ?? 0);
+ const limit = Number(url.searchParams.get("limit") ?? 100);
+ const respond = () => {
+ if (this.malformedHistoryPage) {
+ json(response, 200, { data: null, hasMore: "yes" });
+ return;
+ }
+ if (this.stalledHistoryCursor) {
+ json(response, 200, { data: [], hasMore: true });
+ return;
+ }
+ const events = this.durableEvents.filter((event) => {
+ const durable = event.durable as { seq: number };
+ return durable.seq > after;
+ });
+ json(response, 200, { data: events.slice(0, limit), hasMore: events.length > limit });
+ };
+ if (this.holdHistoryResponses) this.pendingHistoryResponses.push({ respond });
+ else respond();
+ return;
+ }
+ if (request.method === "POST" && path === `/api/session/${this.sessionId}/prompt`) {
+ const body = await requestBody(request);
+ this.prompts.push(body);
+ const messageId = String(body.id);
+ const delivery = String(body.delivery);
+ if (this.releaseDurableOnPrompt) this.releaseDurableConnections();
+ const admittedSeq = this.publish("session.next.prompt.admitted", { messageID: messageId, delivery, prompt: body.prompt });
+ this.active = true;
+ const respond = () => {
+ if (this.stallJson("prompt", response)) return;
+ json(response, 200, {
+ data: {
+ admittedSeq,
+ ...(this.promptReceiptSeqOffset ? { admittedSeq: admittedSeq + this.promptReceiptSeqOffset } : {}),
+ id: this.malformedPromptReceipt ? "msg_wrong" : messageId,
+ sessionID: this.sessionId,
+ prompt: body.prompt,
+ delivery,
+ timeCreated: Date.now(),
+ },
+ });
+ };
+ if (this.holdPromptResponses) this.pendingPromptResponses.push({ respond });
+ else respond();
+ return;
+ }
+ if (request.method === "GET" && path === "/api/session/active") {
+ this.activeCount += 1;
+ const snapshot = this.active ? { [this.sessionId]: { type: "running" } } : {};
+ const respond = () => {
+ if (this.stallJson("active", response)) return;
+ json(response, 200, this.malformedActiveResponse ? { data: null } : { data: snapshot });
+ };
+ if (this.holdActiveResponses) this.pendingActiveResponses.push({ respond });
+ else respond();
+ return;
+ }
+ if (request.method === "POST" && path === `/api/session/${this.sessionId}/interrupt`) {
+ this.interruptCount += 1;
+ this.active = false;
+ response.writeHead(this.interruptStatus).end();
+ return;
+ }
+ if (request.method === "GET" && path === `/api/session/${this.sessionId}/permission`) {
+ json(response, 200, { data: this.pendingPermissions });
+ return;
+ }
+ const permission = path.match(/^\/api\/session\/[^/]+\/permission\/([^/]+)\/reply$/);
+ if (request.method === "POST" && permission) {
+ const body = await requestBody(request);
+ this.permissionReplies.push({ id: permission[1], ...body });
+ const index = this.pendingPermissions.findIndex((item) => item.id === permission[1]);
+ if (index >= 0) this.pendingPermissions.splice(index, 1);
+ response.writeHead(this.permissionReplyStatus).end();
+ return;
+ }
+ json(response, 404, { error: "unknown route" });
+ }
+}
+
+class FakeOpenCodeFactory implements OpenCodeServiceProcessFactory {
+ spawnCount = 0;
+ failPortAttempts = 0;
+ healthVersion = "1.17.20";
+ healthStatus = 200;
+ holdSpawn = false;
+ holdDurableConnections = false;
+ holdPromptResponses = false;
+ releaseDurableOnPrompt = false;
+ failDurableConnections = 0;
+ failLiveConnections = 0;
+ stallDurableConnections = 0;
+ stallLiveConnections = 0;
+ malformedHistoryPage = false;
+ stalledHistoryCursor = false;
+ interruptStatus = 204;
+ permissionReplyStatus = 204;
+ resumeResponseId: string | undefined;
+ createdSessionId: string | undefined;
+ promptReceiptSeqOffset = 0;
+ requiredPaths = REQUIRED_PATHS;
+ readonly stallJsonBodies = new Set<"health" | "history" | "prompt" | "active">();
+ readonly existingSessions = new Set<string>();
+ service: FakeOpenCodeService | undefined;
+ private nextPid = 41000;
+ private releaseSpawnGate?: () => void;
+
+ releaseSpawn(): void {
+ this.releaseSpawnGate?.();
+ }
+
+ async spawnService(_ctx: Parameters<OpenCodeServiceProcessFactory["spawnService"]>[0], port: number, password: string) {
+ this.spawnCount += 1;
+ if (this.holdSpawn) {
+ await new Promise<void>((resolve) => { this.releaseSpawnGate = resolve; });
+ }
+ if (this.failPortAttempts > 0) {
+ this.failPortAttempts -= 1;
+ throw new Error("listen EADDRINUSE: address already in use");
+ }
+ const emitter = new EventEmitter();
+ const process = Object.assign(emitter, {
+ pid: ++this.nextPid,
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ stdin: null,
+ exitCode: null as number | null,
+ signalCode: null as string | null,
+ kill: vi.fn((signal = "SIGTERM") => {
+ this.service?.close(signal);
+ return true;
+ }),
+ }) as MutableProcess;
+ this.service = new FakeOpenCodeService(port, password, process, this.healthVersion, this.healthStatus);
+ this.service.holdDurableConnections = this.holdDurableConnections;
+ this.service.holdPromptResponses = this.holdPromptResponses;
+ this.service.releaseDurableOnPrompt = this.releaseDurableOnPrompt;
+ this.service.failDurableConnections = this.failDurableConnections;
+ this.service.failLiveConnections = this.failLiveConnections;
+ this.service.stallDurableConnections = this.stallDurableConnections;
+ this.service.stallLiveConnections = this.stallLiveConnections;
+ this.service.malformedHistoryPage = this.malformedHistoryPage;
+ this.service.stalledHistoryCursor = this.stalledHistoryCursor;
+ this.service.interruptStatus = this.interruptStatus;
+ this.service.permissionReplyStatus = this.permissionReplyStatus;
+ this.service.resumeResponseId = this.resumeResponseId;
+ this.service.createdSessionId = this.createdSessionId;
+ this.service.promptReceiptSeqOffset = this.promptReceiptSeqOffset;
+ this.service.requiredPaths = this.requiredPaths;
+ for (const key of this.stallJsonBodies) this.service.stallJsonBodies.add(key);
+ for (const id of this.existingSessions) this.service.existingSessions.add(id);
+ await this.service.listen();
+ killers.set(process.pid, () => this.service?.close());
+ return { process };
+ }
+}
+
+const factories: FakeOpenCodeFactory[] = [];
+const killers = new Map<number, () => void>();
+
+function makeLane(
+ factory = new FakeOpenCodeFactory(),
+ startTimeoutMs = 1_000,
+ requestTimeoutMs = 1_000,
+ reconnectDelayMs = 5,
+): OpenCodeServiceLane {
+ factories.push(factory);
+ const lane = new OpenCodeServiceLane(
+ factory,
+ fakeLaunchContext("opencode", process.cwd(), {
+ config: { runtimeConfig: { model: { kind: "default" } } },
+ }),
+ {
+ password: "test-password",
+ activePollMs: 5,
+ reconnectDelayMs,
+ startTimeoutMs,
+ requestTimeoutMs,
+ },
+ );
+ return lane;
+}
+
+function makeConfiguredLane(
+ factory: FakeOpenCodeFactory,
+ runtimeConfig: Record<string, unknown>,
+ options: ConstructorParameters<typeof OpenCodeServiceLane>[2] = {},
+): OpenCodeServiceLane {
+ factories.push(factory);
+ return new OpenCodeServiceLane(
+ factory,
+ fakeLaunchContext("opencode", process.cwd(), {
+ config: { runtimeConfig: runtimeConfig as never },
+ }),
+ {
+ password: "test-password",
+ activePollMs: 5,
+ reconnectDelayMs: 5,
+ startTimeoutMs: 1_000,
+ requestTimeoutMs: 1_000,
+ ...options,
+ },
+ );
+}
+
+function collectEvents(lane: OpenCodeServiceLane): {
+ runtime: AdapterEvent[];
+ exits: RuntimeLaneEventMap["exit"][];
+ errors: Error[];
+} {
+ const runtime: AdapterEvent[] = [];
+ const exits: RuntimeLaneEventMap["exit"][] = [];
+ const errors: Error[] = [];
+ lane.on("runtime_event", (event) => runtime.push(event));
+ lane.on("exit", (event) => exits.push(event));
+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));
+ return { runtime, exits, errors };
+}
+
+async function waitForTurn(events: AdapterEvent[], count: number): Promise<void> {
+ await vi.waitFor(() => {
+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(count);
+ });
+}
+
+beforeEach(() => {
+ killProcessTree.mockReset();
+ killProcessTree.mockImplementation(async (pid: number) => killers.get(pid)?.());
+});
+
+afterEach(() => {
+ for (const factory of factories.splice(0)) factory.service?.close();
+ killers.clear();
+});
+
+describe("OpenCodeServiceLane authenticated persistent protocol", () => {
+ it("validates model, OpenAPI, session creation, and resumed identity responses", async () => {
+ const invalidModel = makeConfiguredLane(new FakeOpenCodeFactory(), {
+ model: { kind: "named", name: "missing-provider-separator" },
+ });
+ await expect(invalidModel.start({ text: "root", terminalOwner: "msg_invalid_model" }))
+ .resolves.toMatchObject({ ok: false, reason: "incompatible_configuration" });
+
+ const missingApiFactory = new FakeOpenCodeFactory();
+ missingApiFactory.requiredPaths = REQUIRED_PATHS.slice(1);
+ const missingApi = makeLane(missingApiFactory);
+ await expect(missingApi.start({ text: "root", terminalOwner: "msg_missing_api" }))
+ .resolves.toMatchObject({ ok: false, reason: "incompatible_configuration" });
+
+ const invalidSessionFactory = new FakeOpenCodeFactory();
+ invalidSessionFactory.createdSessionId = "invalid";
+ const invalidSession = makeLane(invalidSessionFactory);
+ await expect(invalidSession.start({ text: "root", terminalOwner: "msg_invalid_session" }))
+ .rejects.toThrow("valid session id");
+
+ const changedResumeFactory = new FakeOpenCodeFactory();
+ changedResumeFactory.existingSessions.add("ses_resume");
+ changedResumeFactory.resumeResponseId = "ses_different";
+ const changedResume = makeLane(changedResumeFactory);
+ await expect(changedResume.start({
+ text: "root",
+ sessionId: "ses_resume",
+ terminalOwner: "msg_changed_resume",
+ })).resolves.toMatchObject({ ok: false, reason: "reset_required" });
+
+ const configuredResumeFactory = new FakeOpenCodeFactory();
+ configuredResumeFactory.existingSessions.add("ses_configured");
+ const configuredResume = makeConfiguredLane(configuredResumeFactory, {
+ model: { kind: "named", name: "anthropic/claude-sonnet" },
+ });
+ await expect(configuredResume.start({
+ text: "root",
+ sessionId: "ses_configured",
+ terminalOwner: "msg_configured",
+ })).resolves.toMatchObject({ ok: true });
+ await configuredResume.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("rejects missing process identity and an exhausted zero-attempt startup", async () => {
+ const invalidProcess = Object.assign(new EventEmitter(), {
+ pid: 0,
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ stdin: null,
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn(() => true),
+ }) as MutableProcess;
+ const invalidPidLane = new OpenCodeServiceLane(
+ { spawnService: async () => ({ process: invalidProcess }) },
+ fakeLaunchContext("opencode", process.cwd()),
+ { password: "test-password", allocatePort: async () => 43_123, portAttempts: 1 },
+ );
+ await expect(invalidPidLane.start({ text: "root", terminalOwner: "msg_invalid_pid" }))
+ .rejects.toThrow("did not expose a process id");
+
+ const noAttemptLane = new OpenCodeServiceLane(
+ { spawnService: vi.fn() },
+ fakeLaunchContext("opencode", process.cwd()),
+ { password: "test-password", portAttempts: 0 },
+ );
+ await expect(noAttemptLane.start({ text: "root", terminalOwner: "msg_no_attempt" }))
+ .rejects.toThrow("failed to start");
+ });
+
+ it("keeps pre-spawn stop pending until the eventual child is killed exactly once", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.holdSpawn = true;
+ const lane = makeLane(factory);
+ const starting = lane.start({ text: "root", terminalOwner: "msg_root" });
+ await vi.waitFor(() => expect(factory.spawnCount).toBe(1));
+
+ let stopSettled = false;
+ const stopping = lane.stop({ reason: "pre_spawn_stop", forceAfterMs: 0 })
+ .then(() => { stopSettled = true; });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(stopSettled).toBe(false);
+
+ factory.releaseSpawn();
+ await stopping;
+ await expect(starting).rejects.toThrow("stopped during startup");
+ expect(killProcessTree).toHaveBeenCalledTimes(1);
+ });
+
+ it("settles stop when an in-flight spawn ultimately rejects", async () => {
+ let rejectSpawn!: (error: Error) => void;
+ const spawn = new Promise<never>((_resolve, reject) => { rejectSpawn = reject; });
+ const lane = new OpenCodeServiceLane(
+ { spawnService: async () => spawn },
+ fakeLaunchContext("opencode", process.cwd()),
+ { password: "test-password", allocatePort: async () => 43_123 },
+ );
+ const starting = lane.start({ text: "root", terminalOwner: "msg_root" });
+ await Promise.resolve();
+ const stopping = lane.stop({ reason: "test", forceAfterMs: 0 });
+ rejectSpawn(new Error("spawn failed"));
+
+ await expect(stopping).resolves.toBeUndefined();
+ await expect(starting).rejects.toThrow("spawn failed");
+ });
+
+ it.each([
+ { stderr: "listen EADDRINUSE: address already in use", message: "port bind raced" },
+ { stderr: "", message: "exited before readiness" },
+ ])("classifies a startup process exit as $message", async ({ stderr, message }) => {
+ const child = Object.assign(new EventEmitter(), {
+ pid: 41_999,
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ stdin: null,
+ exitCode: null as number | null,
+ signalCode: null as string | null,
+ kill: vi.fn(() => true),
+ }) as MutableProcess;
+ const lane = new OpenCodeServiceLane(
+ {
+ spawnService: async () => {
+ setTimeout(() => {
+ if (stderr) (child.stderr as PassThrough).write(stderr);
+ child.exitCode = 1;
+ child.emit("exit", 1, null);
+ }, 0);
+ return { process: child };
+ },
+ },
+ fakeLaunchContext("opencode", process.cwd()),
+ { password: "test-password", allocatePort: async () => 43_123, portAttempts: 1, startTimeoutMs: 100 },
+ );
+
+ await expect(lane.start({ text: "root", terminalOwner: "msg_root" })).rejects.toThrow(message);
+ });
+
+ it("kills the detached service group even after its root handle is already terminal", async () => {
+ const factory = new FakeOpenCodeFactory();
+ const lane = makeLane(factory);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factory.service!;
+ service.process.exitCode = 0;
+
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+
+ expect(killProcessTree).toHaveBeenCalledWith(service.process.pid, { graceMs: 0 });
+ });
+
+ it("admits the first prompt when durable SSE headers wait for its first event", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.holdDurableConnections = true;
+ factory.releaseDurableOnPrompt = true;
+ const lane = makeLane(factory);
+ const starting = lane.start({ text: "root", terminalOwner: "msg_root" });
+
+ await vi.waitFor(() => expect(factory.service?.prompts).toHaveLength(1));
+ await expect(starting).resolves.toMatchObject({ ok: true, acceptedAs: "prompt", receipt: "msg_root" });
+ expect(factory.service?.durableClients.size).toBe(1);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("moves startup readiness to the next live gate after a pre-open transport failure", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.failLiveConnections = 1;
+ const lane = makeLane(factory);
+ const starting = lane.start({ text: "root", terminalOwner: "msg_root" });
+
+ await vi.waitFor(() => expect(factory.service?.prompts).toHaveLength(1));
+ await expect(starting).resolves.toMatchObject({ ok: true, acceptedAs: "prompt" });
+ expect(factory.service?.liveConnectionAttempts).toBeGreaterThanOrEqual(2);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("retries a live header deadline without cancelling lifecycle readiness", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.stallLiveConnections = 1;
+ const lane = makeLane(factory, 1_000, 1_000);
+ const starting = lane.start({ text: "root", terminalOwner: "msg_root" });
+
+ await vi.waitFor(() => expect(factory.service?.liveConnectionAttempts).toBeGreaterThanOrEqual(2), {
+ timeout: 2_500,
+ });
+ await vi.waitFor(() => expect(factory.service?.prompts).toHaveLength(1));
+ await expect(starting).resolves.toMatchObject({ ok: true, acceptedAs: "prompt" });
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("does not retry a stalled stream after lifecycle stop aborts it", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.stallLiveConnections = 1;
+ const lane = makeLane(factory, 1_000, 1_000);
+ const { runtime } = collectEvents(lane);
+ const starting = lane.start({ text: "root", terminalOwner: "msg_root" });
+ await vi.waitFor(() => expect(factory.service?.liveConnectionAttempts).toBe(1));
+
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ await expect(starting).rejects.toThrow("OpenCode service lane stopped");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(factory.service?.liveConnectionAttempts).toBe(1);
+ expect(runtime.filter((event) => event.kind === "runtime_metric")).toHaveLength(0);
+ });
+
+ it("aborts established live and durable streams on stop without process teardown", async () => {
+ const factory = new FakeOpenCodeFactory();
+ const lane = makeLane(factory, 1_000, 1_000);
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factory.service!;
+ await vi.waitFor(() => {
+ expect(service.liveClients.size).toBe(1);
+ expect(service.durableClients.size).toBe(1);
+ });
+ killProcessTree.mockImplementation(async () => {});
+
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ await vi.waitFor(() => {
+ expect(service.liveClients.size).toBe(0);
+ expect(service.durableClients.size).toBe(0);
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(service.liveConnectionAttempts).toBe(1);
+ expect(service.durableConnectionAttempts).toBe(1);
+ expect(runtime.filter((event) => event.kind === "runtime_metric")).toHaveLength(0);
+ });
+
+ it("bounds JSON response bodies for health, history, prompt admission, and active barriers", async () => {
+ const healthFactory = new FakeOpenCodeFactory();
+ healthFactory.stallJsonBodies.add("health");
+ const healthLane = makeLane(healthFactory, 60, 20);
+ await expect(healthLane.start({ text: "root", terminalOwner: "msg_health" }))
+ .rejects.toThrow("OpenCode service readiness timed out");
+
+ const historyFactory = new FakeOpenCodeFactory();
+ historyFactory.stallJsonBodies.add("history");
+ const historyLane = makeLane(historyFactory, 1_000, 20);
+ await expect(historyLane.start({ text: "root", terminalOwner: "msg_history" }))
+ .rejects.toThrow("OpenCode session history response timed out");
+
+ const promptLane = makeLane(new FakeOpenCodeFactory(), 1_000, 1_000);
+ const promptEvents = collectEvents(promptLane);
+ await promptLane.start({ text: "root", terminalOwner: "msg_prompt" });
+ const promptService = factories.at(-1)!.service!;
+ promptService.stallJsonBodies.add("prompt");
+ await expect(promptLane.send({ text: "steer", mode: "busy" }))
+ .rejects.toThrow("OpenCode prompt admission response timed out");
+ expect(promptEvents.errors).toContainEqual(
+ new Error("OpenCode prompt admission did not produce a valid durable receipt"),
+ );
+
+ const activeLane = makeLane(new FakeOpenCodeFactory(), 1_000, 1_000);
+ const activeEvents = collectEvents(activeLane);
+ await activeLane.start({ text: "root", terminalOwner: "msg_active" });
+ const activeService = factories.at(-1)!.service!;
+ activeService.stallJsonBodies.add("active");
+ activeService.finishSuccess();
+ await vi.waitFor(() => expect(activeService.stalledJsonResponses.size).toBe(1));
+ const stalledActiveResponse = [...activeService.stalledJsonResponses][0]!;
+ const activeCountAtStall = activeService.activeCount;
+ await vi.waitFor(() => expect(activeService.stalledJsonResponses.has(stalledActiveResponse)).toBe(false), {
+ timeout: 2_500,
+ });
+ await vi.waitFor(() => expect(activeService.activeCount).toBeGreaterThan(activeCountAtStall), {
+ timeout: 2_500,
+ });
+ expect(activeEvents.runtime.some((event) => event.kind === "turn_end")).toBe(false);
+ await activeLane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("keeps an external stop abort distinct from a JSON response deadline", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.stallJsonBodies.add("history");
+ const lane = makeLane(factory, 1_000, 1_000);
+ const starting = lane.start({ text: "root", terminalOwner: "msg_stopped" });
+ await vi.waitFor(() => expect(factory.service?.stalledJsonResponses.size).toBe(1));
+
+ const stopping = lane.stop({ reason: "test", forceAfterMs: 0 });
+ const error = await starting.catch((value: unknown) => value);
+ await stopping;
+
+ expect(error).toMatchObject({ name: "AbortError" });
+ expect(error).not.toMatchObject({ message: "OpenCode session history response timed out" });
+ });
+
+ it("turns an activated process error into one killed crash completion", async () => {
+ const lane = makeLane();
+ const { errors, exits } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ service.process.emit("error", new Error("EIO"));
+
+ await vi.waitFor(() => expect(killProcessTree).toHaveBeenCalledWith(service.process.pid, { graceMs: 0 }));
+ expect(errors).toContainEqual(new Error("EIO"));
+ expect(exits).toEqual([{ code: null, signal: null, reason: "runtime_exit" }]);
+ service.process.emit("exit", 1, null);
+ service.process.emit("error", new Error("duplicate"));
+ expect(exits).toHaveLength(1);
+ });
+
+ it("keeps process output observational and surfaces startup process errors", async () => {
+ const factory = new FakeOpenCodeFactory();
+ const observed: string[] = [];
+ const lane = makeConfiguredLane(factory, { model: { kind: "default" } }, {
+ onRawStdoutLine: (line) => {
+ observed.push(line);
+ if (line === "throw") throw new Error("observer failure");
+ },
+ });
+ const stderr: string[] = [];
+ lane.on("stderr", (text) => stderr.push(text));
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factory.service!;
+ (service.process.stdout as PassThrough).write("one\n\nthrow\npartial");
+ (service.process.stdout as PassThrough).write("-line\n");
+ (service.process.stderr as PassThrough).write("service warning");
+ expect(observed).toEqual(["one", "throw", "partial-line"]);
+ expect(stderr).toEqual(["service warning"]);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+
+ const startingFactory = new FakeOpenCodeFactory();
+ startingFactory.healthStatus = 503;
+ const startingLane = makeLane(startingFactory, 1_000);
+ const starting = startingLane.start({ text: "root", terminalOwner: "msg_start_error" });
+ await vi.waitFor(() => expect(startingFactory.service).toBeDefined());
+ startingFactory.service!.process.emit("error", new Error("startup EIO"));
+ await expect(starting).rejects.toThrow("startup EIO");
+ });
+
+ it("rejects an interrupt failure without exposing its request id", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.interruptStatus = 503;
+ const lane = makeLane(factory);
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+
+ await expect(lane.interrupt({ requestId: "not safe to show" })).rejects.toThrow("HTTP 503");
+ expect(runtime).toContainEqual({
+ kind: "runtime_diagnostic",
+ severity: "error",
+ source: "opencode.v2",
+ message: "OpenCode interrupt failed (unknown)",
+ });
+ });
+
+ it("fails startup if the process identity changes after prompt admission", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.holdPromptResponses = true;
+ const lane = makeLane(factory);
+ const starting = lane.start({ text: "root", terminalOwner: "msg_root" });
+ await vi.waitFor(() => expect(factory.service?.pendingPromptResponses).toHaveLength(1));
+ const service = factory.service!;
+ service.process.pid += 1;
+ service.releasePrompt();
+ await expect(starting).rejects.toThrow("identity changed during startup");
+ });
+
+ it("fails closed on unseen lower history events and sequence identity collisions", async () => {
+ const lane = makeLane();
+ const laneEvents = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ const laneState = lane as unknown as {
+ durableGap: boolean;
+ historyTail: Promise<void>;
+ catchUpHistory(project: boolean): Promise<void>;
+ };
+ await vi.waitFor(() => expect(laneState.durableGap).toBe(false));
+ await laneState.historyTail;
+ service.holdHistoryResponses = true;
+ service.appendHistoryOnly("session.next.step.ended", {
+ assistantMessageID: "msg_assistant",
+ finish: "stop",
+ cost: 0,
+ tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
+ });
+ const catchingUp = laneState.catchUpHistory(true);
+ await vi.waitFor(() => expect(service.pendingHistoryResponses).toHaveLength(1));
+ service.replayDurable({
+ id: "evt_higher_first",
+ type: "session.next.text.ended",
+ durable: { aggregateID: service.sessionId, seq: 3, version: 1 },
+ data: { sessionID: service.sessionId, assistantMessageID: "msg_assistant", textID: "text_3", text: "done" },
+ });
+ await vi.waitFor(() => expect(laneEvents.runtime).toContainEqual({ kind: "text", text: "done" }));
+ service.releaseHistory();
+ await expect(catchingUp).rejects.toThrow("OpenCode emitted an unseen durable event below the replay cursor");
+ expect(laneEvents.runtime.some((event) => event.kind === "turn_end")).toBe(false);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+
+ const collisionLane = makeLane();
+ const collisionEvents = collectEvents(collisionLane);
+ await collisionLane.start({ text: "root", terminalOwner: "msg_collision" });
+ const collisionService = factories.at(-1)!.service!;
+ const first = {
+ id: "evt_seq_owner",
+ type: "session.next.text.ended",
+ durable: { aggregateID: collisionService.sessionId, seq: 2, version: 1 },
+ data: { sessionID: collisionService.sessionId, assistantMessageID: "msg_assistant", textID: "text_2", text: "one" },
+ };
+ collisionService.replayDurable(first);
+ collisionService.replayDurable({ ...first, id: "evt_seq_collision" });
+ await vi.waitFor(() => {
+ expect(collisionEvents.errors).toContainEqual(
+ new Error("OpenCode durable event stream violated the v2 protocol"),
+ );
+ });
+ });
+
+ it("rejects malformed history pages and a paginated cursor that cannot advance", async () => {
+ const malformedFactory = new FakeOpenCodeFactory();
+ malformedFactory.malformedHistoryPage = true;
+ const malformed = makeLane(malformedFactory);
+ await expect(malformed.start({ text: "root", terminalOwner: "msg_malformed_history" }))
+ .rejects.toThrow("invalid page");
+
+ const stalledFactory = new FakeOpenCodeFactory();
+ stalledFactory.stalledHistoryCursor = true;
+ const stalled = makeLane(stalledFactory);
+ await expect(stalled.start({ text: "root", terminalOwner: "msg_stalled_history" }))
+ .rejects.toThrow("cursor did not advance");
+ });
+
+ it("rejects a prompt receipt whose durable sequence disagrees", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.promptReceiptSeqOffset = 1;
+ factory.holdPromptResponses = true;
+ const lane = makeLane(factory);
+ const { errors } = collectEvents(lane);
+ const starting = lane.start({ text: "root", terminalOwner: "msg_root" });
+ await vi.waitFor(() => expect(factory.service?.pendingPromptResponses).toHaveLength(1));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ factory.service!.releasePrompt();
+ await expect(starting)
+ .rejects.toThrow("did not match its receipt");
+ expect(errors).toContainEqual(
+ new Error("OpenCode prompt admission did not produce a valid durable receipt"),
+ );
+ });
+
+ it("fails closed when post-admission history catch-up violates the protocol", async () => {
+ const factory = new FakeOpenCodeFactory();
+ const lane = makeLane(factory);
+ const { errors } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factory.service!;
+ service.holdPromptResponses = true;
+
+ const steering = lane.send({ text: "steer", mode: "busy" });
+ await vi.waitFor(() => expect(service.pendingPromptResponses).toHaveLength(1));
+ service.disconnectDurable();
+ service.malformedHistoryPage = true;
+ service.releasePrompt();
+ await expect(steering).resolves.toMatchObject({ ok: true, acceptedAs: "steer" });
+ await vi.waitFor(() => expect(errors).toHaveLength(1));
+ expect(errors[0]!.message).toMatch(/OpenCode .* violated the v2 protocol/);
+ });
+
+ it("routes a background admission catch-up protocol error through lane failure", async () => {
+ const lane = makeLane();
+ const { errors } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const internals = lane as unknown as {
+ sessionId: string;
+ handleDurableEvent(value: unknown, project: boolean): Promise<number>;
+ fetchJsonWithTimeout(path: string, init: RequestInit, operation: string): Promise<{ response: Response; body: unknown }>;
+ catchUpHistory(project: boolean): Promise<void>;
+ queueAdmission(text: string, delivery: "queue" | "steer", messageId: string): Promise<LaneAdmission>;
+ };
+ const protocolError = await internals.handleDurableEvent({ invalid: true }, true)
+ .catch((error: unknown) => error as Error);
+ const originalFetch = internals.fetchJsonWithTimeout.bind(internals);
+ internals.fetchJsonWithTimeout = async (path, init, operation) => path.endsWith("/prompt")
+ ? {
+ response: new Response("", { status: 200 }),
+ body: {
+ data: {
+ id: "msg_background",
+ sessionID: internals.sessionId,
+ delivery: "steer",
+ admittedSeq: 9_999,
+ },
+ },
+ }
+ : originalFetch(path, init, operation);
+ internals.catchUpHistory = async () => { throw protocolError; };
+
+ await expect(internals.queueAdmission("steer", "steer", "msg_background"))
+ .resolves.toMatchObject({ ok: true, acceptedAs: "steer" });
+ await vi.waitFor(() => expect(errors).toContainEqual(
+ new Error("OpenCode session history violated the v2 protocol"),
+ ));
+ });
+
+ it("does not accept a root until the caller-id admission response arrives", async () => {
+ const factory = new FakeOpenCodeFactory();
+ const lane = makeLane(factory);
+ const starting = lane.start({ text: "root", terminalOwner: "msg_root_1" });
+ await vi.waitFor(() => expect(factory.service?.prompts).toHaveLength(1));
+ const service = factory.service!;
+ killers.set(service.process.pid, () => service.close());
+ service.holdPromptResponses = true;
+ // The first request may already have responded; hold the next root instead.
+ expect(await starting).toMatchObject({ ok: true, acceptedAs: "prompt", receipt: "msg_root_1" });
+ const events = collectEvents(lane);
+ service.finishSuccess();
+ await waitForTurn(events.runtime, 1);
+
+ const pending = lane.send({ text: "second", mode: "idle", terminalOwner: "msg_root_2" });
+ await vi.waitFor(() => expect(service.pendingPromptResponses).toHaveLength(1));
+ let settled = false;
+ void pending.then(() => { settled = true; });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ service.finishSuccess("before-receipt");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(events.runtime.filter((event) => event.kind === "turn_end")).toHaveLength(1);
+ service.releasePrompt();
+ await expect(pending).resolves.toMatchObject({ ok: true, acceptedAs: "prompt", receipt: "msg_root_2" });
+ await waitForTurn(events.runtime, 2);
+ expect(service.authHeaders.every((header) => header === `Basic ${Buffer.from("opencode:test-password").toString("base64")}`)).toBe(true);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("reuses one service for ten roots and never lets step/global-idle events own terminal", async () => {
+ const factory = new FakeOpenCodeFactory();
+ const lane = makeLane(factory);
+ const { runtime } = collectEvents(lane);
+ expect(await lane.start({ text: "identical", terminalOwner: "msg_root_1" })).toMatchObject({ ok: true });
+ const service = factory.service!;
+ killers.set(service.process.pid, () => service.close());
+ service.replayDurable(service.durableEvents[0]!);
+
+ for (let turn = 1; turn <= 10; turn += 1) {
+ service.emitGlobalIdle();
+ service.publish("session.next.step.ended", {
+ assistantMessageID: `msg_intermediate_${turn}`,
+ finish: "tool-calls",
+ cost: 0,
+ tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 15));
+ expect(runtime.filter((event) => event.kind === "turn_end")).toHaveLength(turn - 1);
+ service.finishSuccess("identical-final");
+ await waitForTurn(runtime, turn);
+ if (turn < 10) {
+ await expect(lane.send({
+ text: "identical",
+ mode: "idle",
+ terminalOwner: `msg_root_${turn + 1}`,
+ })).resolves.toMatchObject({ ok: true, acceptedAs: "prompt" });
+ }
+ }
+
+ expect(factory.spawnCount).toBe(1);
+ expect(service.prompts).toHaveLength(10);
+ expect(runtime.filter((event) => event.kind === "turn_end").map((event) => event.kind === "turn_end" && event.turnOwner))
+ .toEqual(Array.from({ length: 10 }, (_, index) => `msg_root_${index + 1}`));
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ expect(killProcessTree).toHaveBeenCalledTimes(1);
+ expect(killProcessTree).toHaveBeenCalledWith(service.process.pid, { graceMs: 0 });
+ });
+
+ it("projects the complete durable event vocabulary and fails the final turn exactly once", async () => {
+ const lane = makeLane();
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+
+ service.publish("session.next.step.started", { assistantMessageID: "msg_assistant" });
+ service.publish("session.next.reasoning.ended", {
+ assistantMessageID: "msg_assistant",
+ textID: "reasoning_1",
+ text: "considering",
+ });
+ service.publish("session.next.tool.called", {
+ assistantMessageID: "msg_assistant",
+ callID: "call_1",
+ tool: "Read",
+ input: { path: "README.md" },
+ });
+ service.publish("session.next.tool.success", {
+ assistantMessageID: "msg_assistant",
+ callID: "call_1",
+ });
+ service.publish("session.next.tool.failed", {
+ assistantMessageID: "msg_assistant",
+ callID: "call_unknown",
+ });
+ service.publish("session.next.compaction.started", { assistantMessageID: "msg_assistant" });
+ service.publish("session.next.compaction.ended", { assistantMessageID: "msg_assistant" });
+ service.publish("session.next.step.failed", {
+ assistantMessageID: "msg_assistant",
+ error: { message: "secret vendor detail" },
+ });
+ service.publish("session.next.step.failed", {
+ assistantMessageID: "msg_assistant",
+ error: {},
+ });
+ service.active = false;
+
+ await waitForTurn(runtime, 1);
+ expect(runtime).toContainEqual({ kind: "thinking", text: "" });
+ expect(runtime).toContainEqual({ kind: "thinking", text: "considering" });
+ expect(runtime).toContainEqual({ kind: "tool_call", name: "Read", input: { path: "README.md" } });
+ expect(runtime).toContainEqual({ kind: "tool_output", name: "Read" });
+ expect(runtime).toContainEqual({ kind: "tool_output", name: "OpenCode tool" });
+ expect(runtime).toContainEqual({ kind: "compaction_started" });
+ expect(runtime).toContainEqual({ kind: "compaction_finished" });
+ expect(runtime).toContainEqual({ kind: "error", message: "OpenCode reported an inconsistent turn outcome" });
+ expect(JSON.stringify(runtime)).not.toContain("secret vendor detail");
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("sorts multiple durable outcomes and uses the latest terminal fact", async () => {
+ const lane = makeLane();
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ service.publish("session.next.step.ended", { assistantMessageID: "msg_one", finish: "stop" });
+ service.publish("session.next.step.ended", { assistantMessageID: "msg_two", finish: "length" });
+ service.active = false;
+
+ await waitForTurn(runtime, 1);
+ expect(runtime.some((event) => event.kind === "error")).toBe(false);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("rechecks the durable frontier after the active-absence history barrier", async () => {
+ const lane = new OpenCodeServiceLane(
+ { spawnService: vi.fn() },
+ fakeLaunchContext("opencode", process.cwd()),
+ { password: "test-password" },
+ );
+ const { runtime } = collectEvents(lane);
+ const child = Object.assign(new EventEmitter(), {
+ pid: 42_100,
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ stdin: null,
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn(() => true),
+ }) as MutableProcess;
+ const internals = lane as unknown as {
+ activeRoot: {
+ receipt: string;
+ baselineSeq: number;
+ frontier: Map<string, number>;
+ durableAdmissions: Map<string, number>;
+ observedAdmissions: Set<string>;
+ outcomes: unknown[];
+ generation: number;
+ pendingAdmissions: number;
+ interrupted: boolean;
+ interruptPending: boolean;
+ };
+ process: MutableProcess;
+ identity: { generation: number; process: MutableProcess; pid: number };
+ sessionId: string;
+ ready: boolean;
+ stopping: boolean;
+ lastDurableSeq: number;
+ durableGap: boolean;
+ evaluationTimer?: ReturnType<typeof setTimeout>;
+ evaluating: boolean;
+ fetchJsonWithTimeout(): Promise<{ response: Response; body: unknown }>;
+ catchUpHistory(project: boolean): Promise<void>;
+ barrierStillCurrent(): boolean;
+ evaluateTerminal(): Promise<void>;
+ };
+ internals.process = child;
+ internals.identity = { generation: 1, process: child, pid: child.pid };
+ internals.sessionId = "ses_barrier";
+ internals.ready = true;
+ internals.stopping = false;
+ internals.lastDurableSeq = 1;
+ internals.durableGap = false;
+ internals.activeRoot = {
+ receipt: "msg_root",
+ baselineSeq: 0,
+ frontier: new Map([["msg_root", 1]]),
+ durableAdmissions: new Map([["msg_root", 1]]),
+ observedAdmissions: new Set(["msg_root"]),
+ outcomes: [],
+ generation: 0,
+ pendingAdmissions: 0,
+ interrupted: false,
+ interruptPending: false,
+ };
+ internals.evaluating = false;
+ internals.fetchJsonWithTimeout = async () => ({
+ response: new Response("", { status: 200 }),
+ body: { data: {} },
+ });
+ internals.catchUpHistory = async () => {
+ internals.activeRoot.observedAdmissions.clear();
+ internals.durableGap = false;
+ };
+ internals.barrierStillCurrent = () => true;
+ await internals.evaluateTerminal();
+
+ expect(runtime.some((event) => event.kind === "turn_end")).toBe(false);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("rejects malformed durable and live protocol values before they can project", async () => {
+ const lane = makeLane();
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ const internals = lane as unknown as {
+ handleDurableEvent(value: unknown, project: boolean): Promise<number>;
+ handleLiveEvent(value: unknown): Promise<void>;
+ };
+
+ await expect(internals.handleDurableEvent({ type: "bad" }, true))
+ .rejects.toThrow("invalid durable event");
+ const replayed = {
+ id: "evt_replayed",
+ type: "session.next.text.ended",
+ durable: { aggregateID: service.sessionId, seq: 500, version: 1 },
+ data: { sessionID: service.sessionId, text: "one" },
+ };
+ await internals.handleDurableEvent(replayed, true);
+ await expect(internals.handleDurableEvent({
+ ...replayed,
+ durable: { aggregateID: service.sessionId, seq: 501, version: 1 },
+ }, true)).rejects.toThrow("different sequence");
+ await expect(internals.handleDurableEvent({
+ id: "evt_missing_finish",
+ type: "session.next.step.ended",
+ durable: { aggregateID: service.sessionId, seq: 502, version: 1 },
+ data: { sessionID: service.sessionId },
+ }, true)).rejects.toThrow("omitted its finish reason");
+ await expect(internals.handleLiveEvent({
+ type: "permission.v2.asked",
+ data: { sessionID: service.sessionId, id: "malformed" },
+ })).rejects.toThrow("malformed permission request");
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it.each([
+ { kind: "durable", publish: (service: FakeOpenCodeService) => service.publishRawDurable("{not-json}") },
+ {
+ kind: "live",
+ publish: (service: FakeOpenCodeService) => service.publishLive({
+ type: "permission.v2.asked",
+ data: { sessionID: service.sessionId, id: "malformed" },
+ }),
+ },
+ ])("fails the $kind stream closed on a protocol violation", async ({ publish }) => {
+ const lane = makeLane();
+ const { errors } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ publish(factories.at(-1)!.service!);
+ await vi.waitFor(() => expect(errors).toHaveLength(1));
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("serializes ten busy steers and extends the terminal frontier by exact ids", async () => {
+ const factory = new FakeOpenCodeFactory();
+ const lane = makeLane(factory);
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factory.service!;
+ killers.set(service.process.pid, () => service.close());
+ service.holdPromptResponses = true;
+
+ const admissions = Array.from({ length: 10 }, (_, index) => lane.send({
+ text: `steer-${index + 1}`,
+ mode: "busy" as const,
+ }));
+ await vi.waitFor(() => expect(service.pendingPromptResponses).toHaveLength(1));
+ expect(service.prompts).toHaveLength(2);
+ for (let index = 0; index < 10; index += 1) {
+ service.releasePrompt();
+ if (index < 9) await vi.waitFor(() => expect(service.pendingPromptResponses).toHaveLength(1));
+ }
+ const receipts = await Promise.all(admissions);
+ expect(receipts.every((receipt) => receipt.ok && receipt.acceptedAs === "steer")).toBe(true);
+ expect(service.prompts.slice(1).map((prompt) => (prompt.prompt as { text: string }).text))
+ .toEqual(Array.from({ length: 10 }, (_, index) => `steer-${index + 1}`));
+ expect(new Set(service.prompts.map((prompt) => prompt.id)).size).toBe(11);
+
+ service.finishSuccess();
+ await waitForTurn(runtime, 1);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("fails closed when active absence has only an intermediate step outcome", async () => {
+ const lane = makeLane();
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ killers.set(service.process.pid, () => service.close());
+ service.publish("session.next.step.ended", {
+ assistantMessageID: "msg_intermediate",
+ finish: "tool-calls",
+ cost: 0,
+ tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
+ });
+ service.active = false;
+ await waitForTurn(runtime, 1);
+ expect(runtime).toContainEqual({ kind: "error", message: "OpenCode drain settled without a durable turn outcome" });
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("fails closed on malformed admission and active-barrier responses", async () => {
+ const admissionLane = makeLane();
+ const admissionEvents = collectEvents(admissionLane);
+ await admissionLane.start({ text: "root", terminalOwner: "msg_root" });
+ const admissionService = factories.at(-1)!.service!;
+ killers.set(admissionService.process.pid, () => admissionService.close());
+ admissionService.malformedPromptReceipt = true;
+ await expect(admissionLane.send({ text: "steer", mode: "busy" }))
+ .rejects.toThrow("OpenCode prompt admission returned an invalid receipt");
+ expect(admissionEvents.errors).toContainEqual(
+ new Error("OpenCode prompt admission did not produce a valid durable receipt"),
+ );
+
+ const activeLane = makeLane();
+ const activeEvents = collectEvents(activeLane);
+ await activeLane.start({ text: "root", terminalOwner: "msg_root" });
+ const activeService = factories.at(-1)!.service!;
+ killers.set(activeService.process.pid, () => activeService.close());
+ activeService.finishSuccess();
+ activeService.malformedActiveResponse = true;
+ await vi.waitFor(() => {
+ expect(activeEvents.errors).toContainEqual(new Error("OpenCode active barrier violated the v2 protocol"));
+ });
+ expect(activeEvents.runtime.some((event) => event.kind === "turn_end")).toBe(false);
+ });
+
+ it("discards an absent response whose generation changed during the query", async () => {
+ const lane = makeLane();
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ killers.set(service.process.pid, () => service.close());
+ service.holdActiveResponses = true;
+ service.finishSuccess("before-steer");
+ await vi.waitFor(() => expect(service.pendingActiveResponses).toHaveLength(1));
+
+ const steer = lane.send({ text: "late-steer", mode: "busy" });
+ await expect(steer).resolves.toMatchObject({ ok: true, acceptedAs: "steer" });
+ service.releaseActive();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(runtime.some((event) => event.kind === "turn_end")).toBe(false);
+
+ service.holdActiveResponses = false;
+ while (service.pendingActiveResponses.length > 0) service.releaseActive();
+ service.finishSuccess("after-steer");
+ await waitForTurn(runtime, 1);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("pauses admission across durable SSE disconnect and closes the replay gap before terminal", async () => {
+ const lane = makeLane();
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ killers.set(service.process.pid, () => service.close());
+ service.holdDurableConnections = true;
+ service.disconnectDurable();
+ await vi.waitFor(() => expect(runtime.filter((event) => event.kind === "runtime_metric")).toEqual([{
+ kind: "runtime_metric",
+ name: "sse_reconnect",
+ increment: 1,
+ }]));
+
+ const before = service.prompts.length;
+ const steer = lane.send({ text: "after-gap", mode: "busy" });
+ await new Promise((resolve) => setTimeout(resolve, 15));
+ expect(service.prompts).toHaveLength(before);
+ service.finishSuccess("history-only");
+ expect(runtime.some((event) => event.kind === "turn_end")).toBe(false);
+
+ service.releaseDurableConnections();
+ await expect(steer).resolves.toMatchObject({ ok: true, acceptedAs: "steer" });
+ service.finishSuccess("after-replay");
+ await waitForTurn(runtime, 1);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("moves a paused admission to the next durable gate after a pre-open transport failure", async () => {
+ const lane = makeLane(new FakeOpenCodeFactory(), 1_000, 1_000, 100);
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ service.failDurableConnections = 1;
+ service.holdDurableConnections = true;
+ service.disconnectDurable();
+ await vi.waitFor(() => expect(runtime.filter((event) => event.kind === "runtime_metric")).toHaveLength(1));
+
+ const steer = lane.send({ text: "after-gap", mode: "busy" });
+ await vi.waitFor(() => expect(service.durableConnectionAttempts).toBeGreaterThanOrEqual(3));
+ service.finishSuccess("history-only");
+ service.releaseDurableConnections();
+
+ await expect(steer).resolves.toMatchObject({ ok: true, acceptedAs: "steer" });
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("retries a durable header deadline while keeping later admission paused", async () => {
+ const lane = makeLane(new FakeOpenCodeFactory(), 1_000, 100, 50);
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ service.stallDurableConnections = 1;
+ service.disconnectDurable();
+ await vi.waitFor(() => expect(runtime.filter((event) => event.kind === "runtime_metric")).toHaveLength(1));
+
+ const steer = lane.send({ text: "after-deadline", mode: "busy" });
+ await vi.waitFor(() => expect(service.durableConnectionAttempts).toBe(2));
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ expect(service.prompts).toHaveLength(1);
+ await vi.waitFor(() => expect(service.durableConnectionAttempts).toBeGreaterThanOrEqual(3));
+
+ await expect(steer).resolves.toMatchObject({ ok: true, acceptedAs: "steer" });
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("replies allow-once to live and recovered pending permissions", async () => {
+ const lane = makeLane();
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ killers.set(service.process.pid, () => service.close());
+ service.askPermission("per_live");
+ await vi.waitFor(() => expect(service.permissionReplies).toContainEqual({ id: "per_live", reply: "once" }));
+ service.pendingPermissions.push({
+ id: "per_recovered",
+ sessionID: service.sessionId,
+ action: "read",
+ resources: ["file"],
+ });
+ service.disconnectLive();
+ await vi.waitFor(() => expect(runtime.filter((event) => event.kind === "runtime_metric")).toEqual([{
+ kind: "runtime_metric",
+ name: "sse_reconnect",
+ increment: 1,
+ }]));
+ await vi.waitFor(() => expect(service.permissionReplies).toContainEqual({ id: "per_recovered", reply: "once" }));
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("treats an already-removed permission reply as handled", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.permissionReplyStatus = 404;
+ const lane = makeLane(factory);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factory.service!;
+ service.askPermission("per_removed");
+ await vi.waitFor(() => expect(service.permissionReplies).toContainEqual({ id: "per_removed", reply: "once" }));
+ service.askPermission("per_removed");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(service.permissionReplies.filter((item) => item.id === "per_removed")).toHaveLength(1);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("interrupts through HTTP and settles only after the active-absence barrier", async () => {
+ const lane = makeLane();
+ const { runtime } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ killers.set(service.process.pid, () => service.close());
+ expect(await lane.interrupt({ requestId: "interrupt-1" })).toBe(true);
+ expect(service.interruptCount).toBe(1);
+ await waitForTurn(runtime, 1);
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("crashes an active turn when the service PID identity changes", async () => {
+ const lane = makeLane();
+ const { exits } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ killers.set(service.process.pid, () => service.close());
+ service.process.pid += 1;
+ await expect(lane.send({ text: "must-fail", mode: "busy" })).resolves.toMatchObject({ ok: false, reason: "closed" });
+ await vi.waitFor(() => expect(exits).toContainEqual({ code: null, signal: null, reason: "runtime_exit" }));
+ });
+
+ it("reports a service crash during an active turn and rejects incompatible installed versions", async () => {
+ const lane = makeLane();
+ const { exits } = collectEvents(lane);
+ await lane.start({ text: "root", terminalOwner: "msg_root" });
+ const service = factories.at(-1)!.service!;
+ killers.set(service.process.pid, () => service.close());
+ service.close("SIGKILL");
+ await vi.waitFor(() => expect(exits).toContainEqual({ code: null, signal: "SIGKILL", reason: "runtime_exit" }));
+
+ const incompatibleFactory = new FakeOpenCodeFactory();
+ incompatibleFactory.healthVersion = "1.17.21";
+ const incompatible = makeLane(incompatibleFactory);
+ await expect(incompatible.start({ text: "root", terminalOwner: "msg_bad_version" }))
+ .resolves.toMatchObject({ ok: false, reason: "incompatible_configuration" });
+ });
+
+ it("fails a health timeout without admitting a prompt", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.healthStatus = 503;
+ const lane = makeLane(factory, 40);
+ await expect(lane.start({ text: "root", terminalOwner: "msg_timeout" }))
+ .rejects.toThrow("OpenCode service readiness timed out");
+ expect(factory.service?.prompts).toHaveLength(0);
+ });
+
+ it("resumes an existing cross-interface session without silently creating a replacement", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.existingSessions.add("ses_legacy_run");
+ const lane = makeLane(factory);
+ await expect(lane.start({
+ text: "resume",
+ sessionId: "ses_legacy_run",
+ terminalOwner: "msg_resume",
+ })).resolves.toMatchObject({ ok: true, receipt: "msg_resume" });
+ expect(lane.currentSessionId).toBe("ses_legacy_run");
+ expect(factory.service?.createCount).toBe(0);
+ const service = factory.service!;
+ killers.set(service.process.pid, () => service.close());
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+ });
+
+ it("retries a bounded port bind race and fails a missing resume closed", async () => {
+ const factory = new FakeOpenCodeFactory();
+ factory.failPortAttempts = 1;
+ const lane = makeLane(factory);
+ await expect(lane.start({ text: "root", terminalOwner: "msg_root" })).resolves.toMatchObject({ ok: true });
+ expect(factory.spawnCount).toBe(2);
+ const service = factory.service!;
+ killers.set(service.process.pid, () => service.close());
+ await lane.stop({ reason: "test", forceAfterMs: 0 });
+
+ const missingFactory = new FakeOpenCodeFactory();
+ const missing = makeLane(missingFactory);
+ await expect(missing.start({ text: "root", sessionId: "ses_missing", terminalOwner: "msg_missing" }))
+ .resolves.toMatchObject({ ok: false, reason: "reset_required" });
+ expect(missingFactory.service?.createCount).toBe(0);
+ });
+
+ it("normalizes low-level HTTP, JSON, and stopped-stream failures", async () => {
+ const ctx = fakeLaunchContext("opencode", process.cwd(), {
+ config: { runtimeConfig: { model: { kind: "default" } } },
+ });
+ const factory = new FakeOpenCodeFactory();
+ const httpLane = new OpenCodeServiceLane(factory, ctx, {
+ password: "test-password",
+ fetch: vi.fn(async () => new Response("", { status: 503 })),
+ });
+ const http = httpLane as unknown as {
+ baseUrl: string;
+ requestNoContent(path: string, method: "POST", body: Record<string, unknown> | undefined, operation: string): Promise<void>;
+ };
+ http.baseUrl = "http://127.0.0.1";
+ await expect(http.requestNoContent("/fail", "POST", undefined, "test operation"))
+ .rejects.toThrow("OpenCode test operation failed with HTTP 503");
+
+ const jsonLane = new OpenCodeServiceLane(factory, ctx, {
+ password: "test-password",
+ fetch: vi.fn(async () => new Response("{", {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ })),
+ });
+ const json = jsonLane as unknown as {
+ baseUrl: string;
+ fetchJsonWithTimeout(path: string, init: RequestInit, operation: string): Promise<unknown>;
+ };
+ json.baseUrl = "http://127.0.0.1";
+ await expect(json.fetchJsonWithTimeout("/bad-json", { method: "GET" }, "test JSON"))
+ .rejects.toThrow("OpenCode test JSON returned invalid JSON");
+
+ const rejectedLane = new OpenCodeServiceLane(factory, ctx, {
+ password: "test-password",
+ fetch: vi.fn(async () => Promise.reject("network rejected")),
+ });
+ const rejected = rejectedLane as unknown as {
+ baseUrl: string;
+ fetchWithTimeout(path: string, init: RequestInit, operation: string): Promise<Response>;
+ };
+ rejected.baseUrl = "http://127.0.0.1";
+ await expect(rejected.fetchWithTimeout("/rejected", { method: "GET" }, "test fetch"))
+ .rejects.toThrow("OpenCode test fetch request failed");
+
+ const stoppedLane = new OpenCodeServiceLane(factory, ctx, { password: "test-password" });
+ await stoppedLane.stop({ reason: "test", forceAfterMs: 0 });
+ const stopped = stoppedLane as unknown as {
+ waitForLiveStream(): Promise<void>;
+ waitForStreams(): Promise<void>;
+ protocolFailure(message: string): void;
+ };
+ await expect(stopped.waitForLiveStream()).rejects.toThrow("stopped before stream recovery");
+ await expect(stopped.waitForStreams()).rejects.toThrow("stopped before stream recovery");
+ expect(() => stopped.protocolFailure("already stopped")).not.toThrow();
+ });
+
+ it("cleans defensive no-pid, stream-failure, replay, and admission paths", async () => {
+ const ctx = fakeLaunchContext("opencode", process.cwd(), {
+ config: { runtimeConfig: { model: { kind: "default" } } },
+ });
+ const processWithoutPid = Object.assign(new EventEmitter(), {
+ pid: undefined,
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ stdin: null,
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn(() => true),
+ }) as unknown as MutableProcess;
+ const stopLane = new OpenCodeServiceLane({ spawnService: vi.fn() }, ctx, { password: "test-password" });
+ (stopLane as unknown as { process: MutableProcess }).process = processWithoutPid;
+ await stopLane.stop({ signal: "SIGKILL", forceAfterMs: 0 });
+ expect(processWithoutPid.kill).toHaveBeenCalledWith("SIGKILL");
+
+ const streamLane = new OpenCodeServiceLane({ spawnService: vi.fn() }, ctx, { password: "test-password" });
+ const streamErrors: Error[] = [];
+ streamLane.on("error", (error) => streamErrors.push(error instanceof Error ? error : new Error(String(error))));
+ (streamLane as unknown as { streamFailure(kind: "durable" | "live", error: unknown): void })
+ .streamFailure("durable", new Error("stream task failed"));
+ expect(streamErrors).toEqual([new Error("OpenCode durable stream stopped unexpectedly")]);
+
+ const replayLane = new OpenCodeServiceLane({ spawnService: vi.fn() }, ctx, { password: "test-password" });
+ const replay = replayLane as unknown as {
+ sessionId: string;
+ handleDurableEvent(value: unknown, project: boolean): Promise<number>;
+ queueAdmission(text: string, delivery: "queue" | "steer", messageId: string): Promise<LaneAdmission>;
+ beginRoot(input: { text: string; terminalOwner?: string }): Promise<LaneAdmission>;
+ activeRoot: unknown;
+ };
+ replay.sessionId = "ses_replay";
+ await expect(replay.handleDurableEvent({
+ id: "evt_replay",
+ type: "session.next.text.ended",
+ durable: { aggregateID: "ses_replay", seq: 1, version: 1 },
+ data: { sessionID: "ses_replay", text: "not projected" },
+ }, false)).resolves.toBe(1);
+
+ replay.activeRoot = {
+ receipt: "msg_closed",
+ baselineSeq: 0,
+ frontier: new Map(),
+ durableAdmissions: new Map(),
+ observedAdmissions: new Set(),
+ outcomes: [],
+ generation: 0,
+ pendingAdmissions: 0,
+ interrupted: false,
+ interruptPending: false,
+ };
+ await expect(replay.queueAdmission("closed", "queue", "msg_closed"))
+ .resolves.toEqual({ ok: false, reason: "closed" });
+
+ const originalQueue = replay.queueAdmission.bind(replay);
+ replay.queueAdmission = async () => { throw new Error("admission failed"); };
+ await expect(replay.beginRoot({ text: "root", terminalOwner: "msg_root" }))
+ .rejects.toThrow("admission failed");
+ expect(replay.activeRoot).toBeNull();
+ replay.queueAdmission = originalQueue;
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts b/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts
new file mode 100644
index 000000000..1a2c3389d
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts
@@ -0,0 +1,1287 @@
+import { randomBytes } from "node:crypto";
+import { EventEmitter } from "node:events";
+import { createServer } from "node:net";
+import type {
+ AdapterEvent,
+ AdapterLaunchContext,
+ LaneAdmission,
+ LaneInterruptInput,
+ LaneSendInput,
+ LaneStartInput,
+ LaneStopInput,
+ RuntimeLane,
+ RuntimeLaneEventMap,
+ SpawnedProcess,
+ SpawnedProcessHandle,
+} from "../../internal/adapter.js";
+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
+import { killProcessTree, SESSION_STOP_GRACE_MS } from "../../internal/killTree.js";
+
+const SUPPORTED_VERSION = "1.17.20";
+const HOST = "127.0.0.1";
+const START_TIMEOUT_MS = 15_000;
+const REQUEST_TIMEOUT_MS = 15_000;
+const RECONNECT_DELAY_MS = 100;
+const ACTIVE_POLL_MS = 50;
+const PORT_ATTEMPTS = 3;
+const HISTORY_PAGE_LIMIT = 100;
+
+type JsonRecord = Record<string, unknown>;
+
+interface ServiceIdentity {
+ readonly generation: number;
+ readonly process: SpawnedProcessHandle;
+ readonly pid: number;
+}
+
+interface TurnOutcome {
+ readonly seq: number;
+ readonly ok: boolean;
+ readonly message?: string;
+}
+
+interface ActiveRoot {
+ readonly receipt: string;
+ readonly baselineSeq: number;
+ readonly frontier: Map<string, number>;
+ readonly durableAdmissions: Map<string, number>;
+ readonly observedAdmissions: Set<string>;
+ readonly outcomes: TurnOutcome[];
+ generation: number;
+ pendingAdmissions: number;
+ interrupted: boolean;
+ interruptPending: boolean;
+}
+
+interface StreamGate {
+ readonly promise: Promise<void>;
+ resolve(): void;
+ reject(error: Error): void;
+}
+
+interface OpenCodeServiceLaneOptions {
+ readonly onRawStdoutLine?: (line: string) => void;
+ readonly fetch?: typeof fetch;
+ readonly allocatePort?: () => Promise<number>;
+ readonly startTimeoutMs?: number;
+ readonly requestTimeoutMs?: number;
+ readonly reconnectDelayMs?: number;
+ readonly activePollMs?: number;
+ readonly portAttempts?: number;
+ readonly password?: string;
+}
+
+export interface OpenCodeServiceProcessFactory {
+ spawnService(ctx: AdapterLaunchContext, port: number, password: string): Promise<SpawnedProcess>;
+}
+
+class OpenCodeIncompatibleError extends Error {}
+class OpenCodeResetRequiredError extends Error {}
+class OpenCodePortBindError extends Error {}
+class OpenCodeProtocolError extends Error {}
+class OpenCodeStoppedError extends Error {}
+
+class OpenCodeHttpError extends Error {
+ constructor(
+ readonly status: number,
+ operation: string,
+ ) {
+ super(`OpenCode ${operation} failed with HTTP ${status}`);
+ }
+}
+
+function record(value: unknown): JsonRecord | null {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? value as JsonRecord
+ : null;
+}
+
+function safeLabel(value: unknown): string {
+ return typeof value === "string" && /^[a-z0-9_.:-]{1,80}$/i.test(value) ? value : "unknown";
+}
+
+function makeGate(): StreamGate {
+ let resolve!: () => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<void>((accept, decline) => {
+ resolve = accept;
+ reject = decline;
+ });
+ promise.catch(() => {});
+ return { promise, resolve, reject };
+}
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolve) => {
+ const timer = setTimeout(resolve, ms);
+ timer.unref?.();
+ });
+}
+
+async function allocateLoopbackPort(): Promise<number> {
+ return new Promise<number>((resolve, reject) => {
+ const server = createServer();
+ server.unref();
+ server.once("error", reject);
+ server.listen({ host: HOST, port: 0, exclusive: true }, () => {
+ const address = server.address();
+ if (!address || typeof address === "string") {
+ server.close(() => reject(new Error("OpenCode port allocation returned no TCP address")));
+ return;
+ }
+ server.close((error) => error ? reject(error) : resolve(address.port));
+ });
+ });
+}
+
+function parseModelRef(model: string | undefined): JsonRecord | undefined {
+ if (!model) return undefined;
+ const slash = model.indexOf("/");
+ if (slash < 1 || slash === model.length - 1) {
+ throw new OpenCodeIncompatibleError("Configured OpenCode model must use provider/model form for the v2 API");
+ }
+ return { providerID: model.slice(0, slash), id: model.slice(slash + 1) };
+}
+
+function messageFromError(value: unknown): string {
+ const payload = record(value);
+ const message = typeof payload?.message === "string" && payload.message.trim()
+ ? payload.message
+ : undefined;
+ return message ? "OpenCode turn failed" : "OpenCode reported an inconsistent turn outcome";
+}
+
+export class OpenCodeServiceLane implements RuntimeLane {
+ private readonly events = new EventEmitter();
+ private readonly fetchFn: typeof fetch;
+ private readonly password: string;
+ private readonly requestControllers = new Set<AbortController>();
+ private process: SpawnedProcessHandle | null = null;
+ private identity: ServiceIdentity | null = null;
+ private baseUrl = "";
+ private sessionId: string | null = null;
+ private stdoutBuffer = "";
+ private stderrBuffer = "";
+ private serviceGeneration = 0;
+ private started = false;
+ private ready = false;
+ private stopping = false;
+ private requestedStopReason?: string;
+ private suppressExit = false;
+ private serviceActivated = false;
+ private processStartError: Error | null = null;
+ private spawnPromise: Promise<SpawnedProcess> | null = null;
+ private stopPromise?: Promise<void>;
+ private readonly processStopPromises = new WeakMap<object, Promise<void>>();
+ private terminalProcessGeneration: number | null = null;
+ private durableAbort?: AbortController;
+ private liveAbort?: AbortController;
+ private durableTask?: Promise<void>;
+ private liveTask?: Promise<void>;
+ private durableBootstrapAdmissionUsed = false;
+ private durableGate = makeGate();
+ private liveGate = makeGate();
+ private durableGap = true;
+ private lastDurableSeq = 0;
+ private readonly durableSeqById = new Map<string, number>();
+ private readonly durableIdBySeq = new Map<number, string>();
+ private readonly toolNames = new Map<string, string>();
+ private readonly handledPermissions = new Set<string>();
+ private readonly permissionFlights = new Map<string, Promise<void>>();
+ private activeRoot: ActiveRoot | null = null;
+ private admissionTail: Promise<void> = Promise.resolve();
+ private historyTail: Promise<void> = Promise.resolve();
+ private evaluationTimer?: ReturnType<typeof setTimeout>;
+ private evaluating = false;
+ private reevaluate = false;
+ private reevaluateDelayMs: number | undefined;
+ private identityFailed = false;
+
+ constructor(
+ private readonly factory: OpenCodeServiceProcessFactory,
+ private readonly ctx: AdapterLaunchContext,
+ private readonly options: OpenCodeServiceLaneOptions = {},
+ ) {
+ this.fetchFn = options.fetch ?? fetch;
+ this.password = options.password ?? randomBytes(32).toString("base64url");
+ }
+
+ get currentSessionId(): string | null {
+ return this.sessionId;
+ }
+
+ on<K extends keyof RuntimeLaneEventMap>(
+ event: K,
+ listener: (value: RuntimeLaneEventMap[K]) => void,
+ ): void {
+ this.events.on(event, listener);
+ }
+
+ async start(input: LaneStartInput): Promise<LaneAdmission> {
+ if (this.started) return { ok: false, reason: "already_started", error: "OpenCode service lane already started" };
+ this.started = true;
+ try {
+ await this.startService();
+ const startupIdentity = this.identity;
+ if (!startupIdentity) throw new Error("OpenCode service started without an identity");
+ this.assertStartupIdentity(startupIdentity);
+ await this.openSession(input.sessionId ?? this.ctx.config.sessionId);
+ this.assertStartupIdentity(startupIdentity);
+ await this.primeHistory();
+ this.assertStartupIdentity(startupIdentity);
+ this.startStreams();
+ await this.waitForLiveStream();
+ this.assertStartupIdentity(startupIdentity);
+ if (!this.sessionId) throw new Error("OpenCode v2 session was not initialized");
+ this.ready = true;
+ this.events.emit("runtime_event", {
+ kind: "session_init",
+ sessionId: this.sessionId,
+ } satisfies AdapterEvent);
+ const admission = await this.beginRoot(input);
+ this.assertStartupIdentity(startupIdentity);
+ this.serviceActivated = true;
+ return admission;
+ } catch (error) {
+ this.suppressExit = true;
+ await this.stop({ reason: "failed_start", forceAfterMs: 0 }).catch(() => {});
+ if (error instanceof OpenCodeResetRequiredError) {
+ return { ok: false, reason: "reset_required", error: error.message };
+ }
+ if (error instanceof OpenCodeIncompatibleError) {
+ return { ok: false, reason: "incompatible_configuration", error: error.message };
+ }
+ throw error;
+ }
+ }
+
+ async send(input: LaneSendInput): Promise<LaneAdmission> {
+ if (!this.ready || this.stopping || !this.sessionId || !this.identityMatches()) {
+ return { ok: false, reason: "closed" };
+ }
+ if (input.mode === "idle") {
+ if (this.activeRoot) return { ok: false, reason: "runtime_busy", error: "OpenCode root turn is still active" };
+ return this.beginRoot(input);
+ }
+ if (!this.activeRoot) return { ok: false, reason: "not_ready", error: "OpenCode has no active root turn" };
+ return this.queueAdmission(input.text, "steer", this.newMessageId());
+ }
+
+ async interrupt(input: LaneInterruptInput): Promise<boolean> {
+ const root = this.activeRoot;
+ if (!this.ready || !root || !this.sessionId || this.stopping || !this.identityMatches()) return false;
+ root.generation += 1;
+ root.interrupted = true;
+ root.interruptPending = true;
+ try {
+ await this.requestNoContent(
+ `/api/session/${encodeURIComponent(this.sessionId)}/interrupt`,
+ "POST",
+ undefined,
+ "session interrupt",
+ );
+ root.interruptPending = false;
+ setTimeout(() => this.scheduleEvaluation(), 0).unref?.();
+ return true;
+ } catch (error) {
+ root.interruptPending = false;
+ this.events.emit("runtime_event", {
+ kind: "runtime_diagnostic",
+ severity: "error",
+ source: "opencode.v2",
+ message: `OpenCode interrupt failed (${safeLabel(input.requestId)})`,
+ } satisfies AdapterEvent);
+ void this.stop({ reason: "interrupt_timeout", forceAfterMs: 0 });
+ throw error;
+ }
+ }
+
+ stop(input: LaneStopInput = {}): Promise<void> {
+ this.requestedStopReason ??= input.reason ?? "requested_stop";
+ this.ready = false;
+ this.stopping = true;
+ this.activeRoot = null;
+ if (this.evaluationTimer) clearTimeout(this.evaluationTimer);
+ this.durableAbort?.abort();
+ this.liveAbort?.abort();
+ for (const controller of this.requestControllers) controller.abort();
+ const stopped = new Error("OpenCode service lane stopped");
+ this.durableGate.reject(stopped);
+ this.liveGate.reject(stopped);
+ this.stopPromise ??= this.stopPhysicalOnce(input);
+ return this.stopPromise;
+ }
+
+ private async stopPhysicalOnce(input: LaneStopInput): Promise<void> {
+ let proc = this.process;
+ const pendingSpawn = this.spawnPromise;
+ if (!proc && pendingSpawn) {
+ try {
+ proc = (await pendingSpawn).process;
+ } catch {
+ return;
+ }
+ }
+ if (!proc) return;
+ await this.stopProcessOnce(proc, input);
+ }
+
+ private async startService(): Promise<void> {
+ const attempts = this.options.portAttempts ?? PORT_ATTEMPTS;
+ let lastError: unknown;
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
+ const port = await (this.options.allocatePort ?? allocateLoopbackPort)();
+ this.assertRunning();
+ const generation = ++this.serviceGeneration;
+ this.baseUrl = `http://${HOST}:${port}`;
+ this.stderrBuffer = "";
+ this.serviceActivated = false;
+ this.processStartError = null;
+ this.terminalProcessGeneration = null;
+ try {
+ const spawnPromise = this.factory.spawnService(this.ctx, port, this.password);
+ this.spawnPromise = spawnPromise;
+ const spawned = await spawnPromise;
+ const pid = spawned.process.pid;
+ if (!Number.isInteger(pid) || Number(pid) < 1) {
+ throw new Error("OpenCode service did not expose a process id");
+ }
+ this.process = spawned.process;
+ this.identity = { generation, process: spawned.process, pid: Number(pid) };
+ this.attachProcess(spawned.process, generation);
+ this.assertRunning();
+ await this.waitForCompatibility(generation);
+ this.assertRunning();
+ return;
+ } catch (error) {
+ lastError = error;
+ if (this.stopping) throw error;
+ const retryable = error instanceof OpenCodePortBindError
+ || (error instanceof Error && /EADDRINUSE|address already in use/i.test(error.message));
+ await this.killCandidate();
+ if (!retryable || attempt === attempts) throw error;
+ }
+ }
+ throw lastError instanceof Error ? lastError : new Error("OpenCode service failed to start");
+ }
+
+ private async killCandidate(): Promise<void> {
+ const proc = this.process;
+ this.process = null;
+ this.identity = null;
+ if (!proc) return;
+ await this.stopProcessOnce(proc, { signal: "SIGKILL", forceAfterMs: 0 });
+ }
+
+ private stopProcessOnce(proc: SpawnedProcessHandle, input: LaneStopInput): Promise<void> {
+ const existing = this.processStopPromises.get(proc);
+ if (existing) return existing;
+ const stopping = (async () => {
+ if (proc.pid) {
+ await killProcessTree(proc.pid, { graceMs: input.forceAfterMs ?? SESSION_STOP_GRACE_MS });
+ } else if (!this.isProcessClosed(proc)) {
+ proc.kill(input.signal ?? "SIGTERM");
+ }
+ })();
+ this.processStopPromises.set(proc, stopping);
+ return stopping;
+ }
+
+ private attachProcess(proc: SpawnedProcessHandle, generation: number): void {
+ proc.stdout?.on("data", (chunk) => {
+ if (this.identity?.generation !== generation) return;
+ const text = chunk.toString();
+ this.stdoutBuffer += text;
+ const lines = this.stdoutBuffer.split("\n");
+ this.stdoutBuffer = lines.pop() ?? "";
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ try {
+ this.options.onRawStdoutLine?.(line);
+ } catch {
+ // Observability must not affect the service protocol.
+ }
+ }
+ });
+ proc.stderr?.on("data", (chunk) => {
+ if (this.identity?.generation !== generation) return;
+ const text = chunk.toString();
+ this.stderrBuffer = `${this.stderrBuffer}${text}`.slice(-4096);
+ this.events.emit("stderr", text);
+ });
+ proc.on("error", (error) => {
+ if (this.identity?.generation !== generation || this.suppressExit) return;
+ if (!this.serviceActivated) {
+ this.processStartError = error instanceof Error ? error : new Error("OpenCode service process failed to start");
+ this.abortRuntime(this.processStartError);
+ return;
+ }
+ this.handleActiveProcessError(proc, generation, error);
+ });
+ proc.on("exit", (code, signal) => this.handleProcessExit(proc, generation, code, signal));
+ }
+
+ private handleProcessExit(
+ proc: SpawnedProcessHandle,
+ generation: number,
+ code: number | null,
+ signal: string | null,
+ ): void {
+ if (this.identity?.generation !== generation || this.identity.process !== proc) return;
+ if (this.terminalProcessGeneration === generation) return;
+ this.terminalProcessGeneration = generation;
+ const error = new Error("OpenCode service exited");
+ this.abortRuntime(error);
+ if (this.suppressExit || !this.serviceActivated) return;
+ this.events.emit("exit", {
+ code,
+ signal,
+ reason: this.requestedStopReason ? "requested" : "runtime_exit",
+ } satisfies RuntimeLaneEventMap["exit"]);
+ }
+
+ private handleActiveProcessError(proc: SpawnedProcessHandle, generation: number, value: unknown): void {
+ if (
+ this.identity?.generation !== generation
+ || this.identity.process !== proc
+ || this.terminalProcessGeneration === generation
+ ) return;
+ this.terminalProcessGeneration = generation;
+ const error = value instanceof Error ? value : new Error("OpenCode service process failed");
+ this.abortRuntime(error);
+ void this.stop({ reason: "runtime_error", forceAfterMs: 0 });
+ this.events.emit("error", error);
+ this.events.emit("exit", {
+ code: null,
+ signal: null,
+ reason: "runtime_exit",
+ } satisfies RuntimeLaneEventMap["exit"]);
+ }
+
+ private abortRuntime(error: Error): void {
+ this.ready = false;
+ this.durableAbort?.abort();
+ this.liveAbort?.abort();
+ for (const controller of this.requestControllers) controller.abort();
+ this.durableGate.reject(error);
+ this.liveGate.reject(error);
+ }
+
+ private assertRunning(): void {
+ if (this.stopping) throw new OpenCodeStoppedError("OpenCode service lane stopped during startup");
+ }
+
+ private assertStartupIdentity(identity: ServiceIdentity): void {
+ this.assertRunning();
+ if (!this.isIdentity(identity)) {
+ throw new Error("OpenCode service identity changed during startup");
+ }
+ }
+
+ private async waitForCompatibility(generation: number): Promise<void> {
+ const deadline = Date.now() + (this.options.startTimeoutMs ?? START_TIMEOUT_MS);
+ while (Date.now() < deadline) {
+ if (this.processStartError) throw this.processStartError;
+ if (!this.identity || this.identity.generation !== generation || this.isProcessClosed(this.identity.process)) {
+ if (/EADDRINUSE|address already in use/i.test(this.stderrBuffer)) throw new OpenCodePortBindError("OpenCode service port bind raced");
+ throw new Error("OpenCode service exited before readiness");
+ }
+ try {
+ const healthTimeoutMs = Math.max(1, Math.min(
+ 1_000,
+ deadline - Date.now(),
+ this.options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS,
+ ));
+ const { response, body } = await this.fetchJsonWithTimeout(
+ "/global/health",
+ { method: "GET" },
+ "health",
+ healthTimeoutMs,
+ );
+ if (response.ok) {
+ const health = record(body);
+ if (health?.healthy !== true || health.version !== SUPPORTED_VERSION) {
+ throw new OpenCodeIncompatibleError(`Installed OpenCode service must be version ${SUPPORTED_VERSION}`);
+ }
+ await this.verifyOpenApi();
+ return;
+ }
+ if (response.status === 401) throw new OpenCodeIncompatibleError("OpenCode service rejected session-scoped authentication");
+ } catch (error) {
+ if (error instanceof OpenCodeIncompatibleError) throw error;
+ }
+ await delay(25);
+ }
+ throw new Error("OpenCode service readiness timed out");
+ }
+
+ private async verifyOpenApi(): Promise<void> {
+ const { response, body } = await this.fetchJsonWithTimeout("/doc", { method: "GET" }, "OpenAPI");
+ if (!response.ok) throw new OpenCodeIncompatibleError("Installed OpenCode service does not expose its OpenAPI document");
+ const document = record(body);
+ const paths = record(document?.paths);
+ const required = [
+ "/api/session",
+ "/api/session/active",
+ "/api/session/{sessionID}/prompt",
+ "/api/session/{sessionID}/event",
+ "/api/session/{sessionID}/history",
+ "/api/session/{sessionID}/interrupt",
+ "/api/session/{sessionID}/model",
+ "/api/session/{sessionID}/permission",
+ "/api/session/{sessionID}/permission/{requestID}/reply",
+ "/api/event",
+ ];
+ if (!paths || required.some((path) => !record(paths[path]))) {
+ throw new OpenCodeIncompatibleError("Installed OpenCode service is missing required v2 session capabilities");
+ }
+ }
+
+ private async openSession(resumeId: string | undefined): Promise<void> {
+ const model = parseModelRef(resolveLaunchFieldsOrDefault(this.ctx.config.runtimeConfig).model);
+ if (resumeId) {
+ const { response, body } = await this.fetchJsonWithTimeout(
+ `/api/session/${encodeURIComponent(resumeId)}`,
+ { method: "GET" },
+ "session resume",
+ );
+ if (response.status === 404) {
+ throw new OpenCodeResetRequiredError("OpenCode session cannot be loaded through the v2 service; reset this agent to start a new session");
+ }
+ if (!response.ok) throw new OpenCodeHttpError(response.status, "session resume");
+ const session = record(record(body)?.data);
+ if (session?.id !== resumeId) {
+ throw new OpenCodeResetRequiredError("OpenCode v2 returned a different resumed session; reset this agent before continuing");
+ }
+ this.sessionId = resumeId;
+ if (model) {
+ await this.requestNoContent(
+ `/api/session/${encodeURIComponent(resumeId)}/model`,
+ "POST",
+ { model },
+ "model selection",
+ );
+ }
+ return;
+ }
+ const body: JsonRecord = {
+ location: { directory: this.ctx.workingDirectory },
+ ...(model ? { model } : {}),
+ };
+ const { response, body: responseBody } = await this.fetchJsonWithTimeout("/api/session", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }, "session create");
+ if (!response.ok) throw new OpenCodeHttpError(response.status, "session create");
+ const payload = record(responseBody);
+ const session = record(payload?.data);
+ if (typeof session?.id !== "string" || !/^ses/.test(session.id)) {
+ throw new Error("OpenCode v2 did not return a valid session id");
+ }
+ this.sessionId = session.id;
+ }
+
+ private async primeHistory(): Promise<void> {
+ await this.catchUpHistory(false);
+ }
+
+ private startStreams(): void {
+ const identity = this.identity;
+ if (!identity || !this.sessionId) throw new Error("OpenCode service streams started before session initialization");
+ this.durableTask = this.runDurableStream(identity).catch((error) => this.streamFailure("durable", error));
+ this.liveTask = this.runLiveStream(identity).catch((error) => this.streamFailure("live", error));
+ }
+
+ private async runDurableStream(identity: ServiceIdentity): Promise<void> {
+ while (!this.stopping && this.isIdentity(identity)) {
+ this.durableGap = true;
+ const gate = this.durableGate;
+ const controller = new AbortController();
+ this.durableAbort = controller;
+ try {
+ const path = `/api/session/${encodeURIComponent(this.sessionId!)}/event?after=${this.lastDurableSeq}`;
+ const response = await this.openStream(path, controller, "durable event stream");
+ await this.catchUpHistory(true);
+ if (!this.isIdentity(identity)) return;
+ this.durableGap = false;
+ gate.resolve();
+ this.scheduleEvaluation();
+ await this.consumeSse(response, async (value) => { await this.handleDurableEvent(value, true); });
+ if (!this.stopping) this.diagnostic("warning", "OpenCode durable event stream disconnected; replaying from its cursor");
+ } catch (error) {
+ if (this.stopping || !this.isIdentity(identity) || controller.signal.aborted) return;
+ if (error instanceof OpenCodeProtocolError || (error instanceof OpenCodeHttpError && error.status < 500)) {
+ this.protocolFailure("OpenCode durable event stream violated the v2 protocol", error);
+ return;
+ }
+ this.diagnostic("warning", "OpenCode durable event stream reconnecting after transport failure");
+ }
+ this.durableGap = true;
+ if (this.durableGate === gate) {
+ this.durableGate = makeGate();
+ // A pre-open failure leaves the old gate unresolved. Wake its waiters
+ // so they can observe the generation change and bind to the retry.
+ gate.resolve();
+ }
+ this.events.emit("runtime_event", {
+ kind: "runtime_metric",
+ name: "sse_reconnect",
+ increment: 1,
+ } satisfies AdapterEvent);
+ await delay(this.options.reconnectDelayMs ?? RECONNECT_DELAY_MS);
+ }
+ }
+
+ private async runLiveStream(identity: ServiceIdentity): Promise<void> {
+ while (!this.stopping && this.isIdentity(identity)) {
+ const gate = this.liveGate;
+ const controller = new AbortController();
+ this.liveAbort = controller;
+ try {
+ const response = await this.openStream("/api/event", controller, "live event stream");
+ await this.recoverPendingPermissions();
+ if (!this.isIdentity(identity)) return;
+ gate.resolve();
+ await this.consumeSse(response, (value) => this.handleLiveEvent(value));
+ if (!this.stopping) this.diagnostic("warning", "OpenCode live event stream disconnected; reconnecting");
+ } catch (error) {
+ if (this.stopping || !this.isIdentity(identity) || controller.signal.aborted) return;
+ if (error instanceof OpenCodeProtocolError || (error instanceof OpenCodeHttpError && error.status < 500)) {
+ this.protocolFailure("OpenCode live event stream violated the v2 protocol", error);
+ return;
+ }
+ this.diagnostic("warning", "OpenCode live event stream reconnecting after transport failure");
+ }
+ if (this.liveGate === gate) {
+ this.liveGate = makeGate();
+ gate.resolve();
+ }
+ this.events.emit("runtime_event", {
+ kind: "runtime_metric",
+ name: "sse_reconnect",
+ increment: 1,
+ } satisfies AdapterEvent);
+ await delay(this.options.reconnectDelayMs ?? RECONNECT_DELAY_MS);
+ }
+ }
+
+ private streamFailure(kind: "durable" | "live", error: unknown): void {
+ if (this.stopping) return;
+ this.protocolFailure(`OpenCode ${kind} stream stopped unexpectedly`, error);
+ }
+
+ private async openStream(path: string, lifecycle: AbortController, operation: string): Promise<Response> {
+ const deadline = new AbortController();
+ const timeout = setTimeout(() => deadline.abort(), this.options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS);
+ timeout.unref?.();
+ try {
+ const response = await this.fetchFn(`${this.baseUrl}${path}`, {
+ method: "GET",
+ headers: this.headers({ accept: "text/event-stream" }),
+ signal: AbortSignal.any([lifecycle.signal, deadline.signal]),
+ });
+ if (!response.ok || !response.body) throw new OpenCodeHttpError(response.status, operation);
+ return response;
+ } finally {
+ clearTimeout(timeout);
+ }
+ }
+
+ private async consumeSse(response: Response, consume: (value: unknown) => Promise<void>): Promise<void> {
+ const reader = response.body!.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ while (!this.stopping) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true }).replaceAll("\r\n", "\n");
+ let boundary: number;
+ while ((boundary = buffer.indexOf("\n\n")) >= 0) {
+ const block = buffer.slice(0, boundary);
+ buffer = buffer.slice(boundary + 2);
+ const data = block.split("\n")
+ .filter((line) => line.startsWith("data:"))
+ .map((line) => line.slice(5).trimStart())
+ .join("\n");
+ if (!data) continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(data);
+ } catch {
+ throw new OpenCodeProtocolError("OpenCode SSE emitted malformed JSON");
+ }
+ await consume(parsed);
+ }
+ }
+ }
+
+ private catchUpHistory(project: boolean): Promise<void> {
+ const run = this.historyTail.then(async () => {
+ if (!this.sessionId || this.stopping) return;
+ let hasMore = true;
+ let historyCursor = this.lastDurableSeq;
+ while (hasMore && !this.stopping) {
+ const { response, body: responseBody } = await this.fetchJsonWithTimeout(
+ `/api/session/${encodeURIComponent(this.sessionId)}/history?after=${historyCursor}&limit=${HISTORY_PAGE_LIMIT}`,
+ { method: "GET" },
+ "session history",
+ );
+ if (!response.ok) throw new OpenCodeHttpError(response.status, "session history");
+ const body = record(responseBody);
+ if (!Array.isArray(body?.data) || typeof body.hasMore !== "boolean") {
+ throw new OpenCodeProtocolError("OpenCode session history returned an invalid page");
+ }
+ const before = historyCursor;
+ for (const event of body.data) {
+ historyCursor = Math.max(historyCursor, await this.handleDurableEvent(event, project));
+ }
+ hasMore = body.hasMore;
+ if (hasMore && historyCursor === before) {
+ throw new OpenCodeProtocolError("OpenCode session history cursor did not advance");
+ }
+ }
+ });
+ this.historyTail = run.catch(() => {});
+ return run;
+ }
+
+ private async handleDurableEvent(value: unknown, project: boolean): Promise<number> {
+ const event = record(value);
+ const durable = record(event?.durable);
+ const data = record(event?.data);
+ if (
+ !event
+ || typeof event.id !== "string"
+ || typeof event.type !== "string"
+ || !durable
+ || durable.aggregateID !== this.sessionId
+ || !Number.isInteger(durable.seq)
+ || Number(durable.seq) < 0
+ || data?.sessionID !== this.sessionId
+ ) {
+ throw new OpenCodeProtocolError("OpenCode session stream emitted an invalid durable event");
+ }
+ const seq = Number(durable.seq);
+ const priorSeq = this.durableSeqById.get(event.id);
+ if (priorSeq !== undefined) {
+ if (priorSeq !== seq) {
+ throw new OpenCodeProtocolError("OpenCode replayed a durable event id at a different sequence");
+ }
+ return seq;
+ }
+ const priorId = this.durableIdBySeq.get(seq);
+ if (priorId !== undefined) {
+ throw new OpenCodeProtocolError("OpenCode emitted different durable event ids at the same sequence");
+ }
+ if (seq < this.lastDurableSeq) {
+ throw new OpenCodeProtocolError("OpenCode emitted an unseen durable event below the replay cursor");
+ }
+ this.durableSeqById.set(event.id, seq);
+ this.durableIdBySeq.set(seq, event.id);
+ const root = this.activeRoot;
+ this.lastDurableSeq = Math.max(this.lastDurableSeq, seq);
+ if (event.type === "session.next.prompt.admitted") {
+ const messageId = data.messageID;
+ if (root && typeof messageId === "string") {
+ root.durableAdmissions.set(messageId, seq);
+ const expected = root.frontier.get(messageId);
+ if (expected !== undefined) {
+ if (expected !== seq) throw new OpenCodeProtocolError("OpenCode durable prompt admission sequence did not match its receipt");
+ root.observedAdmissions.add(messageId);
+ }
+ }
+ }
+ if (!project || !root || seq <= root.baselineSeq) {
+ this.scheduleEvaluation();
+ return seq;
+ }
+ switch (event.type) {
+ case "session.next.step.started":
+ this.events.emit("runtime_event", { kind: "thinking", text: "" } satisfies AdapterEvent);
+ break;
+ case "session.next.text.ended":
+ if (typeof data.text === "string" && data.text.length > 0) {
+ this.events.emit("runtime_event", { kind: "text", text: data.text } satisfies AdapterEvent);
+ }
+ break;
+ case "session.next.reasoning.ended":
+ if (typeof data.text === "string" && data.text.length > 0) {
+ this.events.emit("runtime_event", { kind: "thinking", text: data.text } satisfies AdapterEvent);
+ }
+ break;
+ case "session.next.tool.called":
+ if (typeof data.callID === "string") {
+ const name = typeof data.tool === "string" ? data.tool : "OpenCode tool";
+ this.toolNames.set(data.callID, name);
+ this.events.emit("runtime_event", { kind: "tool_call", name, input: data.input } satisfies AdapterEvent);
+ }
+ break;
+ case "session.next.tool.success":
+ case "session.next.tool.failed":
+ if (typeof data.callID === "string") {
+ const name = this.toolNames.get(data.callID) ?? "OpenCode tool";
+ this.toolNames.delete(data.callID);
+ this.events.emit("runtime_event", { kind: "tool_output", name } satisfies AdapterEvent);
+ }
+ break;
+ case "session.next.compaction.started":
+ this.events.emit("runtime_event", { kind: "compaction_started" } satisfies AdapterEvent);
+ break;
+ case "session.next.compaction.ended":
+ this.events.emit("runtime_event", { kind: "compaction_finished" } satisfies AdapterEvent);
+ break;
+ case "session.next.step.ended": {
+ if (typeof data.finish !== "string") {
+ throw new OpenCodeProtocolError("OpenCode step outcome omitted its finish reason");
+ }
+ if (data.finish !== "tool-calls") {
+ const successful = data.finish === "stop" || data.finish === "length" || data.finish === "content-filter";
+ root.outcomes.push({
+ seq,
+ ok: successful,
+ ...(!successful ? { message: "OpenCode reported an unsupported final step outcome" } : {}),
+ });
+ }
+ const tokens = record(data.tokens);
+ if (tokens) {
+ this.events.emit("runtime_event", {
+ kind: "telemetry",
+ name: "token_usage",
+ source: "opencode.v2",
+ attrs: tokens,
+ } satisfies AdapterEvent);
+ }
+ break;
+ }
+ case "session.next.step.failed":
+ root.outcomes.push({ seq, ok: false, message: messageFromError(data.error) });
+ break;
+ default:
+ break;
+ }
+ this.scheduleEvaluation();
+ return seq;
+ }
+
+ private async handleLiveEvent(value: unknown): Promise<void> {
+ const event = record(value);
+ const data = record(event?.data);
+ if (event?.type !== "permission.v2.asked" || data?.sessionID !== this.sessionId) return;
+ if (typeof data.id !== "string" || !/^per/.test(data.id)) {
+ throw new OpenCodeProtocolError("OpenCode emitted a malformed permission request");
+ }
+ await this.replyPermission(data.id);
+ }
+
+ private async recoverPendingPermissions(): Promise<void> {
+ if (!this.sessionId) return;
+ const { response, body: responseBody } = await this.fetchJsonWithTimeout(
+ `/api/session/${encodeURIComponent(this.sessionId)}/permission`,
+ { method: "GET" },
+ "permission list",
+ );
+ if (!response.ok) throw new OpenCodeHttpError(response.status, "permission list");
+ const body = record(responseBody);
+ if (!Array.isArray(body?.data)) throw new OpenCodeProtocolError("OpenCode permission list returned invalid data");
+ for (const item of body.data) {
+ const permission = record(item);
+ if (permission?.sessionID === this.sessionId && typeof permission.id === "string") {
+ await this.replyPermission(permission.id);
+ }
+ }
+ }
+
+ private async replyPermission(requestId: string): Promise<void> {
+ if (this.handledPermissions.has(requestId)) return;
+ const existing = this.permissionFlights.get(requestId);
+ if (existing) return existing;
+ const flight = this.requestNoContent(
+ `/api/session/${encodeURIComponent(this.sessionId!)}/permission/${encodeURIComponent(requestId)}/reply`,
+ "POST",
+ { reply: "once" },
+ "permission reply",
+ )
+ .catch((error) => {
+ if (!(error instanceof OpenCodeHttpError) || error.status !== 404) throw error;
+ })
+ .then(() => { this.handledPermissions.add(requestId); })
+ .finally(() => { this.permissionFlights.delete(requestId); });
+ this.permissionFlights.set(requestId, flight);
+ return flight;
+ }
+
+ private async beginRoot(input: LaneStartInput): Promise<LaneAdmission> {
+ const receipt = input.terminalOwner?.startsWith("msg_") ? input.terminalOwner : this.newMessageId();
+ this.activeRoot = {
+ receipt,
+ baselineSeq: this.lastDurableSeq,
+ frontier: new Map(),
+ durableAdmissions: new Map(),
+ observedAdmissions: new Set(),
+ outcomes: [],
+ generation: 0,
+ pendingAdmissions: 0,
+ interrupted: false,
+ interruptPending: false,
+ };
+ try {
+ return await this.queueAdmission(input.text, "queue", receipt);
+ } catch (error) {
+ this.activeRoot = null;
+ throw error;
+ }
+ }
+
+ private queueAdmission(text: string, delivery: "queue" | "steer", messageId: string): Promise<LaneAdmission> {
+ const root = this.activeRoot;
+ if (!root) return Promise.resolve({ ok: false, reason: "not_ready" });
+ root.generation += 1;
+ root.pendingAdmissions += 1;
+ const run = this.admissionTail.then(async (): Promise<LaneAdmission> => {
+ if (!this.ready || this.stopping || this.activeRoot !== root || !this.sessionId || !this.identityMatches()) {
+ return { ok: false, reason: "closed" };
+ }
+ await this.waitForLiveStream();
+ // OpenCode 1.17.20 does not flush the durable SSE response headers until
+ // the first durable event. The first prompt admission creates that event,
+ // so waiting for the durable fetch here deadlocks startup. History closes
+ // the pre-admission gap; after this POST releases the stream, the normal
+ // durable cursor/frontier barrier remains the sole terminal authority.
+ if (this.durableGap && this.durableBootstrapAdmissionUsed) await this.waitForStreams();
+ this.durableBootstrapAdmissionUsed = true;
+ if (this.durableGap) await this.catchUpHistory(true);
+ const { response, body: responseBody } = await this.fetchJsonWithTimeout(
+ `/api/session/${encodeURIComponent(this.sessionId)}/prompt`,
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ id: messageId, prompt: { text }, delivery, resume: true }),
+ },
+ "prompt admission",
+ );
+ if (!response.ok) throw new OpenCodeHttpError(response.status, "prompt admission");
+ const body = record(responseBody);
+ const admitted = record(body?.data);
+ if (
+ admitted?.id !== messageId
+ || admitted.sessionID !== this.sessionId
+ || admitted.delivery !== delivery
+ || !Number.isInteger(admitted.admittedSeq)
+ || Number(admitted.admittedSeq) < 0
+ ) {
+ throw new OpenCodeProtocolError("OpenCode prompt admission returned an invalid receipt");
+ }
+ root.frontier.set(messageId, Number(admitted.admittedSeq));
+ const durableSeq = root.durableAdmissions.get(messageId);
+ if (durableSeq !== undefined) {
+ if (durableSeq !== Number(admitted.admittedSeq)) {
+ throw new OpenCodeProtocolError("OpenCode durable prompt admission sequence did not match its receipt");
+ }
+ root.observedAdmissions.add(messageId);
+ } else {
+ void this.catchUpHistory(true).catch((error) => {
+ if (!this.stopping && this.activeRoot === root) {
+ if (
+ error instanceof OpenCodeProtocolError
+ || (error instanceof OpenCodeHttpError && error.status < 500)
+ ) {
+ this.protocolFailure("OpenCode session history violated the v2 protocol", error);
+ return;
+ }
+ this.diagnostic("warning", "OpenCode durable admission catch-up failed; waiting for SSE replay");
+ }
+ });
+ }
+ return { ok: true, acceptedAs: delivery === "steer" ? "steer" : "prompt", receipt: messageId };
+ }).catch((error) => {
+ if (!this.stopping && this.activeRoot === root) {
+ this.protocolFailure("OpenCode prompt admission did not produce a valid durable receipt", error);
+ }
+ throw error;
+ }).finally(() => {
+ root.pendingAdmissions -= 1;
+ this.scheduleEvaluation();
+ });
+ this.admissionTail = run.then(() => {}, () => {});
+ return run;
+ }
+
+ private scheduleEvaluation(delayMs = 0): void {
+ if (!this.activeRoot || this.stopping) return;
+ if (this.evaluating) {
+ this.reevaluate = true;
+ this.reevaluateDelayMs = this.reevaluateDelayMs === undefined
+ ? delayMs
+ : Math.min(this.reevaluateDelayMs, delayMs);
+ return;
+ }
+ if (this.evaluationTimer) return;
+ this.evaluationTimer = setTimeout(() => {
+ this.evaluationTimer = undefined;
+ void this.evaluateTerminal();
+ }, delayMs);
+ this.evaluationTimer.unref?.();
+ }
+
+ private async evaluateTerminal(): Promise<void> {
+ const root = this.activeRoot;
+ const identity = this.identity;
+ if (!root || !identity || this.stopping || this.evaluating) return;
+ if (
+ root.pendingAdmissions > 0
+ || root.interruptPending
+ || this.durableGap
+ || root.frontier.size === 0
+ || root.observedAdmissions.size !== root.frontier.size
+ ) return;
+ const maxAdmission = Math.max(...root.frontier.values());
+ if (this.lastDurableSeq < maxAdmission) return;
+ this.evaluating = true;
+ const generation = root.generation;
+ try {
+ const { response, body: responseBody } = await this.fetchJsonWithTimeout(
+ "/api/session/active",
+ { method: "GET" },
+ "active session query",
+ );
+ if (!response.ok) throw new OpenCodeHttpError(response.status, "active session query");
+ const body = record(responseBody);
+ const active = record(body?.data);
+ if (!active) throw new OpenCodeProtocolError("OpenCode active session query returned invalid data");
+ if (!this.barrierStillCurrent(root, identity, generation)) return;
+ if (active[this.sessionId!] !== undefined) {
+ this.scheduleEvaluation(this.options.activePollMs ?? ACTIVE_POLL_MS);
+ return;
+ }
+ await this.catchUpHistory(true);
+ if (!this.barrierStillCurrent(root, identity, generation) || this.durableGap) return;
+ if (
+ root.observedAdmissions.size !== root.frontier.size
+ || this.lastDurableSeq < maxAdmission
+ ) return;
+ const outcome = root.outcomes
+ .filter((item) => item.seq > maxAdmission)
+ .sort((left, right) => left.seq - right.seq)
+ .at(-1);
+ if (!root.interrupted && !outcome) {
+ this.settleRoot(root, false, "OpenCode drain settled without a durable turn outcome");
+ return;
+ }
+ if (outcome && !outcome.ok) {
+ this.settleRoot(root, false, outcome.message ?? "OpenCode turn failed");
+ return;
+ }
+ this.settleRoot(root, true);
+ } catch (error) {
+ if (
+ error instanceof OpenCodeProtocolError
+ || (error instanceof OpenCodeHttpError && error.status < 500)
+ ) {
+ this.protocolFailure("OpenCode active barrier violated the v2 protocol", error);
+ return;
+ }
+ if (!this.stopping && this.activeRoot === root && this.isIdentity(identity)) {
+ this.diagnostic("warning", "OpenCode active barrier query failed; retrying without settling the turn");
+ this.scheduleEvaluation(this.options.activePollMs ?? ACTIVE_POLL_MS);
+ }
+ } finally {
+ this.evaluating = false;
+ if (this.reevaluate) {
+ this.reevaluate = false;
+ const delayMs = this.reevaluateDelayMs ?? 0;
+ this.reevaluateDelayMs = undefined;
+ this.scheduleEvaluation(delayMs);
+ }
+ }
+ }
+
+ private barrierStillCurrent(root: ActiveRoot, identity: ServiceIdentity, generation: number): boolean {
+ return this.activeRoot === root
+ && root.generation === generation
+ && root.pendingAdmissions === 0
+ && !root.interruptPending
+ && this.isIdentity(identity)
+ && this.identityMatches();
+ }
+
+ private settleRoot(root: ActiveRoot, success: boolean, message?: string): void {
+ if (this.activeRoot !== root) return;
+ this.activeRoot = null;
+ this.toolNames.clear();
+ if (!success) {
+ this.events.emit("runtime_event", {
+ kind: "error",
+ message: message ?? "OpenCode turn failed",
+ } satisfies AdapterEvent);
+ }
+ this.events.emit("runtime_event", {
+ kind: "turn_end",
+ sessionId: this.sessionId ?? undefined,
+ turnOwner: root.receipt,
+ } satisfies AdapterEvent);
+ }
+
+ private async requestNoContent(
+ path: string,
+ method: "POST",
+ body: JsonRecord | undefined,
+ operation: string,
+ ): Promise<void> {
+ const response = await this.fetchWithTimeout(path, {
+ method,
+ ...(body ? {
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ } : {}),
+ }, operation);
+ if (!response.ok) throw new OpenCodeHttpError(response.status, operation);
+ }
+
+ private async fetchWithTimeout(
+ path: string,
+ init: RequestInit,
+ operation: string,
+ timeoutMs = this.options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS,
+ ): Promise<Response> {
+ if (this.stopping) throw new Error("OpenCode service lane is stopping");
+ const controller = new AbortController();
+ this.requestControllers.add(controller);
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ timer.unref?.();
+ try {
+ return await this.fetchFn(`${this.baseUrl}${path}`, {
+ ...init,
+ headers: this.headers(init.headers),
+ signal: controller.signal,
+ });
+ } catch (error) {
+ throw error instanceof Error ? error : new Error(`OpenCode ${operation} request failed`);
+ } finally {
+ clearTimeout(timer);
+ this.requestControllers.delete(controller);
+ }
+ }
+
+ private async fetchJsonWithTimeout(
+ path: string,
+ init: RequestInit,
+ operation: string,
+ timeoutMs = this.options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS,
+ ): Promise<{ response: Response; body: unknown }> {
+ if (this.stopping) throw new OpenCodeStoppedError("OpenCode service lane is stopping");
+ const controller = new AbortController();
+ this.requestControllers.add(controller);
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, timeoutMs);
+ timer.unref?.();
+ try {
+ const response = await this.fetchFn(`${this.baseUrl}${path}`, {
+ ...init,
+ headers: this.headers(init.headers),
+ signal: controller.signal,
+ });
+ if (!response.ok) return { response, body: undefined };
+ try {
+ return { response, body: await response.json() };
+ } catch (error) {
+ if (timedOut) {
+ throw new Error(`OpenCode ${operation} response timed out`);
+ }
+ if (controller.signal.aborted) throw error;
+ throw new OpenCodeProtocolError(`OpenCode ${operation} returned invalid JSON`);
+ }
+ } catch (error) {
+ throw error instanceof Error ? error : new Error(`OpenCode ${operation} request failed`);
+ } finally {
+ clearTimeout(timer);
+ this.requestControllers.delete(controller);
+ }
+ }
+
+ private headers(input?: HeadersInit): Headers {
+ const headers = new Headers(input);
+ headers.set("authorization", `Basic ${Buffer.from(`opencode:${this.password}`).toString("base64")}`);
+ return headers;
+ }
+
+ private newMessageId(): string {
+ return `msg_${randomBytes(16).toString("hex")}`;
+ }
+
+ private diagnostic(severity: "warning" | "error", message: string): void {
+ this.events.emit("runtime_event", {
+ kind: "runtime_diagnostic",
+ severity,
+ source: "opencode.v2",
+ message,
+ } satisfies AdapterEvent);
+ }
+
+ private protocolFailure(message: string, _cause?: unknown): void {
+ if (this.stopping) return;
+ void this.stop({ reason: "protocol_error", forceAfterMs: 0 });
+ this.events.emit("error", new Error(message));
+ }
+
+ private identityMatches(): boolean {
+ const identity = this.identity;
+ const matches = !!identity
+ && identity.process === this.process
+ && identity.process.pid === identity.pid
+ && !this.isProcessClosed(identity.process);
+ if (
+ !matches
+ && identity
+ && identity.process === this.process
+ && identity.process.pid !== identity.pid
+ && this.ready
+ && !this.stopping
+ ) {
+ this.failPidIdentity();
+ }
+ return matches;
+ }
+
+ private isIdentity(identity: ServiceIdentity): boolean {
+ return this.identity === identity && this.identityMatches();
+ }
+
+ private isProcessClosed(proc: SpawnedProcessHandle): boolean {
+ return proc.exitCode !== null || proc.signalCode !== null;
+ }
+
+ private async waitForLiveStream(): Promise<void> {
+ while (!this.stopping) {
+ const live = this.liveGate;
+ await live.promise;
+ if (live === this.liveGate) return;
+ }
+ throw new Error("OpenCode service lane stopped before stream recovery");
+ }
+
+ private async waitForStreams(): Promise<void> {
+ while (!this.stopping) {
+ const durable = this.durableGate;
+ const live = this.liveGate;
+ await Promise.all([durable.promise, live.promise]);
+ if (!this.durableGap && durable === this.durableGate && live === this.liveGate) return;
+ }
+ throw new Error("OpenCode service lane stopped before stream recovery");
+ }
+
+ private failPidIdentity(): void {
+ if (this.identityFailed) return;
+ this.identityFailed = true;
+ this.ready = false;
+ this.events.emit("exit", {
+ code: null,
+ signal: null,
+ reason: "runtime_exit",
+ } satisfies RuntimeLaneEventMap["exit"]);
+ void this.stop({ reason: "service_identity_changed", forceAfterMs: 0 });
+ }
+}
diff --git a/src/daemon/agent-driver/src/adapters/pi/index.test.ts b/src/daemon/agent-driver/src/adapters/pi/index.test.ts
new file mode 100644
index 000000000..bf93e4707
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/pi/index.test.ts
@@ -0,0 +1,354 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import {
+ PiDriver,
+ PI_IGNORED_EVENT_TYPES,
+ mapPiSdkEvent,
+ resolvePiSdkVersionFromPath,
+ resolvePiSdkPackageDir,
+ findPiSessionFile,
+} from "./index.js";
+import { CANONICAL_FILE } from "../../internal/agentFile.js";
+import { capabilitiesFor, createAgentDriverRegistry } from "../../registry.js";
+import { createAgentDriverSdkWithRegistry } from "../../sdk.js";
+import { createFakeAgentDriverHost } from "../../testing/fake-host.js";
+import type { BuiltinBackendSpecs } from "../../contract.js";
+import type { AdapterLaunchContext } from "../../internal/adapter.js";
+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
+
+let tmpDir: string;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-driver-test-"));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+function baseCtx(overrides: Partial<AdapterLaunchContext> = {}): AdapterLaunchContext {
+ return fakeLaunchContext("pi", tmpDir, {
+ standingPrompt: "You are Pi.",
+ prompt: "hello",
+ ...overrides,
+ });
+}
+
+function fakeDeps() {
+ const session = {
+ prompt: vi.fn().mockResolvedValue(undefined),
+ steer: vi.fn(),
+ abort: vi.fn(),
+ dispose: vi.fn(),
+ isStreaming: false,
+ subscribe: vi.fn(),
+ };
+ const createAgentSession = vi.fn().mockResolvedValue({ session, sessionId: "sess_1" });
+ const buildSpawnEnv = vi.fn().mockResolvedValue({});
+ return { buildSpawnEnv, createAgentSession, session };
+}
+
+describe("PiDriver.openLane — AGENTS.md packing", () => {
+ it("exposes SDK-only parser and encoder no-ops", () => {
+ const driver = new PiDriver(() => fakeDeps());
+ expect(driver.normalizeLine()).toEqual([]);
+ expect(driver.encodeMessage()).toBeNull();
+ });
+
+ it("does not write AGENTS.md itself — the logical-session core is the single packing point", async () => {
+ const deps = fakeDeps();
+ const driver = new PiDriver(() => deps);
+
+ await driver.openLane(baseCtx());
+
+ // The adapter does not duplicate the core's instruction materialization.
+ expect(fs.existsSync(path.join(tmpDir, CANONICAL_FILE))).toBe(false);
+
+ const sessionOpts = deps.createAgentSession.mock.calls[0][0];
+ expect(sessionOpts).not.toHaveProperty("standingPrompt");
+ });
+});
+
+describe("PiDriver.openLane — does not fire the initial prompt itself", () => {
+ it("returns without calling session.prompt — the caller (logical session) sends the first turn", async () => {
+ const deps = fakeDeps();
+ const driver = new PiDriver(() => deps);
+
+ const runtimeSession = await driver.openLane(baseCtx());
+
+ expect(deps.session.prompt).not.toHaveBeenCalled();
+ expect(runtimeSession.currentSessionId).toBe("sess_1");
+ });
+
+ it("wires session.subscribe before returning, so events fired by a later prompt() call are not lost", async () => {
+ const deps = fakeDeps();
+ const driver = new PiDriver(() => deps);
+
+ const runtimeSession = await driver.openLane(baseCtx());
+ const received: unknown[] = [];
+ runtimeSession.on("runtime_event", (e) => received.push(e));
+
+ // Simulate the SDK emitting a text_delta while handling a prompt sent
+ // later, via the subscribe callback deps.session.subscribe captured.
+ const subscribeCb = deps.session.subscribe.mock.calls[0][0];
+ subscribeCb({ type: "message_update", delta: { type: "text_delta", delta: "hi" } });
+
+ expect(received).toEqual([
+ { kind: "session_init", sessionId: "sess_1" },
+ { kind: "text", text: "hi" },
+ ]);
+ });
+
+ it("binds terminal ownership to each prompt promise and ignores duplicate content-identical agent_end events", async () => {
+ const deps = fakeDeps();
+ const prompts: Array<{ resolve: () => void; promise: Promise<void> }> = [];
+ deps.session.prompt.mockImplementation(() => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => { resolve = done; });
+ prompts.push({ resolve, promise });
+ return promise;
+ });
+ const driver = new PiDriver(() => deps);
+ const runtimeSession = await driver.openLane(baseCtx());
+ const received: any[] = [];
+ runtimeSession.on("runtime_event", (event) => received.push(event));
+ const notify = deps.session.subscribe.mock.calls[0][0];
+
+ const firstOwner = driver.beginTurn();
+ await runtimeSession.send({ text: "same", mode: "idle", terminalOwner: firstOwner });
+ notify({ type: "agent_end", messages: [] });
+ prompts[0]!.resolve();
+ await prompts[0]!.promise;
+ await Promise.resolve();
+ const secondOwner = driver.beginTurn();
+ await runtimeSession.send({ text: "same", mode: "idle", terminalOwner: secondOwner });
+ notify({ type: "agent_end", messages: [] });
+ notify({ type: "agent_end", messages: [] });
+ prompts[1]!.resolve();
+ await prompts[1]!.promise;
+ await Promise.resolve();
+
+ expect(received.filter((event) => event.kind === "turn_end").map((event) => event.turnOwner)).toEqual([
+ firstOwner,
+ secondOwner,
+ ]);
+ expect(deps.session.prompt.mock.calls).toEqual([["same"], ["same"]]);
+ });
+});
+
+describe("PiDriver persistent RuntimeLane contract", () => {
+ it("keeps one vendor session across ten owned prompts, busy steer, interrupt, and stop", async () => {
+ const deps = fakeDeps();
+ const promptResolutions: Array<() => void> = [];
+ deps.session.prompt.mockImplementation(() => new Promise<void>((resolve) => {
+ promptResolutions.push(resolve);
+ }));
+ const driver = new PiDriver(() => deps);
+ const beginTurn = vi.spyOn(driver, "beginTurn");
+ const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
+ id: "pi",
+ contractVersion: 1,
+ capabilities: capabilitiesFor("pi"),
+ createAdapter: () => driver,
+ }]);
+ const sdk = createAgentDriverSdkWithRegistry({
+ registry,
+ host: createFakeAgentDriverHost(),
+ });
+ const opened = await sdk.open({
+ backend: "pi",
+ config: { model: { kind: "default" }, provider: { kind: "default" } },
+ launch: {
+ workingDirectory: tmpDir,
+ instructions: { format: "markdown", content: "You are Pi." },
+ launchId: "pi-ten-turns",
+ },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+
+ const observed: Array<{ readonly type: string; readonly commandIds?: readonly string[] }> = [];
+ const collecting = (async () => {
+ for await (const event of opened.session.events) observed.push(event);
+ })();
+ const completedCount = () => observed.filter((event) => event.type === "turn_completed").length;
+
+ expect(await opened.session.start({ id: "root-1", kind: "user", text: "same prompt" }))
+ .toMatchObject({ status: "accepted" });
+ await vi.waitFor(() => expect(deps.session.prompt).toHaveBeenCalledTimes(1));
+ const notify = deps.session.subscribe.mock.calls[0]![0];
+
+ expect(await opened.session.interrupt({ requestId: "not-streaming", reason: "test" }))
+ .toEqual({ status: "not_running" });
+ expect(deps.session.abort).not.toHaveBeenCalled();
+
+ deps.session.isStreaming = true;
+ expect(await opened.session.send({ id: "busy", kind: "user", text: "busy steer" }))
+ .toMatchObject({ status: "accepted", delivery: "steer" });
+ expect(deps.session.steer).toHaveBeenCalledWith("busy steer");
+ expect(await opened.session.interrupt({ requestId: "streaming", reason: "test" }))
+ .toMatchObject({ status: "accepted", requestId: "streaming" });
+ expect(deps.session.abort).toHaveBeenCalledTimes(1);
+ deps.session.isStreaming = false;
+
+ for (let turn = 1; turn <= 10; turn += 1) {
+ if (turn > 1) {
+ expect(await opened.session.send({ id: `root-${turn}`, kind: "user", text: "same prompt" }))
+ .toMatchObject({ status: "accepted" });
+ await vi.waitFor(() => expect(deps.session.prompt).toHaveBeenCalledTimes(turn));
+ }
+ notify({ type: "agent_end", messages: [] });
+ notify({ type: "agent_end", messages: [] });
+ await Promise.resolve();
+ expect(completedCount()).toBe(turn - 1);
+ promptResolutions[turn - 1]!();
+ await vi.waitFor(() => expect(completedCount()).toBe(turn));
+ }
+
+ expect(deps.createAgentSession).toHaveBeenCalledTimes(1);
+ expect(deps.session.prompt.mock.calls).toEqual(Array.from({ length: 10 }, () => ["same prompt"]));
+ expect(deps.session.steer).toHaveBeenCalledTimes(1);
+ expect(beginTurn).toHaveBeenCalledTimes(10);
+ const owners = beginTurn.mock.results.map((result) => result.value);
+ expect(new Set(owners).size).toBe(10);
+ expect(observed.flatMap((event) => event.type === "turn_completed" ? [event.commandIds] : []))
+ .toEqual([
+ ["root-1", "busy"],
+ ...Array.from({ length: 9 }, (_, index) => [`root-${index + 2}`]),
+ ]);
+
+ expect(await opened.session.stop({ reason: "shutdown", forceAfterMs: 25 }))
+ .toMatchObject({ status: "accepted" });
+ await opened.session.closed;
+ await collecting;
+ expect(deps.session.dispose).toHaveBeenCalledTimes(1);
+ expect(deps.session.abort).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("Pi SDK event-family coverage", () => {
+ it("maps every supported family and explicitly no-ops every known unsupported family", () => {
+ const state = { sawTextDelta: false };
+ const supported = [
+ { input: { type: "message_update", delta: { type: "thinking_delta", delta: "t" } }, kind: "thinking" },
+ { input: { type: "message_update", delta: { type: "text_delta", delta: "x" } }, kind: "text" },
+ { input: { type: "message_update", delta: { type: "error", message: "e" } }, kind: "error" },
+ { input: { type: "tool_execution_start", toolName: "bash", args: {} }, kind: "tool_call" },
+ { input: { type: "tool_execution_end", toolName: "bash" }, kind: "tool_output" },
+ { input: { type: "compaction_start" }, kind: "compaction_started" },
+ { input: { type: "compaction_end" }, kind: "compaction_finished" },
+ ];
+ for (const item of supported) {
+ expect(mapPiSdkEvent(item.input, "session", state)[0]?.kind).toBe(item.kind);
+ }
+ for (const type of PI_IGNORED_EVENT_TYPES) {
+ expect(mapPiSdkEvent({ type }, "session", state)).toEqual([]);
+ }
+ });
+});
+
+describe("findPiSessionFile", () => {
+ it("matches an entry ending in `_${sessionId}.jsonl`", () => {
+ const sessionDir = path.join(tmpDir, "sessions");
+ fs.mkdirSync(sessionDir, { recursive: true });
+ fs.writeFileSync(path.join(sessionDir, "2026-01-01_someone-else.jsonl"), "");
+ fs.writeFileSync(path.join(sessionDir, "2026-05-01_target-id.jsonl"), "");
+
+ expect(findPiSessionFile(sessionDir, "target-id")).toBe(
+ path.join(sessionDir, "2026-05-01_target-id.jsonl"),
+ );
+ });
+
+ it("returns null when no entry matches the id", () => {
+ const sessionDir = path.join(tmpDir, "sessions");
+ fs.mkdirSync(sessionDir, { recursive: true });
+ fs.writeFileSync(path.join(sessionDir, "2026-01-01_someone-else.jsonl"), "");
+
+ expect(findPiSessionFile(sessionDir, "target-id")).toBeNull();
+ });
+
+ it("returns null when the session directory is unreadable / missing", () => {
+ expect(findPiSessionFile(path.join(tmpDir, "does-not-exist"), "target-id")).toBeNull();
+ });
+});
+
+describe("resolvePiSdkVersionFromPath — globally-installed pi fallback detection", () => {
+ it("finds the SDK version by following the `pi` binary's symlink up to its package.json (simulates npm/Homebrew/pnpm global installs)", () => {
+ // Simulate a global install layout:
+ // <root>/lib/node_modules/@earendil-works/pi-coding-agent/{package.json,dist/cli.js}
+ // <root>/bin/pi -> ../lib/node_modules/@earendil-works/pi-coding-agent/dist/cli.js
+ const pkgDir = path.join(tmpDir, "lib", "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(path.join(pkgDir, "dist"), { recursive: true });
+ fs.writeFileSync(
+ path.join(pkgDir, "package.json"),
+ JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.80.3" }),
+ );
+ const entryFile = path.join(pkgDir, "dist", "cli.js");
+ fs.writeFileSync(entryFile, "#!/usr/bin/env node\n");
+
+ const binDir = path.join(tmpDir, "bin");
+ fs.mkdirSync(binDir, { recursive: true });
+ const binPath = path.join(binDir, "pi");
+ fs.symlinkSync(entryFile, binPath);
+
+ const version = resolvePiSdkVersionFromPath({ which: (cmd) => (cmd === "pi" ? binPath : null) });
+ expect(version).toBe("0.80.3");
+ });
+
+ it("returns undefined when `pi` is not on PATH", () => {
+ const version = resolvePiSdkVersionFromPath({ which: () => null });
+ expect(version).toBeUndefined();
+ });
+
+ it("returns undefined (does not throw) when the resolved binary isn't part of the pi-coding-agent package", () => {
+ const otherDir = path.join(tmpDir, "some-other-tool");
+ fs.mkdirSync(otherDir, { recursive: true });
+ fs.writeFileSync(path.join(otherDir, "package.json"), JSON.stringify({ name: "unrelated-tool", version: "1.0.0" }));
+ const binPath = path.join(otherDir, "pi");
+ fs.writeFileSync(binPath, "#!/usr/bin/env node\n");
+
+ const version = resolvePiSdkVersionFromPath({ which: (cmd) => (cmd === "pi" ? binPath : null) });
+ expect(version).toBeUndefined();
+ });
+
+ it("returns undefined (does not throw) when the resolved path doesn't exist on disk", () => {
+ const version = resolvePiSdkVersionFromPath({ which: () => path.join(tmpDir, "nonexistent", "pi") });
+ expect(version).toBeUndefined();
+ });
+
+ // Regression test: on Windows, npm writes the `.cmd` shim as a real file
+ // directly in the global prefix root (e.g. `%AppData%\npm`) — NOT a
+ // symlink into the package like POSIX — so `realpathSync` never walks us
+ // inside it. The package instead sits in a SIBLING `node_modules` folder
+ // at that same level, never an ancestor of the shim's own directory.
+ it("finds the SDK version via a sibling node_modules dir (simulates a Windows npm global install, where the shim is a real file next to node_modules, not a symlink into it)", () => {
+ // Simulate: %AppData%\npm\pi.cmd (a real file, not a symlink) and
+ // %AppData%\npm\node_modules\@earendil-works\pi-coding-agent\
+ const npmRoot = path.join(tmpDir, "AppData", "npm");
+ const pkgDir = path.join(npmRoot, "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(pkgDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(pkgDir, "package.json"),
+ JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.90.1" }),
+ );
+ const binPath = path.join(npmRoot, "pi.cmd");
+ fs.writeFileSync(binPath, "@echo off\r\n"); // a real file, not a symlink
+
+ const version = resolvePiSdkVersionFromPath({ which: (cmd) => (cmd === "pi" ? binPath : null) });
+ expect(version).toBe("0.90.1");
+ });
+
+ it("resolvePiSdkPackageDir returns the sibling package dir itself, not the shim's own directory", () => {
+ const npmRoot = path.join(tmpDir, "AppData", "npm");
+ const pkgDir = path.join(npmRoot, "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(pkgDir, { recursive: true });
+ fs.writeFileSync(path.join(pkgDir, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.90.1" }));
+ const binPath = path.join(npmRoot, "pi.cmd");
+ fs.writeFileSync(binPath, "@echo off\r\n");
+
+ const dir = resolvePiSdkPackageDir({ which: (cmd) => (cmd === "pi" ? binPath : null) });
+ // Compare via realpath — on macOS, tmpdir() itself sits behind a
+ // `/var` -> `/private/var` symlink unrelated to the thing under test.
+ expect(dir && fs.realpathSync(dir)).toBe(fs.realpathSync(pkgDir));
+ });
+});
diff --git a/src/daemon/src/drivers/pi.ts b/src/daemon/agent-driver/src/adapters/pi/index.ts
similarity index 51%
rename from src/daemon/src/drivers/pi.ts
rename to src/daemon/agent-driver/src/adapters/pi/index.ts
index e49c5bdc1..ba2f44ec5 100644
--- a/src/daemon/src/drivers/pi.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/index.ts
@@ -1,38 +1,19 @@
-/**
- * Pi driver — in-process, multi-provider SDK runtime (@earendil-works/pi-coding-agent).
- *
- * Pi runs in-process (no child process, no stdin). It is
- * multi-provider: model ids look like `provider/id` and resolve through an
- * auth/settings registry (Google / OpenAI / OpenRouter). Sessions persist as
- * JSONL; a custom bash tool is injected so shell calls inherit the CLI-transport
- * env. Steering is `direct` (guarded by `session.isStreaming`).
- *
- * The standing prompt is delivered via `AGENTS.md` written into the workdir
- * by `prepareCliTransport` inside `piSdkDeps.buildSpawnEnv` — Pi is unusual in
- * that it has no child process of its own, but its bash tool still goes
- * through the same transport, so the AGENTS.md packing happens exactly once
- * (in `buildSpawnEnv`) and this file doesn't need to re-write it.
- *
- * `createSession` only builds and wires the session — it does not send the
- * first turn. `SdkManagedSession` (the `ManagedSession` adapter that drives
- * this from `managerRuntime.ts`) attaches its `"runtime_event"` listener to
- * the returned session first, then sends the initial prompt, so nothing
- * fires into an unlistened `EventEmitter` and gets dropped.
- */
+/** In-process Pi SDK adapter; the controller sends only after listeners attach. */
import { createRequire } from "module";
import { existsSync, readdirSync, readFileSync, realpathSync } from "fs";
import { homedir } from "os";
import * as path from "path";
-import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SdkDriverDeps, SpawnResult } from "../types.js";
-import { buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { SdkRuntimeSession, type SdkSessionHandle } from "../runtime/sdkRuntimeSession.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { resolveCommandOnPath, type ProbeDeps } from "./probe.js";
+import type {
+ BackendAdapter, AdapterLaunchContext, AdapterEvent, VendorSessionHandle,
+} from "../../internal/adapter.js";
+import { SdkLane } from "../../controller/sdk-host.js";
+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
+import { resolveCommandOnPath, type ProbeDeps } from "../../internal/probe.js";
+import { createPiSessionDependencies, type PiSessionDependencies } from "./sessionDeps.js";
const PI_SDK_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
-/** Minimal shape of the vendor SDK's `AgentSession` this driver actually calls. */
-export interface PiSdkAgentSession {
+interface PiSdkAgentSession {
prompt(text: string, options?: { streamingBehavior?: "steer" | "followUp" }): Promise<void>;
steer(text: string): Promise<void>;
abort(): Promise<void>;
@@ -41,45 +22,19 @@ export interface PiSdkAgentSession {
subscribe(listener: (event: unknown) => void): () => void;
}
-/** True if `pkgJsonPath` exists and is the pi SDK's own `package.json`. */
function isPiSdkPackageJson(pkgJsonPath: string): boolean {
if (!existsSync(pkgJsonPath)) return false;
try {
const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf-8")) as { name?: string };
return pkg.name === PI_SDK_PACKAGE_NAME;
} catch {
- // Malformed package.json — treat as "not this package"; the caller
- // keeps walking, it may just be an unrelated file that happens to sit
- // alongside the binary.
return false;
}
}
/**
- * Fallback SDK detection for a globally-installed `pi` (e.g. `npm install -g
- * @earendil-works/pi-coding-agent`, a Homebrew formula, or a pnpm/yarn/nvm
- * global install). `require()` from the daemon's own file location can never
- * see a global install — it lives in a completely separate `node_modules`
- * tree — even though `pi --version` works fine in a shell. So instead we
- * resolve the `pi` binary on `PATH` (same as every other driver's `probe()`)
- * and walk upward from it looking for the package's own `package.json`,
- * checking two shapes at each level:
- * 1. `dir` itself IS inside the package — true on POSIX, where the PATH
- * resolution follows a symlink through `realpathSync` into the
- * package's real install directory (npm/Homebrew/pnpm/yarn/nvm all do
- * this).
- * 2. `dir/node_modules/@earendil-works/pi-coding-agent` — true on Windows,
- * where npm writes the `.cmd` shim as a real file directly in the
- * global prefix root (e.g. `%AppData%\npm`) rather than a symlink INTO
- * the package, so `realpathSync` never gets us inside it; the actual
- * package instead sits in a SIBLING `node_modules` folder at that same
- * level, never an ancestor.
- * This is package-manager-agnostic: it doesn't assume npm specifically (no
- * `npm root -g` shell-out), so it keeps working no matter how the global
- * install actually got there.
- *
- * Also used by `piSdkDeps.ts::loadPiSdkModule` to find the real install
- * directory to `import()` when the SDK isn't a bundled dependency.
+ * Finds a globally installed Pi SDK from the PATH binary. Handles POSIX
+ * symlinks and Windows shims with sibling node_modules layouts.
*/
export function resolvePiSdkPackageDir(deps: ProbeDeps = {}): string | undefined {
const binPath = resolveCommandOnPath("pi", deps);
@@ -87,11 +42,6 @@ export function resolvePiSdkPackageDir(deps: ProbeDeps = {}): string | undefined
try {
let dir = path.dirname(realpathSync(binPath));
- // 8 levels is enough to cover every layout we've seen: npm/pnpm globals
- // resolve within 2-4 hops, nvm adds ~1, Homebrew Cellar adds ~2, and
- // Windows `.cmd` shims sit alongside a sibling `node_modules` at the same
- // root (0 hops upward, checked as the second shape below). Higher would
- // wander into unrelated ancestor trees; lower would miss nvm-under-brew.
const MAX_DEPTH = 8;
for (let i = 0; i < MAX_DEPTH; i++) {
if (isPiSdkPackageJson(path.join(dir, "package.json"))) return dir;
@@ -100,27 +50,15 @@ export function resolvePiSdkPackageDir(deps: ProbeDeps = {}): string | undefined
if (isPiSdkPackageJson(path.join(siblingDir, "package.json"))) return siblingDir;
const parent = path.dirname(dir);
- if (parent === dir) break; // hit filesystem root
+ if (parent === dir) break;
dir = parent;
}
} catch {
- // Broken symlink, permission error, etc. — treat as not found.
}
return undefined;
}
-/**
- * Locate the Pi SDK session-rollout file for `sessionId` in `sessionDir`.
- *
- * Pi persists each session as `<isoDate>_<sessionId>.jsonl` inside its session
- * directory (`--<encoded-cwd>--`). To resume a specific session we need the
- * actual file path — not just the id — because `SessionManager.open` takes a
- * path. Returns null if the directory is unreadable or no matching file exists
- * (the caller falls back to `create` in that case).
- *
- * Pure enough to unit-test without touching the SDK: read a directory, filter
- * by suffix, return the first match.
- */
+/** Finds Pi's persisted `<date>_<sessionId>.jsonl` rollout. */
export function findPiSessionFile(sessionDir: string, sessionId: string): string | null {
let entries: string[];
try {
@@ -140,7 +78,7 @@ export function findPiSessionFile(sessionDir: string, sessionId: string): string
* vendor barrel (it enumerates re-exports by name and omits this one), so
* calling it unconditionally throws `sdk.getDefaultSessionDir is not a
* function` and takes down every Pi resume — `withSessionDirHelper` in
- * `piSdkDeps.ts` grafts it on from the deep `core/session-manager.js` module,
+ * `sessionDeps.ts` grafts it on from the deep `core/session-manager.js` module,
* which is why it's usually present here despite the barrel gap.
*
* The fallback reproduces the SDK's rule (`core/session-manager.js`):
@@ -204,8 +142,23 @@ function readPiSdkVersion(): string | undefined {
return resolvePiSdkVersionFromPath();
}
+/** Vendor notifications that intentionally carry no public semantic event. */
+export const PI_IGNORED_EVENT_TYPES = [
+ "agent_start",
+ "turn_start",
+ "turn_end",
+ "message_end",
+ "tool_execution_update",
+ "queue_update",
+ "session_info_changed",
+ "thinking_level_changed",
+ "auto_retry_start",
+ "auto_retry_end",
+ "agent_end",
+] as const;
+
/** Map a Pi SDK event to zero or more normalized events. */
-export function mapPiSdkEventToParsedEvents(event: any, sessionId: string, state: { sawTextDelta: boolean }): ParsedEvent[] {
+export function mapPiSdkEvent(event: any, sessionId: string, state: { sawTextDelta: boolean }): AdapterEvent[] {
if (event?.type === "message_update") {
const d = event.delta ?? {};
switch (d.type) {
@@ -231,36 +184,28 @@ export function mapPiSdkEventToParsedEvents(event: any, sessionId: string, state
return [{ kind: "compaction_started" }];
case "compaction_end":
return [{ kind: "compaction_finished" }];
- case "agent_end":
- return [{ kind: "turn_end", sessionId }];
default:
- // Dropped: agent_start, turn_start, turn_end, message_end,
- // tool_execution_update, queue_update, session_info_changed,
- // thinking_level_changed, auto_retry_start, auto_retry_end, …
+ // PI_IGNORED_EVENT_TYPES documents the complete known no-op family.
return [];
}
}
-export class PiDriver implements Driver {
+export class PiDriver implements BackendAdapter {
readonly id = "pi";
- readonly lifecycle = { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const;
- readonly session = { recovery: "resume_or_fresh" } as const;
- readonly model = {
- detectedModelsVerifiedAs: "launchable",
- toLaunchSpec: (modelId: string) => ({ params: { model: modelId } }),
- } as const;
-
- readonly supportsNativeStandingPrompt = true;
-
- readonly capabilities = {
- reasoningEffort: true,
- fastMode: false,
- disallowedTools: false,
- command: true,
- sessionResumeMode: "by-id",
+ readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
+ readonly execution = {
+ lifetime: "session",
+ transport: { kind: "in_process_sdk", protocol: "pi_sdk" },
+ wakeStart: "immediate",
+ terminalOwnership: "prompt_invocation",
} as const;
private sessionId: string | null = null;
+ private terminalSequence = 0;
+
+ constructor(
+ private readonly dependenciesFor: (ctx: AdapterLaunchContext) => PiSessionDependencies = createPiSessionDependencies,
+ ) {}
probe() {
const version = readPiSdkVersion();
@@ -273,23 +218,19 @@ export class PiDriver implements Driver {
return { status: "healthy" as const, version };
}
- spawn(): Promise<SpawnResult> {
- throw new Error("PiDriver uses a native RuntimeSession; child-process spawn is unsupported");
- }
-
/**
- * In-process session factory. `deps` carries the Pi SDK constructors so this
- * file is dependency-free; the daemon injects the real implementations
- * (see `piSdkDeps.ts`).
+ * In-process session factory. The adapter owns vendor loading and session
+ * construction; callers see only the public logical session.
*
* Builds and wires the session but deliberately does NOT fire the initial
- * prompt — `SdkRuntimeSession.emitEvents` fires on a plain `EventEmitter`,
+ * prompt — the SDK lane emits on a plain `EventEmitter`,
* which drops events fired before any listener is attached (unlike a child
- * process's buffered stdout pipe). The caller (`SdkManagedSession.start`)
+ * process's buffered stdout pipe). The logical session controller
* attaches its own `"runtime_event"` listener to the session this returns
* BEFORE sending the first turn via `.send()`, so nothing is lost.
*/
- async createSession(ctx: LaunchContext, deps: SdkDriverDeps): Promise<SdkRuntimeSession> {
+ async openLane(ctx: AdapterLaunchContext): Promise<SdkLane> {
+ const deps = this.dependenciesFor(ctx);
const spawnEnv = await deps.buildSpawnEnv();
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
const { session, sessionId } = (await deps.createAgentSession({
@@ -302,13 +243,12 @@ export class PiDriver implements Driver {
this.sessionId = sessionId;
const state = { sawTextDelta: false };
- const handle: SdkSessionHandle = {
- // `session.prompt()` throws "Agent is already processing" if a prior
- // turn is still streaming (SdkManagedSession's fire-and-forget send is
- // the primary defense — this is a belt-and-suspenders guard against
- // any remaining window between our own turn_end detection and the SDK
- // flipping `isStreaming`): queue as a follow-up instead of throwing.
- prompt: (t: string) => session.prompt(t, session.isStreaming ? { streamingBehavior: "followUp" } : undefined),
+ const handle: VendorSessionHandle = {
+ // A root turn is owned by this exact prompt promise. Never downgrade it
+ // to followUp/steer, whose completion belongs to a different invocation.
+ // SdkLane waits for idle and turns a persistent-busy race into a
+ // controlled failed terminal instead of guessing terminal ownership.
+ prompt: (t: string) => session.prompt(t),
steer: (t: string) => session.steer(t),
abort: () => session.abort(),
dispose: () => session.dispose(),
@@ -316,27 +256,28 @@ export class PiDriver implements Driver {
return session.isStreaming;
},
};
- const runtimeSession = new SdkRuntimeSession(handle, this.sessionId!);
- session.subscribe((event: unknown) =>
- runtimeSession.emitEvents(mapPiSdkEventToParsedEvents(event, this.sessionId!, state)),
- );
+ const runtimeSession = new SdkLane(handle, this.sessionId!, { terminalOnPromptSettled: true });
+ session.subscribe((event: unknown) => {
+ runtimeSession.emitEvents(mapPiSdkEvent(event, this.sessionId!, state));
+ });
return runtimeSession;
}
- parseLine(): ParsedEvent[] {
+ normalizeLine(): AdapterEvent[] {
return [];
}
+ beginTurn(): string {
+ return `pi:${++this.terminalSequence}`;
+ }
+
get currentSessionId(): string | null {
return this.sessionId;
}
- encodeStdinMessage(): string | null {
+ encodeMessage(): string | null {
return null;
}
- buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config);
- }
}
diff --git a/src/daemon/src/drivers/piSdkDeps.test.ts b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts
similarity index 85%
rename from src/daemon/src/drivers/piSdkDeps.test.ts
rename to src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts
index 8b9da91ab..8a283376a 100644
--- a/src/daemon/src/drivers/piSdkDeps.test.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts
@@ -2,10 +2,10 @@ import { describe, it, expect, vi, afterEach } from "vitest";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
-import { createPiSdkDriverDeps, loadPiSdkModule, type PiSdkModule, type PiSdkLoader } from "./piSdkDeps.js";
-import { CredentialBroker } from "../credentials/credentialProxy.js";
-import type { LaunchContext } from "../types.js";
-import { makeRuntimeConfig } from "../runtimeConfig.js";
+import { createPiSessionDependencies, loadPiSdkModule, type PiSdkModule, type PiSdkLoader } from "./sessionDeps.js";
+import type { AdapterLaunchContext } from "../../internal/adapter.js";
+import type { PiConfig } from "../../contract.js";
+import { fakeLaunchContext, fakePrepared } from "../../testing/adapter-fixture.js";
const tmpDirs: string[] = [];
function mkTmp(): string {
@@ -17,21 +17,20 @@ afterEach(() => {
for (const d of tmpDirs.splice(0)) fs.rmSync(d, { recursive: true, force: true });
});
-function baseCtx(overrides: Partial<LaunchContext> = {}): LaunchContext {
+function baseCtx(overrides: Partial<AdapterLaunchContext> = {}): AdapterLaunchContext {
+ return fakeLaunchContext("pi", mkTmp(), {
+ prepared: fakePrepared({
+ networkProtected: { ALOOK_PROXY_URL: "http://127.0.0.1:9/proxy" },
+ credentialSensitive: { ALOOK_PROXY_TOKEN_FILE: "/tmp/voucher" },
+ }),
+ ...overrides,
+ });
+}
+
+function piConfig(overrides: Partial<PiConfig> = {}): PiConfig {
return {
- agentId: "agent_1",
- launchId: "launch_1",
- workingDirectory: mkTmp(),
- standingPrompt: "",
- prompt: "",
- credentialProxy: {
- broker: new CredentialBroker({ upstreamBaseUrl: "https://upstream.test", voucherDir: mkTmp() }),
- proxyUrl: "http://127.0.0.1:9/proxy",
- runnerKey: "sk_agent_test",
- capabilities: ["send", "read"],
- },
- config: {},
- mockCliTransport: true,
+ model: { kind: "default" },
+ provider: { kind: "default" },
...overrides,
};
}
@@ -95,10 +94,10 @@ function fakeSdk(opts: {
};
}
-describe("createPiSdkDriverDeps — buildSpawnEnv", () => {
+describe("createPiSessionDependencies — buildSpawnEnv", () => {
it("delegates to prepareCliTransport: credential voucher present, PATH includes the link dir", async () => {
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fakeSdk().loader);
+ const deps = createPiSessionDependencies(ctx, fakeSdk().loader);
const env = await deps.buildSpawnEnv();
@@ -108,13 +107,13 @@ describe("createPiSdkDriverDeps — buildSpawnEnv", () => {
});
});
-describe("createPiSdkDriverDeps — createAgentSession", () => {
+describe("createPiSessionDependencies — createAgentSession", () => {
it("sets the runtime API key when the runtime config carries a pi-builtin provider", async () => {
const fake = fakeSdk();
const ctx = baseCtx({
- config: { runtimeConfig: makeRuntimeConfig({ runtime: "pi", provider: { kind: "pi-builtin", providerId: "google", apiKey: "key-123" } }) },
+ config: { runtimeConfig: piConfig({ provider: { kind: "builtin", providerId: "google", apiKey: "key-123" } }) },
});
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} });
@@ -124,7 +123,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
it("does not set a runtime API key when there is no pi-builtin provider", async () => {
const fake = fakeSdk();
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} });
@@ -134,7 +133,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
it("resolves a 'provider/id' model string via modelRegistry.find", async () => {
const fake = fakeSdk();
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
await deps.createAgentSession({ cwd: ctx.workingDirectory, model: "google/gemini-2.5-pro", spawnEnv: {} });
@@ -147,7 +146,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
it("omits model (lets the SDK pick its own default) for an unparsable model string", async () => {
const fake = fakeSdk();
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
await deps.createAgentSession({ cwd: ctx.workingDirectory, model: "not-a-provider-id-pair", spawnEnv: {} });
@@ -162,7 +161,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
sessionDirEntries: ["2026-05-01_resume-me.jsonl", "2026-01-01_someone-else.jsonl"],
});
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
await deps.createAgentSession({ cwd: ctx.workingDirectory, sessionId: "resume-me", spawnEnv: {} });
@@ -180,7 +179,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
const sessionDir = mkTmp();
const fake = fakeSdk({ sessionDir });
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
await deps.createAgentSession({ cwd: ctx.workingDirectory, sessionId: "brand-new-id", spawnEnv: {} });
@@ -197,7 +196,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
const agentDir = mkTmp();
const fake = fakeSdk({ omitGetDefaultSessionDir: true, agentDir });
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
await deps.createAgentSession({ cwd: ctx.workingDirectory, sessionId: "resume-me", spawnEnv: {} });
@@ -210,7 +209,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
it("no sessionId: uses SessionManager.create(cwd) — a fresh session, unchanged from prior behavior", async () => {
const fake = fakeSdk();
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} });
@@ -222,7 +221,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
it("passes a customTools bash tool whose spawnHook merges the given spawnEnv on top of the base env", async () => {
const fake = fakeSdk();
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
const spawnEnv = { ALOOK_PROXY_URL: "http://proxy" };
await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv });
@@ -241,7 +240,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
it("returns the sessionId from session.sessionId when createAgentSession doesn't return one directly", async () => {
const fake = fakeSdk();
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
const result = await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} });
@@ -252,7 +251,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
const fake = fakeSdk();
fake.createAgentSession.mockResolvedValue({ session: {} });
const ctx = baseCtx();
- const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const deps = createPiSessionDependencies(ctx, fake.loader);
await expect(deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} })).rejects.toThrow(/sessionId/);
});
@@ -270,24 +269,24 @@ describe("loadPiSdkModule — global-install fallback", () => {
fs.writeFileSync(path.join(pkgDir, "dist", "index.js"), "export const MARKER = 'loaded-from-global-install';\n");
vi.resetModules();
- vi.doMock("./pi.js", () => ({ resolvePiSdkPackageDir: () => pkgDir }));
- const fresh = await import("./piSdkDeps.js");
+ vi.doMock("./index.js", () => ({ resolvePiSdkPackageDir: () => pkgDir }));
+ const fresh = await import("./sessionDeps.js");
const sdk = (await fresh.loadPiSdkModule()) as unknown as { MARKER: string };
expect(sdk.MARKER).toBe("loaded-from-global-install");
- vi.doUnmock("./pi.js");
+ vi.doUnmock("./index.js");
vi.resetModules();
});
it("throws a clear error when pi isn't found on PATH either", async () => {
vi.resetModules();
- vi.doMock("./pi.js", () => ({ resolvePiSdkPackageDir: () => undefined }));
- const fresh = await import("./piSdkDeps.js");
+ vi.doMock("./index.js", () => ({ resolvePiSdkPackageDir: () => undefined }));
+ const fresh = await import("./sessionDeps.js");
await expect(fresh.loadPiSdkModule()).rejects.toThrow(/pi-coding-agent/);
- vi.doUnmock("./pi.js");
+ vi.doUnmock("./index.js");
vi.resetModules();
});
@@ -303,8 +302,8 @@ describe("loadPiSdkModule — global-install fallback", () => {
vi.resetModules();
let resolvable = false;
- vi.doMock("./pi.js", () => ({ resolvePiSdkPackageDir: () => (resolvable ? pkgDir : undefined) }));
- const fresh = await import("./piSdkDeps.js");
+ vi.doMock("./index.js", () => ({ resolvePiSdkPackageDir: () => (resolvable ? pkgDir : undefined) }));
+ const fresh = await import("./sessionDeps.js");
await expect(fresh.loadPiSdkModule()).rejects.toThrow(/pi-coding-agent/);
@@ -312,7 +311,7 @@ describe("loadPiSdkModule — global-install fallback", () => {
const sdk = (await fresh.loadPiSdkModule()) as unknown as { MARKER: string };
expect(sdk.MARKER).toBe("loaded-from-global-install-retry");
- vi.doUnmock("./pi.js");
+ vi.doUnmock("./index.js");
vi.resetModules();
});
});
@@ -350,10 +349,10 @@ describe("loadPiSdkModule — grafting the vendor's getDefaultSessionDir", () =>
async function loadFrom(pkgDir: string) {
vi.resetModules();
- vi.doMock("./pi.js", () => ({ resolvePiSdkPackageDir: () => pkgDir }));
- const fresh = await import("./piSdkDeps.js");
+ vi.doMock("./index.js", () => ({ resolvePiSdkPackageDir: () => pkgDir }));
+ const fresh = await import("./sessionDeps.js");
const sdk = await fresh.loadPiSdkModule();
- vi.doUnmock("./pi.js");
+ vi.doUnmock("./index.js");
vi.resetModules();
return sdk;
}
diff --git a/src/daemon/src/drivers/piSdkDeps.ts b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts
similarity index 90%
rename from src/daemon/src/drivers/piSdkDeps.ts
rename to src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts
index ba85f87b0..edba40673 100644
--- a/src/daemon/src/drivers/piSdkDeps.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts
@@ -1,5 +1,5 @@
/**
- * Real `SdkDriverDeps` implementation for `PiDriver` — the only piece that
+ * Real session dependencies for `PiDriver` — the only piece that
* actually talks to `@earendil-works/pi-coding-agent`. Kept out of `pi.ts` so
* that file stays free of a hard SDK import (mirrors the "deps carry the
* constructors" design already documented there); this module is where the
@@ -8,9 +8,9 @@
import { readFileSync } from "fs";
import * as path from "path";
import { pathToFileURL } from "url";
-import type { LaunchContext, SdkDriverDeps } from "../types.js";
-import { findPiSessionFile, resolvePiSdkPackageDir, resolvePiSessionDir } from "./pi.js";
-import { prepareCliTransport, DEFAULT_CLI_CONFIG } from "./cliTransport.js";
+import type { AdapterLaunchContext } from "../../internal/adapter.js";
+import { findPiSessionFile, resolvePiSdkPackageDir, resolvePiSessionDir } from "./index.js";
+import { prepareCliTransport } from "../../internal/cliTransport.js";
const PI_SDK_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
@@ -149,29 +149,39 @@ function parseModelString(model: string | undefined): { provider: string; id: st
}
/**
- * Build the real `SdkDriverDeps` for a Pi launch. Closes over `ctx` so
- * `buildSpawnEnv` needs no arguments (matches `PiDriver.createSession`'s
+ * Build the real Pi session dependencies for a launch. Closes over `ctx` so
+ * `buildSpawnEnv` needs no arguments (matches `PiDriver.openLane`'s
* existing contract) — a fresh instance is built per launch, so nothing here
* is process-global mutable state (safe for concurrent agents with different
* credentials).
*/
-export function createPiSdkDriverDeps(ctx: LaunchContext, loadSdk: PiSdkLoader = loadPiSdkModule): SdkDriverDeps {
+export interface PiSessionDependencies {
+ buildSpawnEnv(): Promise<NodeJS.ProcessEnv>;
+ createAgentSession(opts: Record<string, unknown>): Promise<{ session: unknown; sessionId: string }>;
+}
+
+export function createPiSessionDependencies(
+ ctx: AdapterLaunchContext,
+ loadSdk: PiSdkLoader = loadPiSdkModule,
+): PiSessionDependencies {
return {
async buildSpawnEnv(): Promise<NodeJS.ProcessEnv> {
// Pi has no child process of its own, but its bash tool does — reuse the
// exact same credential-voucher + PATH-link machinery every CLI driver
// gets via `prepareCliTransport`, so the agent's `alook` bash calls
// authenticate the same zero-trust way.
- const cliConfig = ctx.agentCliPath ? { ...DEFAULT_CLI_CONFIG, hostCliPath: ctx.agentCliPath } : DEFAULT_CLI_CONFIG;
- const { spawnEnv } = await prepareCliTransport(ctx, {}, cliConfig);
+ const { spawnEnv } = await prepareCliTransport(ctx);
return spawnEnv;
},
async createAgentSession(opts: Record<string, unknown>): Promise<{ session: unknown; sessionId: string }> {
const sdk = await loadSdk();
const authStorage = sdk.AuthStorage.create();
- const provider = ctx.config.runtimeConfig?.provider;
- if (provider?.kind === "pi-builtin") {
+ const runtimeConfig = ctx.config.runtimeConfig;
+ const provider = runtimeConfig && "provider" in runtimeConfig
+ ? runtimeConfig.provider
+ : undefined;
+ if (provider?.kind === "builtin") {
authStorage.setRuntimeApiKey(provider.providerId, provider.apiKey);
}
const modelRegistry = sdk.ModelRegistry.create(authStorage);
diff --git a/src/daemon/agent-driver/src/builtin-config.test.ts b/src/daemon/agent-driver/src/builtin-config.test.ts
new file mode 100644
index 000000000..fe8a9bd9a
--- /dev/null
+++ b/src/daemon/agent-driver/src/builtin-config.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import { toBuiltinBackendSelection, type BuiltinRuntimeConfigInput } from "./builtin-config.js";
+
+function config(runtime: string, overrides: Partial<BuiltinRuntimeConfigInput> = {}): BuiltinRuntimeConfigInput {
+ return {
+ runtime,
+ model: { kind: "default" },
+ mode: { kind: "default" },
+ ...overrides,
+ };
+}
+
+describe("builtin config boundary", () => {
+ it("owns Claude endpoint and Pi provider interpretation inside the package", () => {
+ expect(toBuiltinBackendSelection(config("claude", {
+ provider: { kind: "custom", apiUrl: "https://example.invalid", apiKey: "claude-key" },
+ }))).toMatchObject({
+ backend: "claude",
+ config: { provider: { kind: "custom_endpoint", apiUrl: "https://example.invalid", apiKey: "claude-key" } },
+ });
+ expect(toBuiltinBackendSelection(config("pi", {
+ provider: { kind: "pi-builtin", providerId: "openai", apiKey: "pi-key" },
+ }))).toMatchObject({
+ backend: "pi",
+ config: { provider: { kind: "builtin", providerId: "openai", apiKey: "pi-key" } },
+ });
+ expect(toBuiltinBackendSelection(config("claude", {
+ provider: { kind: "default" },
+ }))).toMatchObject({
+ backend: "claude",
+ config: { provider: { kind: "default" } },
+ });
+ });
+
+ it.each(["codex", "cursor", "opencode", "pi"])("maps %s without daemon-side switches", (runtime) => {
+ expect(toBuiltinBackendSelection(config(runtime))).toMatchObject({ backend: runtime });
+ });
+
+ it("rejects unknown runtime ids", () => {
+ expect(() => toBuiltinBackendSelection(config("unknown"))).toThrow("Unknown runtime: unknown");
+ });
+});
diff --git a/src/daemon/agent-driver/src/builtin-config.ts b/src/daemon/agent-driver/src/builtin-config.ts
new file mode 100644
index 000000000..8e3ca29a5
--- /dev/null
+++ b/src/daemon/agent-driver/src/builtin-config.ts
@@ -0,0 +1,70 @@
+import type {
+ BuiltinBackendId,
+ BuiltinBackendSpecs,
+ ConfigOf,
+ ModelSelection,
+ ReasoningEffort,
+} from "./contract.js";
+
+export interface BuiltinRuntimeConfigInput {
+ readonly runtime: string;
+ readonly model: ModelSelection;
+ readonly mode: { readonly kind: "default" | "fast" };
+ readonly reasoningEffort?: ReasoningEffort;
+ readonly provider?:
+ | { readonly kind: "default" }
+ | { readonly kind: "custom"; readonly apiUrl: string; readonly apiKey: string }
+ | { readonly kind: "pi-builtin"; readonly providerId: string; readonly apiKey: string };
+ readonly command?: string;
+ readonly disallowedTools?: string;
+ readonly envVars?: Readonly<Record<string, string>>;
+}
+
+export type BuiltinBackendSelection = {
+ [Id in BuiltinBackendId]: {
+ readonly backend: Id;
+ readonly config: ConfigOf<BuiltinBackendSpecs, Id>;
+ };
+}[BuiltinBackendId];
+
+export function toBuiltinBackendSelection(config: BuiltinRuntimeConfigInput): BuiltinBackendSelection {
+ const base = { model: config.model, command: config.command, environment: config.envVars };
+ switch (config.runtime) {
+ case "claude":
+ return {
+ backend: "claude",
+ config: {
+ ...base,
+ provider: config.provider?.kind === "custom"
+ ? { kind: "custom_endpoint", apiUrl: config.provider.apiUrl, apiKey: config.provider.apiKey }
+ : { kind: "default" },
+ reasoningEffort: config.reasoningEffort,
+ mode: config.mode.kind,
+ disallowedTools: config.disallowedTools,
+ },
+ };
+ case "codex":
+ return {
+ backend: "codex",
+ config: { ...base, reasoningEffort: config.reasoningEffort, mode: config.mode.kind },
+ };
+ case "cursor":
+ return { backend: "cursor", config: base };
+ case "opencode":
+ return { backend: "opencode", config: base };
+ case "pi":
+ return {
+ backend: "pi",
+ config: {
+ model: config.model,
+ environment: config.envVars,
+ provider: config.provider?.kind === "pi-builtin"
+ ? { kind: "builtin", providerId: config.provider.providerId, apiKey: config.provider.apiKey }
+ : { kind: "default" },
+ reasoningEffort: config.reasoningEffort,
+ },
+ };
+ default:
+ throw new Error(`Unknown runtime: ${config.runtime}`);
+ }
+}
diff --git a/src/daemon/agent-driver/src/contract.ts b/src/daemon/agent-driver/src/contract.ts
new file mode 100644
index 000000000..ad074dfd5
--- /dev/null
+++ b/src/daemon/agent-driver/src/contract.ts
@@ -0,0 +1,510 @@
+export type JsonPrimitive = string | number | boolean | null;
+export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];
+export type JsonObject = { readonly [key: string]: JsonValue };
+
+export type BuiltinBackendId = "claude" | "codex" | "cursor" | "opencode" | "pi";
+export type ReasoningEffort = "low" | "medium" | "high";
+
+export type ModelSelection =
+ | { readonly kind: "default" }
+ | { readonly kind: "named"; readonly name: string }
+ | { readonly kind: "custom"; readonly name: string };
+
+export type DefaultProvider = { readonly kind: "default" };
+export type ClaudeProvider =
+ | DefaultProvider
+ | { readonly kind: "custom_endpoint"; readonly apiUrl: string; readonly apiKey: string };
+export type PiProvider =
+ | DefaultProvider
+ | {
+ readonly kind: "builtin";
+ readonly providerId: "google" | "openai" | "openrouter" | (string & {});
+ readonly apiKey: string;
+ };
+
+export interface BaseBackendConfig {
+ readonly command?: string;
+ readonly environment?: Readonly<Record<string, string>>;
+}
+
+export interface ClaudeConfig extends BaseBackendConfig {
+ readonly model: ModelSelection;
+ readonly provider: ClaudeProvider;
+ readonly reasoningEffort?: ReasoningEffort;
+ readonly mode: "default" | "fast";
+ readonly disallowedTools?: string;
+}
+
+export interface CodexConfig extends BaseBackendConfig {
+ readonly model: ModelSelection;
+ readonly reasoningEffort?: ReasoningEffort;
+ readonly mode: "default" | "fast";
+}
+
+export interface ModelBackendConfig extends BaseBackendConfig {
+ readonly model: ModelSelection;
+}
+
+export type CursorConfig = ModelBackendConfig;
+export type OpenCodeConfig = ModelBackendConfig;
+
+export interface PiConfig extends Omit<BaseBackendConfig, "command"> {
+ readonly model: ModelSelection;
+ readonly provider: PiProvider;
+ readonly reasoningEffort?: ReasoningEffort;
+}
+
+export interface BackendCapabilities {
+ readonly modelSelection: "launchable" | "suggestion_only" | "unsupported";
+ readonly providerConfiguration: boolean;
+ readonly reasoningEffort: boolean;
+ readonly fastMode: boolean;
+ readonly disallowedTools: boolean;
+ readonly commandOverride: boolean;
+ readonly resume: "by_id" | "none";
+ readonly sessionLifetime: "persistent" | "per_turn";
+ readonly midTurnDelivery: "steer" | "safe_boundary_queue" | "next_turn_queue";
+ readonly interrupt: boolean;
+}
+
+export type FixedCapabilities<
+ Provider extends boolean,
+ Reasoning extends boolean,
+ Fast extends boolean,
+ Tools extends boolean,
+ Command extends boolean,
+ Delivery extends BackendCapabilities["midTurnDelivery"],
+ Lifetime extends BackendCapabilities["sessionLifetime"],
+> = BackendCapabilities & {
+ readonly modelSelection: "launchable";
+ readonly providerConfiguration: Provider;
+ readonly reasoningEffort: Reasoning;
+ readonly fastMode: Fast;
+ readonly disallowedTools: Tools;
+ readonly commandOverride: Command;
+ readonly resume: "by_id";
+ readonly sessionLifetime: Lifetime;
+ readonly midTurnDelivery: Delivery;
+ readonly interrupt: true;
+};
+
+export type ClaudeCapabilities = FixedCapabilities<true, true, true, true, true, "safe_boundary_queue", "persistent">;
+export type CodexCapabilities = FixedCapabilities<false, true, true, false, true, "safe_boundary_queue", "persistent">;
+export type CursorCapabilities = FixedCapabilities<false, false, false, false, true, "next_turn_queue", "persistent">;
+export type OpenCodeCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;
+export type PiCapabilities = FixedCapabilities<true, true, false, false, false, "steer", "persistent">;
+
+export interface BackendExtensionSpec<Input, Output> {
+ readonly input: Input;
+ readonly output: Output;
+}
+
+export interface BackendTypeSpec<Config, Capabilities, Extensions, ExtraEvent> {
+ readonly config: Config;
+ readonly capabilities: Capabilities;
+ readonly extensions: Extensions;
+ readonly extraEvent: ExtraEvent;
+}
+
+export interface BuiltinBackendSpecs {
+ readonly claude: BackendTypeSpec<ClaudeConfig, ClaudeCapabilities, {}, never>;
+ readonly codex: BackendTypeSpec<CodexConfig, CodexCapabilities, {}, never>;
+ readonly cursor: BackendTypeSpec<CursorConfig, CursorCapabilities, {}, never>;
+ readonly opencode: BackendTypeSpec<OpenCodeConfig, OpenCodeCapabilities, {}, never>;
+ readonly pi: BackendTypeSpec<PiConfig, PiCapabilities, {}, never>;
+}
+
+export type BackendId<Specs> = Extract<keyof Specs, string>;
+export type ConfigOf<Specs, Id extends BackendId<Specs>> =
+ Specs[Id] extends BackendTypeSpec<infer Config, infer _Caps, infer _Extensions, infer _Event>
+ ? Config
+ : never;
+export type CapabilitiesOf<Specs, Id extends BackendId<Specs>> =
+ Specs[Id] extends BackendTypeSpec<infer _Config, infer Caps, infer _Extensions, infer _Event>
+ ? Caps
+ : never;
+export type ExtensionsOf<Specs, Id extends BackendId<Specs>> =
+ Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer Extensions, infer _Event>
+ ? Extensions
+ : never;
+export type ExtraEventOf<Specs, Id extends BackendId<Specs>> =
+ Specs[Id] extends BackendTypeSpec<infer _Config, infer _Caps, infer _Extensions, infer Event>
+ ? Event
+ : never;
+
+export interface AgentInstructions {
+ readonly format: "markdown";
+ readonly content: string;
+}
+
+export interface AgentLaunchContext {
+ readonly workingDirectory: string;
+ readonly instructions: AgentInstructions;
+ readonly resumeSessionId?: string;
+ readonly launchId: string;
+}
+
+export interface AgentMessage {
+ readonly id: string;
+ readonly kind: "user" | "system" | "recovery";
+ readonly text: string;
+ readonly sequence?: number;
+}
+
+export interface AgentDriverError {
+ readonly category:
+ | "runtime_unavailable"
+ | "authentication"
+ | "configuration"
+ | "protocol"
+ | "process"
+ | "sdk"
+ | "timeout"
+ | "cancelled"
+ | "buffer_overflow"
+ | "internal";
+ readonly code: string;
+ readonly message: string;
+ readonly retryable: boolean;
+ readonly details?: JsonObject;
+}
+
+export type OpenSessionResult<Specs, Id extends BackendId<Specs>> =
+ | {
+ readonly ok: true;
+ readonly session: AgentSession<Specs, Id>;
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+ }
+ | { readonly ok: false; readonly error: AgentDriverError };
+
+export type DeliveryReceipt =
+ | {
+ readonly status: "accepted";
+ readonly delivery: "prompt" | "steer";
+ readonly commandId: string;
+ readonly turnId: string;
+ }
+ | {
+ readonly status: "queued";
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+ readonly commandId: string;
+ }
+ | {
+ readonly status: "rejected";
+ readonly reason:
+ | "closed"
+ | "unsupported"
+ | "invalid_input"
+ | "runtime_unavailable"
+ | "already_started"
+ | "not_started"
+ | "duplicate_conflict";
+ readonly error?: AgentDriverError;
+ };
+
+export type InterruptResult =
+ | { readonly status: "accepted"; readonly requestId: string; readonly turnId: string }
+ | { readonly status: "not_running" }
+ | { readonly status: "unsupported" }
+ | { readonly status: "closed" }
+ | { readonly status: "failed"; readonly error: AgentDriverError };
+
+export interface StopInput {
+ readonly reason: "owner_request" | "idle_timeout" | "stalled" | "shutdown" | "reset";
+ readonly forceAfterMs: number;
+}
+
+export type StopReceipt =
+ | { readonly status: "accepted"; readonly requestId: string }
+ | { readonly status: "already_stopping"; readonly requestId: string }
+ | { readonly status: "closed"; readonly result: AgentSessionResult }
+ | { readonly status: "failed"; readonly error: AgentDriverError };
+
+export type HostCleanupResult =
+ | { readonly status: "not_acquired" }
+ | { readonly status: "released" }
+ | { readonly status: "failed"; readonly error: AgentDriverError }
+ | { readonly status: "timed_out"; readonly error: AgentDriverError };
+
+export type AgentSessionResult =
+ | {
+ readonly outcome: "stopped";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly exitCode?: number | null;
+ readonly signal?: string | null;
+ readonly cleanup: HostCleanupResult;
+ }
+ | {
+ readonly outcome: "crashed";
+ readonly requested: false;
+ readonly backendSessionId?: string;
+ readonly exitCode: number | null;
+ readonly signal: string | null;
+ readonly error?: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+ }
+ | {
+ readonly outcome: "failed_to_start";
+ readonly requested: false;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+ }
+ | {
+ readonly outcome: "forced";
+ readonly requested: true;
+ readonly backendSessionId?: string;
+ readonly error: AgentDriverError;
+ readonly cleanup: HostCleanupResult;
+ };
+
+export type AgentTurnResult =
+ | { readonly outcome: "success"; readonly backendSessionId: string }
+ | { readonly outcome: "interrupted"; readonly backendSessionId?: string }
+ | { readonly outcome: "failed"; readonly backendSessionId?: string; readonly error: AgentDriverError };
+
+export interface TokenUsage {
+ readonly inputTokens?: number;
+ readonly cachedInputTokens?: number;
+ readonly outputTokens?: number;
+ readonly reasoningTokens?: number;
+ readonly totalTokens?: number;
+}
+
+export type CoreAgentEventPayload =
+ | { readonly type: "session_started"; readonly backendSessionId: string }
+ | {
+ readonly type: "command_queued";
+ readonly commandId: string;
+ readonly reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+ }
+ | {
+ readonly type: "command_accepted";
+ readonly commandId: string;
+ readonly turnId: string;
+ readonly delivery: "prompt" | "steer";
+ }
+ | {
+ readonly type: "command_failed";
+ readonly commandId: string;
+ readonly turnId?: string;
+ readonly error: AgentDriverError;
+ }
+ | { readonly type: "turn_started"; readonly turnId: string; readonly commandIds: readonly string[] }
+ | { readonly type: "thinking_delta"; readonly turnId: string; readonly text: string }
+ | { readonly type: "text_delta"; readonly turnId: string; readonly text: string }
+ | {
+ readonly type: "tool_started";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly input: JsonValue;
+ }
+ | {
+ readonly type: "tool_finished";
+ readonly turnId: string;
+ readonly callId?: string;
+ readonly name: string;
+ readonly output?: JsonValue;
+ }
+ | { readonly type: "compaction_started"; readonly turnId: string }
+ | { readonly type: "compaction_finished"; readonly turnId: string }
+ | { readonly type: "review_started"; readonly turnId: string }
+ | { readonly type: "review_finished"; readonly turnId: string }
+ | {
+ readonly type: "internal_progress";
+ readonly turnId?: string;
+ readonly source?: string;
+ readonly itemType?: string;
+ readonly payloadBytes?: number;
+ }
+ | {
+ readonly type: "diagnostic";
+ readonly turnId?: string;
+ readonly severity: "debug" | "info" | "warning" | "error";
+ readonly source?: string;
+ readonly message: string;
+ }
+ | {
+ readonly type: "token_usage";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly usage: TokenUsage;
+ readonly details: JsonObject;
+ }
+ | {
+ readonly type: "rate_limits";
+ readonly turnId?: string;
+ readonly source: string;
+ readonly details: JsonObject;
+ }
+ | {
+ readonly type: "turn_completed";
+ readonly turnId: string;
+ readonly commandIds: readonly string[];
+ readonly result: AgentTurnResult;
+ }
+ | { readonly type: "session_failed"; readonly error: AgentDriverError }
+ | { readonly type: "session_closed"; readonly result: AgentSessionResult };
+
+export interface AgentEventEnvelope {
+ readonly sequence: number;
+ readonly sessionInstanceId: string;
+ readonly at: number;
+}
+
+export type AgentEvent<Specs, Id extends BackendId<Specs>> =
+ AgentEventEnvelope & (CoreAgentEventPayload | ExtraEventOf<Specs, Id>);
+
+export interface AgentSessionSnapshot {
+ readonly sessionInstanceId: string;
+ readonly state:
+ | "new"
+ | "awaiting_first_message"
+ | "starting"
+ | "idle"
+ | "working"
+ | "stopping"
+ | "closed";
+ readonly backendSessionId?: string;
+ readonly activeTurn?: { readonly turnId: string; readonly commandIds: readonly string[] };
+ readonly queuedCommands: readonly {
+ readonly commandId: string;
+ readonly kind: AgentMessage["kind"];
+ }[];
+ readonly lastEventSequence: number;
+ readonly diagnostics: {
+ readonly deliveryPhase:
+ | "idle"
+ | "admission_wait"
+ | "steering"
+ | "next_turn_queued"
+ | "compacting"
+ | "reviewing"
+ | "tool_wait"
+ | "working";
+ readonly metrics: {
+ readonly physicalOpenCount: number;
+ readonly turnCount: number;
+ readonly commandAdmissionCount: number;
+ readonly commandAdmissionLatencyTotalMs: number;
+ readonly queueDwellCount: number;
+ readonly queueDwellTotalMs: number;
+ readonly sseReconnectCount: number;
+ readonly resumeOutcome: "not_requested" | "pending" | "resumed" | "reset_required" | "failed";
+ readonly terminalOwnerKind:
+ | "transport_request"
+ | "vendor_message"
+ | "prompt_invocation"
+ | "lane_generation";
+ };
+ };
+}
+
+export interface AgentEventStream<Event> extends AsyncIterable<Event> {
+ readonly maxBufferedBytes: 4_194_304;
+}
+
+export type ExtensionNames<Specs, Id extends BackendId<Specs>> = Extract<keyof ExtensionsOf<Specs, Id>, string>;
+export type ExtensionInput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> =
+ ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer Input, infer _Output>
+ ? Input
+ : never;
+export type ExtensionOutput<Specs, Id extends BackendId<Specs>, Name extends ExtensionNames<Specs, Id>> =
+ ExtensionsOf<Specs, Id>[Name] extends BackendExtensionSpec<infer _Input, infer Output>
+ ? Output
+ : never;
+
+export type ExtensionResult<Output> =
+ | { readonly ok: true; readonly value: Output }
+ | { readonly ok: false; readonly error: AgentDriverError };
+
+export interface AgentSession<Specs, Id extends BackendId<Specs>> {
+ readonly backend: Id;
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+ readonly sessionInstanceId: string;
+ readonly events: AgentEventStream<AgentEvent<Specs, Id>>;
+ readonly closed: Promise<AgentSessionResult>;
+ start(message: AgentMessage): Promise<DeliveryReceipt>;
+ send(message: AgentMessage): Promise<DeliveryReceipt>;
+ interrupt(input: { readonly requestId: string; readonly reason: string }): Promise<InterruptResult>;
+ stop(input: StopInput): Promise<StopReceipt>;
+ snapshot(): AgentSessionSnapshot;
+ invokeExtension<Name extends ExtensionNames<Specs, Id>>(
+ name: Name,
+ input: ExtensionInput<Specs, Id, Name>,
+ ): Promise<ExtensionResult<ExtensionOutput<Specs, Id, Name>>>;
+}
+
+export interface ProbeInput<Specs, Id extends BackendId<Specs>> {
+ readonly backend: Id;
+ readonly command?: string;
+}
+
+export type BackendProbe<Capabilities> =
+ | { readonly status: "healthy"; readonly version?: string; readonly capabilities: Capabilities }
+ | { readonly status: "unhealthy"; readonly error: AgentDriverError; readonly capabilities: Capabilities };
+
+export interface OpenSessionInput<Specs, Id extends BackendId<Specs>> {
+ readonly backend: Id;
+ readonly launch: AgentLaunchContext;
+ readonly config: ConfigOf<Specs, Id>;
+}
+
+export interface AgentDriverSdk<Specs = BuiltinBackendSpecs> {
+ readonly backendIds: readonly BackendId<Specs>[];
+ probe<Id extends BackendId<Specs>>(
+ input: ProbeInput<Specs, Id>,
+ ): Promise<BackendProbe<CapabilitiesOf<Specs, Id>>>;
+ open<Id extends BackendId<Specs>>(
+ input: OpenSessionInput<Specs, Id>,
+ ): Promise<OpenSessionResult<Specs, Id>>;
+}
+
+export interface PrepareExecutionInput {
+ readonly backend: string;
+ readonly launchId: string;
+ readonly workingDirectory: string;
+}
+
+export type PrepareExecutionResult =
+ | { readonly ok: true; readonly resource: PreparedExecutionResource }
+ | { readonly ok: false; readonly error: AgentDriverError };
+
+export interface RawOutputEvent {
+ readonly backend: string;
+ readonly launchId: string;
+ readonly stream: "stdout" | "stderr";
+ readonly text: string;
+}
+
+export interface PreparedExecutionResource {
+ readonly environmentLayers: Readonly<Record<
+ "base" | "hostStatic" | "identityProtected" | "platformProtected" |
+ "runtimeProtected" | "networkProtected" | "credentialSensitive",
+ Readonly<Record<string, string | undefined>>
+ >>;
+ readonly executablePath?: string;
+ release(input: {
+ readonly reason: "normal" | "failed_start" | "crash" | "requested_stop" | "consumer_closed";
+ readonly signal: AbortSignal;
+ readonly deadlineAt: number;
+ }): Promise<void>;
+}
+
+export interface AgentDriverHost {
+ prepareExecution(input: PrepareExecutionInput): Promise<PrepareExecutionResult>;
+ onRawOutput(event: RawOutputEvent): void;
+ now(): number;
+ createId(): string;
+}
+
+export interface DefaultAgentDriverHostOptions {
+ readonly environment?: Readonly<Record<string, string | undefined>>;
+ readonly onRawOutput?: (event: RawOutputEvent) => void;
+}
+
+export interface CreateAgentDriverSdkOptions {
+ readonly host?: AgentDriverHost;
+ readonly hostReleaseTimeoutMs?: number;
+}
diff --git a/src/daemon/agent-driver/src/controller/event-queue.test.ts b/src/daemon/agent-driver/src/controller/event-queue.test.ts
new file mode 100644
index 000000000..91f968fe6
--- /dev/null
+++ b/src/daemon/agent-driver/src/controller/event-queue.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it, vi } from "vitest";
+import { BufferedEventQueue } from "./event-queue.js";
+
+describe("BufferedEventQueue", () => {
+ it("preserves event boundaries and FIFO order", async () => {
+ const queue = new BufferedEventQueue<Record<string, unknown>>(() => {}, () => {});
+ queue.push({ type: "one", text: "a" });
+ queue.push({ type: "two", text: "b" });
+ queue.close();
+ const observed: Array<Record<string, unknown>> = [];
+ for await (const event of queue.stream) observed.push(event);
+ expect(observed).toEqual([{ type: "one", text: "a" }, { type: "two", text: "b" }]);
+ });
+
+ it("rejects a second iterator", () => {
+ const queue = new BufferedEventQueue(() => {}, () => {});
+ queue.stream[Symbol.asyncIterator]();
+ expect(() => queue.stream[Symbol.asyncIterator]()).toThrow("one consumer");
+ });
+
+ it("initiates consumer cleanup from iterator.return", async () => {
+ const onClosed = vi.fn();
+ const queue = new BufferedEventQueue(onClosed, () => {});
+ const iterator = queue.stream[Symbol.asyncIterator]();
+ await iterator.return?.();
+ await iterator.return?.();
+ expect(onClosed).toHaveBeenCalledOnce();
+ });
+
+ it("fails closed on overflow while retaining the reserved terminal event", async () => {
+ const overflow = vi.fn();
+ const queue = new BufferedEventQueue<{ type: string; text: string }>(() => {}, overflow);
+ expect(queue.push({ type: "oversized", text: "x".repeat(queue.stream.maxBufferedBytes) })).toBe(false);
+ expect(overflow).toHaveBeenCalledOnce();
+ expect(queue.push({ type: "another", text: "x" })).toBe(false);
+ expect(overflow).toHaveBeenCalledOnce();
+ expect(queue.push({ type: "session_closed", text: "terminal" }, true)).toBe(true);
+ queue.close();
+ const iterator = queue.stream[Symbol.asyncIterator]();
+ expect(await iterator.next()).toEqual({ done: false, value: { type: "session_closed", text: "terminal" } });
+ expect(await iterator.next()).toEqual({ done: true, value: undefined });
+ });
+});
diff --git a/src/daemon/agent-driver/src/controller/event-queue.ts b/src/daemon/agent-driver/src/controller/event-queue.ts
new file mode 100644
index 000000000..8354f3f45
--- /dev/null
+++ b/src/daemon/agent-driver/src/controller/event-queue.ts
@@ -0,0 +1,75 @@
+import type { AgentEventStream } from "../contract.js";
+
+const MAX_BUFFERED_BYTES = 4_194_304 as const;
+
+interface Waiter<Event> {
+ resolve(value: IteratorResult<Event>): void;
+}
+
+export class BufferedEventQueue<Event> {
+ private readonly queued: Array<{ event: Event; bytes: number }> = [];
+ private readonly waiters: Waiter<Event>[] = [];
+ private bufferedBytes = 0;
+ private iteratorCreated = false;
+ private consumerClosed = false;
+ private overflowed = false;
+ private ended = false;
+
+ constructor(
+ private readonly onConsumerClosed: () => void,
+ private readonly onOverflow: () => void,
+ ) {}
+
+ readonly stream: AgentEventStream<Event> = {
+ maxBufferedBytes: MAX_BUFFERED_BYTES,
+ [Symbol.asyncIterator]: () => this.createIterator(),
+ };
+
+ push(event: Event, terminal = false): boolean {
+ if (this.ended) return false;
+ if (this.overflowed && !terminal) return false;
+ const waiter = this.waiters.shift();
+ if (waiter) {
+ waiter.resolve({ done: false, value: event });
+ return true;
+ }
+ const bytes = Buffer.byteLength(JSON.stringify(event), "utf8");
+ if (!terminal && this.bufferedBytes + bytes > MAX_BUFFERED_BYTES) {
+ this.overflowed = true;
+ this.onOverflow();
+ return false;
+ }
+ this.queued.push({ event, bytes });
+ this.bufferedBytes += bytes;
+ return true;
+ }
+
+ close(): void {
+ if (this.ended) return;
+ this.ended = true;
+ for (const waiter of this.waiters.splice(0)) waiter.resolve({ done: true, value: undefined });
+ }
+
+ private createIterator(): AsyncIterator<Event> {
+ if (this.iteratorCreated) throw new Error("AgentEventStream supports one consumer");
+ this.iteratorCreated = true;
+ return {
+ next: () => {
+ const item = this.queued.shift();
+ if (item) {
+ this.bufferedBytes -= item.bytes;
+ return Promise.resolve({ done: false as const, value: item.event });
+ }
+ if (this.ended) return Promise.resolve({ done: true as const, value: undefined });
+ return new Promise<IteratorResult<Event>>((resolve) => this.waiters.push({ resolve }));
+ },
+ return: async () => {
+ if (!this.consumerClosed) {
+ this.consumerClosed = true;
+ this.onConsumerClosed();
+ }
+ return { done: true, value: undefined };
+ },
+ };
+ }
+}
diff --git a/src/daemon/agent-driver/src/controller/logical-session.test.ts b/src/daemon/agent-driver/src/controller/logical-session.test.ts
new file mode 100644
index 000000000..0dc9d06ed
--- /dev/null
+++ b/src/daemon/agent-driver/src/controller/logical-session.test.ts
@@ -0,0 +1,1817 @@
+import { EventEmitter } from "node:events";
+import { mkdtempSync, readFileSync, lstatSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { PassThrough } from "node:stream";
+import { describe, expect, it, vi } from "vitest";
+import type { ChildProcess } from "node:child_process";
+import type {
+ AgentDriverError,
+ AgentEvent,
+ BuiltinBackendId,
+ BuiltinBackendSpecs,
+ ConfigOf,
+ PreparedExecutionResource,
+} from "../contract.js";
+import type {
+ BackendAdapter, BackendExecution, AdapterLaunchContext, AdapterEvent, LaneAdmission, LaneSendInput,
+ LaneStartInput, RuntimeLane, RuntimeLaneEventMap, RuntimeLaneOpenOptions,
+} from "../internal/adapter.js";
+import { createFakeAgentDriverHost } from "../testing/fake-host.js";
+import { runAgentDriverConformance } from "../testing/conformance.js";
+import { LogicalAgentSession } from "./logical-session.js";
+import { createProcessLane, ProcessLane } from "./process-host.js";
+import { SdkLane } from "./sdk-host.js";
+import { capabilitiesFor } from "../registry.js";
+
+const configs: Record<BuiltinBackendId, unknown> = {
+ claude: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default" },
+ codex: { model: { kind: "default" }, mode: "default" },
+ cursor: { model: { kind: "default" } },
+ opencode: { model: { kind: "default" } },
+ pi: { model: { kind: "default" }, provider: { kind: "default" } },
+};
+
+class FakeDriver implements BackendAdapter {
+ readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
+ readonly currentSessionId = null;
+ readonly processes: Array<ChildProcess & { stdout: PassThrough; stderr: PassThrough; stdin: PassThrough }> = [];
+ readonly spawnContexts: AdapterLaunchContext[] = [];
+ readonly writes: string[] = [];
+ lane?: SdkLane;
+ sdkHandle?: {
+ isStreaming: boolean;
+ prompt: ReturnType<typeof vi.fn>;
+ steer: ReturnType<typeof vi.fn>;
+ abort: ReturnType<typeof vi.fn>;
+ dispose: ReturnType<typeof vi.fn>;
+ };
+ failSpawn?: Error;
+ failPrompt?: Error;
+ failAbort?: Error;
+ failDispose?: Error;
+ rejectWrites = false;
+ hangDispose = false;
+ spawnGate?: Promise<void>;
+ sdkOpenGate?: Promise<void>;
+ laneOverride?: RuntimeLane;
+ promptAdmissionTimeoutMs?: number;
+ beginTurn: (() => string) | undefined = () => {
+ this.currentTerminalOwner = `${this.id}:test:${++this.terminalSequence}`;
+ return this.currentTerminalOwner;
+ };
+ private terminalSequence = 0;
+ currentTerminalOwner?: string;
+
+ constructor(readonly id: BuiltinBackendId, readonly execution: BackendExecution) {}
+ probe() { return { status: "healthy" as const }; }
+ async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {
+ if (this.laneOverride) return this.laneOverride;
+ if (this.execution.transport.kind === "in_process_sdk") return this.createSdkLane(ctx);
+ return createProcessLane(this, ctx, {
+ onRawStdoutLine: options?.onRawStdoutLine,
+ stopAfterTurn: this.id === "opencode",
+ promptAdmissionTimeoutMs: this.promptAdmissionTimeoutMs,
+ });
+ }
+ async spawn(ctx: AdapterLaunchContext) {
+ await this.spawnGate;
+ if (this.failSpawn) throw this.failSpawn;
+ this.spawnContexts.push(ctx);
+ const proc = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ stdin: new PassThrough(),
+ pid: undefined,
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn(() => true),
+ }) as unknown as ChildProcess & { stdout: PassThrough; stderr: PassThrough; stdin: PassThrough };
+ this.processes.push(proc);
+ return { process: proc };
+ }
+ async createSdkLane(_ctx: AdapterLaunchContext): Promise<SdkLane> {
+ await this.sdkOpenGate;
+ const handle = {
+ isStreaming: false,
+ prompt: vi.fn(async () => {
+ if (this.failPrompt) throw this.failPrompt;
+ }),
+ steer: vi.fn(async () => {}),
+ abort: vi.fn(async () => {
+ if (this.failAbort) throw this.failAbort;
+ }),
+ dispose: vi.fn(() => {
+ if (this.failDispose) return Promise.reject(this.failDispose);
+ return this.hangDispose ? new Promise<void>(() => {}) : Promise.resolve();
+ }),
+ };
+ this.sdkHandle = handle;
+ this.lane = new SdkLane(handle, "sdk-session");
+ return this.lane;
+ }
+ normalizeLine(line: string): AdapterEvent[] { return [JSON.parse(line) as AdapterEvent]; }
+ encodeMessage(text: string): string {
+ this.writes.push(text);
+ return this.rejectWrites ? "" : text;
+ }
+}
+
+class ControlledRuntimeLane implements RuntimeLane {
+ readonly currentSessionId = null;
+ readonly events = new EventEmitter();
+ startAdmission: LaneAdmission = { ok: true, acceptedAs: "prompt", receipt: "claude:test:1" };
+ sendAdmission: LaneAdmission = { ok: true, acceptedAs: "prompt", receipt: "claude:test:2" };
+ startPromise?: Promise<LaneAdmission>;
+ sendPromise?: Promise<LaneAdmission>;
+ sendImpl?: (input: LaneSendInput) => Promise<LaneAdmission>;
+ onStart?: (input: LaneStartInput) => void;
+ onSend?: (input: LaneSendInput) => void;
+ readonly stop = vi.fn(async () => {});
+ readonly interrupt = vi.fn(async () => false);
+
+ on<K extends keyof RuntimeLaneEventMap>(
+ event: K,
+ listener: (value: RuntimeLaneEventMap[K]) => void,
+ ): void {
+ this.events.on(event, listener);
+ }
+ start(input: LaneStartInput): Promise<LaneAdmission> {
+ this.onStart?.(input);
+ return this.startPromise ?? Promise.resolve(this.startAdmission);
+ }
+ send(input: LaneSendInput): Promise<LaneAdmission> {
+ this.onSend?.(input);
+ if (this.sendImpl) return this.sendImpl(input);
+ return this.sendPromise ?? Promise.resolve(this.sendAdmission);
+ }
+ emit(event: AdapterEvent): void {
+ this.events.emit("runtime_event", event);
+ }
+}
+
+function deferred(): { promise: Promise<void>; resolve: () => void } {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+function deferredValue<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+function executionFor(backend: BuiltinBackendId): BackendExecution {
+ if (backend === "opencode") {
+ return {
+ lifetime: "session",
+ transport: { kind: "http_sse", protocol: "opencode.test.v2" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ };
+ }
+ if (backend === "cursor") {
+ return {
+ lifetime: "session",
+ transport: { kind: "stdio_rpc", protocol: "cursor.test.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ };
+ }
+ return backend === "pi"
+ ? {
+ lifetime: "session",
+ transport: { kind: "in_process_sdk", protocol: "pi.test.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "prompt_invocation",
+ }
+ : {
+ lifetime: "session",
+ transport: { kind: "stdio_stream", protocol: `${backend}.test.v1` },
+ wakeStart: "immediate",
+ terminalOwnership: "vendor_message",
+ };
+}
+
+function makeSession<Id extends BuiltinBackendId>(
+ backend: Id,
+ options: {
+ prepared?: PreparedExecutionResource;
+ timeout?: number;
+ resumeSessionId?: string;
+ workingDirectory?: string;
+ instructions?: string;
+ execution?: BackendExecution;
+ lane?: RuntimeLane;
+ authoritativeOwner?: boolean;
+ promptAdmissionTimeoutMs?: number;
+ now?: () => number;
+ } = {},
+) {
+ const driver = new FakeDriver(backend, options.execution ?? executionFor(backend));
+ driver.laneOverride = options.lane;
+ driver.promptAdmissionTimeoutMs = options.promptAdmissionTimeoutMs;
+ if (options.authoritativeOwner) driver.beginTurn = undefined;
+ const baseHost = createFakeAgentDriverHost(options.prepared);
+ const host = options.now ? { ...baseHost, now: options.now } : baseHost;
+ const prepared: PreparedExecutionResource = {
+ environmentLayers: {
+ base: {}, hostStatic: {}, identityProtected: {}, platformProtected: {},
+ runtimeProtected: {}, networkProtected: {}, credentialSensitive: {},
+ },
+ async release(input) { host.releases.push(input); },
+ ...options.prepared,
+ };
+ const session = new LogicalAgentSession<BuiltinBackendSpecs, Id>(
+ backend,
+ configs[backend] as never,
+ {
+ workingDirectory: options.workingDirectory ?? process.cwd(),
+ instructions: options.instructions ?? "",
+ launchId: `launch-${backend}`,
+ resumeSessionId: options.resumeSessionId,
+ },
+ driver as unknown as BackendAdapter<Id, ConfigOf<BuiltinBackendSpecs, Id>>,
+ capabilitiesFor(backend),
+ host,
+ prepared,
+ options.timeout ?? 100,
+ );
+ return { session, driver, host };
+}
+
+async function emit(driver: FakeDriver, event: AdapterEvent): Promise<void> {
+ emitNow(driver, event);
+ await Promise.resolve();
+}
+
+function emitNow(driver: FakeDriver, event: AdapterEvent): void {
+ const ownedEvent = event.kind === "turn_end" && !event.turnOwner && driver.currentTerminalOwner
+ ? { ...event, turnOwner: driver.currentTerminalOwner }
+ : event;
+ if (driver.id === "pi") driver.lane!.emitEvents([ownedEvent]);
+ else driver.processes.at(-1)!.stdout.write(`${JSON.stringify(ownedEvent)}\n`);
+}
+
+async function take(
+ iterator: AsyncIterator<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>>,
+ count: number,
+) {
+ const events: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ while (events.length < count) {
+ const next = await iterator.next();
+ if (next.done) break;
+ events.push(next.value);
+ }
+ return events;
+}
+
+describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)("%s logical-session conformance", (backend) => {
+ it("passes the exported black-box conformance suite", async () => {
+ const { session, driver } = makeSession(backend);
+ await runAgentDriverConformance(async () => ({
+ session,
+ async completeFirstTurn() {
+ await emit(driver, { kind: "turn_end", sessionId: `${backend}-session` });
+ if (driver.execution.lifetime === "turn") {
+ driver.processes[0].emit("exit", 0, null);
+ await Promise.resolve();
+ }
+ },
+ }));
+ });
+
+ it("rejects send-before-start, preserves idempotency, and rejects a second start", async () => {
+ const { session } = makeSession(backend);
+ expect(await session.send({ id: "early", kind: "user", text: "early" })).toEqual({ status: "rejected", reason: "not_started" });
+ const first = session.start({ id: "one", kind: "user", text: "hello" });
+ const duplicate = session.start({ id: "one", kind: "user", text: "hello" });
+ expect(await duplicate).toEqual(await first);
+ expect(await session.start({ id: "two", kind: "user", text: "again" })).toEqual({ status: "rejected", reason: "already_started" });
+ expect(await session.send({ id: "one", kind: "user", text: "different" })).toEqual({ status: "rejected", reason: "duplicate_conflict" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("attaches the iterator before start and loses no normalized event", async () => {
+ const { session, driver } = makeSession(backend);
+ const iterator = session.events[Symbol.asyncIterator]() as AsyncIterator<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>>;
+ const pending = take(iterator, 5);
+ await session.start({ id: "one", kind: "user", text: "hello" });
+ await emit(driver, { kind: "session_init", sessionId: backend === "pi" ? "sdk-session" : `${backend}-session` });
+ await emit(driver, { kind: "thinking", text: "think" });
+ await emit(driver, { kind: "text", text: "answer" });
+ const events = await pending;
+ expect(events.map((event) => event.type)).toEqual([
+ "command_accepted", "turn_started", "session_started", "thinking_delta", "text_delta",
+ ]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+});
+
+describe("runtime-lane admission state machine", () => {
+ it("rejects a lane start without ever publishing command acceptance", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: false, reason: "vendor_rejected" };
+ const { session, host } = makeSession("claude", { lane });
+ const iterator = session.events[Symbol.asyncIterator]();
+
+ await expect(session.start({ id: "one", kind: "user", text: "start" })).resolves.toMatchObject({
+ status: "rejected",
+ reason: "runtime_unavailable",
+ });
+ await expect(session.closed).resolves.toMatchObject({ outcome: "failed_to_start" });
+ const events = await take(iterator as never, 99);
+ expect(events.some((event) => event.type === "command_accepted" || event.type === "turn_started")).toBe(false);
+ expect(events.find((event) => event.type === "command_failed")).toMatchObject({
+ commandId: "one",
+ error: { code: "failed_to_start" },
+ });
+ expect(lane.stop).toHaveBeenCalledOnce();
+ expect(host.releases).toHaveLength(1);
+ });
+
+ it.each(["reset_required", "incompatible_configuration"] as const)(
+ "preserves structured %s admission failures for reset and configuration UX",
+ async (reason) => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: false, reason, error: `Cursor ACP ${reason}` };
+ const { session } = makeSession("cursor", { lane, resumeSessionId: "legacy-session" });
+ const iterator = session.events[Symbol.asyncIterator]();
+
+ await expect(session.start({ id: "one", kind: "user", text: "start" })).resolves.toMatchObject({
+ status: "rejected",
+ reason: "runtime_unavailable",
+ error: { category: "configuration", code: reason, retryable: false },
+ });
+ await expect(session.closed).resolves.toMatchObject({
+ outcome: "failed_to_start",
+ error: { category: "configuration", code: reason, retryable: false },
+ });
+ const events = await take(iterator as never, 99);
+ expect(events.find((event) => event.type === "command_failed")).toMatchObject({
+ error: { category: "configuration", code: reason, retryable: false },
+ });
+ },
+ );
+
+ it("fails a silent authoritative admission without publishing acceptance and stops its process", async () => {
+ vi.useFakeTimers();
+ try {
+ const { session, driver, host } = makeSession("codex", {
+ authoritativeOwner: true,
+ promptAdmissionTimeoutMs: 25,
+ });
+ const iterator = session.events[Symbol.asyncIterator]();
+ const starting = session.start({ id: "one", kind: "user", text: "start" });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(driver.processes).toHaveLength(1);
+
+ await vi.advanceTimersByTimeAsync(25);
+ await expect(starting).resolves.toMatchObject({
+ status: "rejected",
+ reason: "runtime_unavailable",
+ });
+ await expect(session.closed).resolves.toMatchObject({ outcome: "failed_to_start" });
+ const events = await take(iterator as never, 99);
+ expect(events.some((event) => event.type === "command_accepted" || event.type === "turn_started")).toBe(false);
+ expect(events.find((event) => event.type === "command_failed")).toMatchObject({
+ commandId: "one",
+ error: { code: "failed_to_start" },
+ });
+ expect(events.find((event) => event.type === "session_failed")).toMatchObject({
+ error: { code: "failed_to_start" },
+ });
+ expect(driver.processes[0]!.kill).toHaveBeenCalledOnce();
+ expect(driver.processes[0]!.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(host.releases).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("orders a synchronous matching terminal after acceptance and settles the turn", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.onStart = (input) => {
+ lane.emit({ kind: "session_init", sessionId: "vendor-session" });
+ lane.emit({ kind: "turn_end", sessionId: "vendor-session", turnOwner: input.terminalOwner });
+ };
+ const { session } = makeSession("claude", { lane });
+ const iterator = session.events[Symbol.asyncIterator]();
+
+ await expect(session.start({ id: "one", kind: "user", text: "start" })).resolves.toMatchObject({
+ status: "accepted",
+ commandId: "one",
+ });
+ expect(session.snapshot()).toMatchObject({ state: "idle", activeTurn: undefined });
+ const events = await take(iterator as never, 4);
+ expect(events.map((event) => event.type)).toEqual([
+ "command_accepted",
+ "turn_started",
+ "session_started",
+ "turn_completed",
+ ]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("diagnoses a runtime turn-owner acknowledgement that conflicts with admission", async () => {
+ const lane = new ControlledRuntimeLane();
+ const { session } = makeSession("claude", { lane });
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+
+ lane.emit({ kind: "turn_owner", receipt: "different-owner" });
+ const events = await take(iterator as never, 3);
+ expect(events).toContainEqual(expect.objectContaining({
+ type: "diagnostic",
+ severity: "error",
+ message: "Runtime terminal ownership did not match command admission",
+ }));
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("ignores a forged terminal owner and completes only for the admission receipt", async () => {
+ const lane = new ControlledRuntimeLane();
+ const { session } = makeSession("claude", { lane });
+ const iterator = session.events[Symbol.asyncIterator]();
+ const started = await session.start({ id: "one", kind: "user", text: "start" });
+ expect(started).toMatchObject({ status: "accepted" });
+
+ lane.emit({ kind: "turn_end", sessionId: "vendor-session", turnOwner: "owner-wrong" });
+ await Promise.resolve();
+ expect(session.snapshot().activeTurn).toBeDefined();
+ lane.emit({ kind: "turn_end", sessionId: "vendor-session", turnOwner: "claude:test:1" });
+ await Promise.resolve();
+ expect(session.snapshot()).toMatchObject({ state: "idle", activeTurn: undefined });
+ const events = await take(iterator as never, 4);
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("rejects an idle send on an existing lane without publishing acceptance", async () => {
+ const lane = new ControlledRuntimeLane();
+ const { session } = makeSession("claude", { lane });
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ lane.emit({ kind: "turn_end", turnOwner: "claude:test:1" });
+ await Promise.resolve();
+ lane.sendAdmission = { ok: false, reason: "vendor_rejected" };
+
+ await expect(session.send({ id: "two", kind: "user", text: "next" })).resolves.toMatchObject({
+ status: "rejected",
+ reason: "runtime_unavailable",
+ });
+ await expect(session.closed).resolves.toMatchObject({ outcome: "failed_to_start" });
+ const events = await take(iterator as never, 99);
+ expect(events.filter((event) => event.type === "command_accepted" && event.commandId === "two")).toHaveLength(0);
+ expect(events.find((event) => event.type === "command_failed" && event.commandId === "two")).toMatchObject({
+ error: { code: "failed_to_start" },
+ });
+ expect(lane.stop).toHaveBeenCalledOnce();
+ });
+});
+
+describe("logical delivery diagnostics", () => {
+ it("rejects stale/mismatched admission internals and synchronous FIFO operations", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "opencode:test:1" };
+ const { session } = makeSession("opencode", { lane });
+ await session.start({ id: "one", kind: "user", text: "start" });
+ const internals = session as unknown as {
+ activeTurn: { turnId: string; terminalOwner?: string };
+ acceptTurnAdmission(admission: { turnId: string }, laneAdmission: LaneAdmission): void;
+ enqueueLaneAdmission<T>(operation: () => Promise<T>): Promise<T>;
+ };
+
+ const activeTurn = internals.activeTurn;
+ expect(() => internals.acceptTurnAdmission(
+ { turnId: "stale-turn" },
+ { ok: true, acceptedAs: "prompt", receipt: "stale-owner" },
+ )).toThrow("stale turn");
+ internals.activeTurn = activeTurn;
+ expect(() => internals.acceptTurnAdmission(
+ { turnId: internals.activeTurn.turnId },
+ { ok: true, acceptedAs: "prompt", receipt: "different-owner" },
+ )).toThrow("prepared terminal owner");
+ await expect(internals.enqueueLaneAdmission(() => {
+ throw new Error("synchronous admission failure");
+ })).rejects.toThrow("synchronous admission failure");
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("settles physical and cancellation steering failures exactly once", async () => {
+ const rejectedLane = new ControlledRuntimeLane();
+ rejectedLane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "opencode:test:1" };
+ const physicalFailure = {
+ category: "protocol",
+ code: "structured_steer_failure",
+ message: "steer transport failed",
+ retryable: false,
+ } satisfies AgentDriverError;
+ rejectedLane.sendImpl = async () => { throw physicalFailure; };
+ const rejectedSession = makeSession("opencode", { lane: rejectedLane }).session;
+ const rejectedIterator = rejectedSession.events[Symbol.asyncIterator]();
+ await rejectedSession.start({ id: "one", kind: "user", text: "start" });
+ await expect(rejectedSession.send({ id: "two", kind: "user", text: "steer" })).resolves.toMatchObject({
+ status: "rejected",
+ reason: "runtime_unavailable",
+ error: physicalFailure,
+ });
+ const rejectedEvents = await take(rejectedIterator as never, 3);
+ expect(rejectedEvents.filter((event) => event.type === "command_failed" && event.commandId === "two"))
+ .toHaveLength(1);
+ await rejectedSession.stop({ reason: "shutdown", forceAfterMs: 10 });
+
+ const plainRejectedLane = new ControlledRuntimeLane();
+ plainRejectedLane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "opencode:test:1" };
+ plainRejectedLane.sendImpl = async () => { throw new Error("plain steer failure"); };
+ const plainRejectedSession = makeSession("opencode", { lane: plainRejectedLane }).session;
+ await plainRejectedSession.start({ id: "one", kind: "user", text: "start" });
+ await expect(plainRejectedSession.send({ id: "two", kind: "user", text: "steer" })).resolves.toMatchObject({
+ status: "rejected",
+ reason: "runtime_unavailable",
+ error: { category: "process", code: "delivery_failed" },
+ });
+ await plainRejectedSession.stop({ reason: "shutdown", forceAfterMs: 10 });
+
+ const cancelledLane = new ControlledRuntimeLane();
+ cancelledLane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "opencode:test:1" };
+ cancelledLane.sendPromise = new Promise<LaneAdmission>(() => {});
+ const { session: cancelledSession } = makeSession("opencode", { lane: cancelledLane });
+ const cancelledIterator = cancelledSession.events[Symbol.asyncIterator]();
+ await cancelledSession.start({ id: "one", kind: "user", text: "start" });
+ const sending = cancelledSession.send({ id: "two", kind: "user", text: "steer" });
+ const cancelledInternals = cancelledSession as unknown as {
+ steeringDeliveries: Set<{ cancel(error: AgentDriverError): void }>;
+ };
+ await vi.waitFor(() => expect(cancelledInternals.steeringDeliveries.size).toBe(1));
+ const cancellationFailure = {
+ category: "cancelled",
+ code: "structured_external_cancellation",
+ message: "external cancellation",
+ retryable: false,
+ } satisfies AgentDriverError;
+ [...cancelledInternals.steeringDeliveries][0]!.cancel(cancellationFailure);
+ await expect(sending).resolves.toMatchObject({
+ status: "rejected",
+ reason: "runtime_unavailable",
+ error: cancellationFailure,
+ });
+ const cancelledEvents = await take(cancelledIterator as never, 3);
+ expect(cancelledEvents.filter((event) => event.type === "command_failed" && event.commandId === "two"))
+ .toHaveLength(1);
+ await cancelledSession.stop({ reason: "shutdown", forceAfterMs: 10 });
+
+ const plainCancelledLane = new ControlledRuntimeLane();
+ plainCancelledLane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "opencode:test:1" };
+ plainCancelledLane.sendPromise = new Promise<LaneAdmission>(() => {});
+ const plainCancelledSession = makeSession("opencode", { lane: plainCancelledLane }).session;
+ await plainCancelledSession.start({ id: "one", kind: "user", text: "start" });
+ const plainSending = plainCancelledSession.send({ id: "two", kind: "user", text: "steer" });
+ const plainCancelledInternals = plainCancelledSession as unknown as {
+ steeringDeliveries: Set<{ cancel(error: unknown): void }>;
+ };
+ await vi.waitFor(() => expect(plainCancelledInternals.steeringDeliveries.size).toBe(1));
+ [...plainCancelledInternals.steeringDeliveries][0]!.cancel(new Error("plain cancellation"));
+ await expect(plainSending).resolves.toMatchObject({
+ status: "rejected",
+ reason: "runtime_unavailable",
+ error: { category: "process", code: "delivery_failed" },
+ });
+ await plainCancelledSession.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("uses deterministic precedence and cumulative count/total-ms metrics from logical-session facts", async () => {
+ let now = 100;
+ const lane = new ControlledRuntimeLane();
+ const startGate = deferredValue<LaneAdmission>();
+ lane.startPromise = startGate.promise;
+ const { session } = makeSession("claude", { lane, now: () => now });
+
+ expect(session.snapshot().diagnostics).toEqual({
+ deliveryPhase: "idle",
+ metrics: {
+ physicalOpenCount: 0,
+ turnCount: 0,
+ commandAdmissionCount: 0,
+ commandAdmissionLatencyTotalMs: 0,
+ queueDwellCount: 0,
+ queueDwellTotalMs: 0,
+ sseReconnectCount: 0,
+ resumeOutcome: "not_requested",
+ terminalOwnerKind: "vendor_message",
+ },
+ });
+
+ const starting = session.start({ id: "one", kind: "user", text: "start" });
+ await Promise.resolve();
+ expect(session.snapshot().diagnostics.deliveryPhase).toBe("admission_wait");
+ now = 110;
+ startGate.resolve({ ok: true, acceptedAs: "prompt", receipt: "claude:test:1" });
+ await starting;
+ expect(session.snapshot().diagnostics).toMatchObject({
+ deliveryPhase: "working",
+ metrics: {
+ physicalOpenCount: 1,
+ turnCount: 1,
+ commandAdmissionCount: 1,
+ commandAdmissionLatencyTotalMs: 10,
+ },
+ });
+
+ lane.emit({ kind: "tool_call", name: "Read", input: {} });
+ expect(session.snapshot().diagnostics.deliveryPhase).toBe("tool_wait");
+ lane.emit({ kind: "review_started" });
+ expect(session.snapshot().diagnostics.deliveryPhase).toBe("reviewing");
+ lane.emit({ kind: "compaction_started" });
+ expect(session.snapshot().diagnostics.deliveryPhase).toBe("compacting");
+ lane.emit({ kind: "compaction_finished" });
+ expect(session.snapshot().diagnostics.deliveryPhase).toBe("reviewing");
+ lane.emit({ kind: "review_finished" });
+ expect(session.snapshot().diagnostics.deliveryPhase).toBe("tool_wait");
+
+ now = 120;
+ expect(await session.send({ id: "two", kind: "user", text: "queued" })).toMatchObject({ status: "queued" });
+ const sendGate = deferredValue<LaneAdmission>();
+ lane.sendPromise = sendGate.promise;
+ now = 135;
+ lane.emit({ kind: "tool_output", name: "Read" });
+ await Promise.resolve();
+ expect(session.snapshot().diagnostics.deliveryPhase).toBe("steering");
+ sendGate.resolve({ ok: true, acceptedAs: "steer", receipt: "claude:test:2" });
+ await vi.waitFor(() => expect(session.snapshot().activeTurn?.commandIds).toEqual(["one", "two"]));
+ lane.emit({ kind: "runtime_metric", name: "sse_reconnect", increment: 1 });
+ const metrics = session.snapshot().diagnostics.metrics;
+ expect(metrics).toMatchObject({
+ physicalOpenCount: 1,
+ turnCount: 1,
+ commandAdmissionCount: 2,
+ commandAdmissionLatencyTotalMs: 25,
+ queueDwellCount: 1,
+ queueDwellTotalMs: 15,
+ sseReconnectCount: 1,
+ });
+ const numericMetrics = Object.values(metrics).filter((value): value is number => typeof value === "number");
+ expect(numericMetrics.every((value) => Number.isFinite(value) && value >= 0)).toBe(true);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("keeps in-flight steering and next-turn FIFO queues above generic work blockers", async () => {
+ const steerLane = new ControlledRuntimeLane();
+ steerLane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "opencode:test:1" };
+ const { session: steerSession } = makeSession("opencode", { lane: steerLane });
+ await steerSession.start({ id: "root", kind: "user", text: "root" });
+ const steerGate = deferredValue<LaneAdmission>();
+ steerLane.sendPromise = steerGate.promise;
+ const steering = steerSession.send({ id: "steer", kind: "user", text: "steer" });
+ await Promise.resolve();
+ expect(steerSession.snapshot().diagnostics.deliveryPhase).toBe("steering");
+ steerGate.resolve({ ok: true, acceptedAs: "steer", receipt: "opencode:test:2" });
+ await steering;
+
+ const queueLane = new ControlledRuntimeLane();
+ queueLane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "cursor:test:1" };
+ const { session: queueSession } = makeSession("cursor", { lane: queueLane });
+ await queueSession.start({ id: "root", kind: "user", text: "root" });
+ queueLane.emit({ kind: "tool_call", name: "Read", input: {} });
+ expect(await queueSession.send({ id: "next", kind: "user", text: "next" })).toMatchObject({ status: "queued" });
+ expect(queueSession.snapshot().diagnostics.deliveryPhase).toBe("next_turn_queued");
+
+ await steerSession.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await queueSession.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("reports exact resume outcomes without exposing vendor payloads", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:1" };
+ lane.onStart = () => lane.emit({ kind: "session_init", sessionId: "resume-exact" });
+ const { session } = makeSession("codex", { lane, resumeSessionId: "resume-exact" });
+ expect(session.snapshot().diagnostics.metrics.resumeOutcome).toBe("pending");
+ await session.start({ id: "one", kind: "user", text: "resume" });
+ expect(session.snapshot().diagnostics.metrics.resumeOutcome).toBe("resumed");
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("cancels serialized in-flight steers at terminal exactly once before admitting the next idle root", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "opencode:test:1" };
+ const { session } = makeSession("opencode", { lane });
+ const events: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ const collecting = (async () => { for await (const event of session.events) events.push(event as never); })();
+ await session.start({ id: "one", kind: "user", text: "one" });
+
+ const sendGate = deferredValue<LaneAdmission>();
+ lane.sendPromise = sendGate.promise;
+ const second = session.send({ id: "two", kind: "user", text: "two" });
+ const third = session.send({ id: "three", kind: "user", text: "three" });
+ await Promise.resolve();
+ lane.emit({ kind: "turn_end", sessionId: "root", turnOwner: "opencode:test:1" });
+ const fourth = session.send({ id: "four", kind: "user", text: "four" });
+ expect(session.snapshot().diagnostics.deliveryPhase).toBe("admission_wait");
+ sendGate.resolve({ ok: true, acceptedAs: "steer", receipt: "opencode:test:2" });
+
+ await expect(second).resolves.toMatchObject({ status: "rejected" });
+ await expect(third).resolves.toMatchObject({ status: "rejected" });
+ await expect(fourth).resolves.toMatchObject({ status: "accepted", commandId: "four" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await collecting;
+ const finals = events.filter((event) => event.type === "command_accepted" || event.type === "command_failed");
+ expect(finals.map((event) => event.commandId)).toEqual(["one", "two", "three", "four"]);
+ for (const id of ["one", "two", "three", "four"]) {
+ expect(finals.filter((event) => event.commandId === id)).toHaveLength(1);
+ }
+ });
+
+ it("reserves a new idle root ahead of busy steer on the session-wide admission FIFO", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "opencode:test:1" };
+ const oldSteerGate = deferredValue<LaneAdmission>();
+ const newRootGate = deferredValue<LaneAdmission>();
+ const newSteerGate = deferredValue<LaneAdmission>();
+ const physical: Array<Pick<LaneSendInput, "mode" | "text">> = [];
+ lane.sendImpl = (input) => {
+ physical.push({ mode: input.mode, text: input.text });
+ if (input.text === "two") return oldSteerGate.promise;
+ if (input.text === "three") return newRootGate.promise;
+ if (input.text === "four") return newSteerGate.promise;
+ throw new Error(`unexpected lane send: ${input.text}`);
+ };
+ const { session } = makeSession("opencode", { lane });
+ const events: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ const collecting = (async () => { for await (const event of session.events) events.push(event as never); })();
+ await session.start({ id: "one", kind: "user", text: "one" });
+
+ const second = session.send({ id: "two", kind: "user", text: "two" });
+ await vi.waitFor(() => expect(physical).toEqual([{ mode: "busy", text: "two" }]));
+ lane.emit({ kind: "turn_end", sessionId: "root", turnOwner: "opencode:test:1" });
+ const third = session.send({ id: "three", kind: "user", text: "three" });
+ const fourth = session.send({ id: "four", kind: "user", text: "four" });
+ await expect(second).resolves.toMatchObject({ status: "rejected" });
+ expect(session.snapshot().diagnostics.deliveryPhase).toBe("admission_wait");
+ expect(physical).toEqual([{ mode: "busy", text: "two" }]);
+
+ oldSteerGate.resolve({ ok: true, acceptedAs: "steer", receipt: "opencode:test:2" });
+ await vi.waitFor(() => expect(physical).toEqual([
+ { mode: "busy", text: "two" },
+ { mode: "idle", text: "three" },
+ ]));
+ expect(physical.some((input) => input.text === "four")).toBe(false);
+
+ newRootGate.resolve({ ok: true, acceptedAs: "prompt", receipt: "opencode:test:2" });
+ await expect(third).resolves.toMatchObject({ status: "accepted", commandId: "three" });
+ await vi.waitFor(() => expect(physical).toEqual([
+ { mode: "busy", text: "two" },
+ { mode: "idle", text: "three" },
+ { mode: "busy", text: "four" },
+ ]));
+ newSteerGate.resolve({ ok: true, acceptedAs: "steer", receipt: "opencode:test:3" });
+ await expect(fourth).resolves.toMatchObject({ status: "accepted", commandId: "four" });
+
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await collecting;
+ const finals = events.filter((event) => event.type === "command_accepted" || event.type === "command_failed");
+ expect(finals.map((event) => event.commandId)).toEqual(["one", "two", "three", "four"]);
+ for (const id of ["one", "two", "three", "four"]) {
+ expect(finals.filter((event) => event.commandId === id)).toHaveLength(1);
+ }
+ });
+});
+
+describe("closed physical-lane tombstone", () => {
+ it("drops every closed per-turn lane tail before it can poison the next turn boundary", async () => {
+ const { session, driver } = makeSession("claude", {
+ execution: {
+ lifetime: "turn",
+ transport: { kind: "one_shot_cli", protocol: "test.one-shot.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "lane_generation",
+ },
+ });
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "a", kind: "user", text: "first" });
+ await emit(driver, { kind: "turn_end", sessionId: "root" });
+ await emit(driver, { kind: "tool_call", name: "late", input: {} });
+ await emit(driver, { kind: "compaction_started" });
+ await emit(driver, { kind: "review_started" });
+ await emit(driver, { kind: "error", message: "late error" });
+ await emit(driver, { kind: "internal_progress", source: "late", itemType: "tail" });
+ driver.processes[0]!.emit("exit", 0, null);
+ await Promise.resolve();
+
+ const second = await session.send({ id: "b", kind: "user", text: "second" });
+ expect(second.status).toBe("accepted");
+ await emit(driver, { kind: "tool_call", name: "current", input: {} });
+ expect(await session.send({ id: "c", kind: "user", text: "third" })).toEqual({
+ status: "queued",
+ reason: "unsafe_boundary",
+ commandId: "c",
+ });
+ await emit(driver, { kind: "tool_output", name: "current" });
+ await vi.waitFor(() => {
+ expect(session.snapshot()).toMatchObject({
+ activeTurn: { commandIds: ["b", "c"] },
+ queuedCommands: [],
+ });
+ });
+
+ const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ while (observed.length < 10) {
+ const next = await iterator.next();
+ if (next.done) break;
+ observed.push(next.value);
+ }
+ expect(observed.filter((event) => event.type === "internal_progress")).toHaveLength(0);
+ expect(observed.filter((event) => event.type === "diagnostic")).toHaveLength(0);
+ expect(observed.filter((event) => event.type === "command_accepted" && event.commandId === "c"))
+ .toHaveLength(1);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("reopens only for proven same-lane root work, re-closes once, and suppresses bare duplicate terminals", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ const receipt = await session.start({ id: "one", kind: "user", text: "start" });
+ expect(receipt).toMatchObject({ status: "accepted" });
+ const turnId = receipt.status === "accepted" ? receipt.turnId : "unreachable";
+
+ await emit(driver, { kind: "turn_end", sessionId: "root-session" });
+ await emit(driver, { kind: "turn_end", sessionId: "root-session" });
+ await emit(driver, {
+ kind: "telemetry",
+ name: "rate_limits",
+ source: "tail-telemetry",
+ attrs: { remaining: 1 },
+ });
+ expect(session.snapshot().activeTurn).toBeUndefined();
+
+ await emit(driver, {
+ kind: "internal_progress",
+ source: "root-owner",
+ itemType: "post-terminal-work",
+ });
+ expect(session.snapshot().activeTurn).toEqual({ turnId, commandIds: ["one"] });
+
+ await emit(driver, { kind: "turn_end", sessionId: "root-session" });
+ await emit(driver, { kind: "turn_end", sessionId: "root-session" });
+ expect(session.snapshot().activeTurn).toBeUndefined();
+
+ const observed = await take(iterator as never, 7);
+ expect(observed.map((event) => event.type)).toEqual([
+ "command_accepted",
+ "turn_started",
+ "session_started",
+ "turn_completed",
+ "rate_limits",
+ "internal_progress",
+ "turn_completed",
+ ]);
+ expect(observed.filter((event) => event.type === "turn_completed")).toHaveLength(2);
+ expect(observed.find((event) => event.type === "internal_progress")).toMatchObject({ turnId });
+ expect(observed.find((event) => event.type === "rate_limits")).toMatchObject({ turnId: undefined });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("rejects a prior receipt after the next turn starts and accepts only the new terminal owner", async () => {
+ const { session, driver } = makeSession("claude");
+ const first = await session.start({ id: "one", kind: "user", text: "first" });
+ const firstOwner = driver.currentTerminalOwner!;
+ await emit(driver, { kind: "turn_end", sessionId: "root", turnOwner: firstOwner });
+ const second = await session.send({ id: "two", kind: "user", text: "second" });
+ const secondOwner = driver.currentTerminalOwner!;
+ await emit(driver, { kind: "turn_end", sessionId: "root", turnOwner: firstOwner });
+ expect(session.snapshot().activeTurn?.turnId).toBe(second.status === "accepted" ? second.turnId : "unreachable");
+ await emit(driver, { kind: "turn_end", sessionId: "root", turnOwner: secondOwner });
+ expect(session.snapshot().activeTurn).toBeUndefined();
+ expect(first.status).toBe("accepted");
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("does not reopen a tombstone for a different physical owner or generation", async () => {
+ const { session, driver } = makeSession("claude");
+ await session.start({ id: "one", kind: "user", text: "first" });
+ await emit(driver, { kind: "turn_end", sessionId: "root" });
+ const reopened = (session as any).reopenClosedLaneForWork(
+ { kind: "text", text: "stale" },
+ new SdkLane({ prompt: async () => {}, steer: async () => {} }, "other"),
+ 99,
+ );
+ expect(reopened).toBeUndefined();
+ expect(session.snapshot().activeTurn).toBeUndefined();
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+});
+
+it("returns not_running when an SDK lane declines interrupt without disturbing the active turn", async () => {
+ const { session } = makeSession("pi");
+ const started = await session.start({ id: "one", kind: "user", text: "first" });
+ expect(await session.interrupt({ requestId: "no-op", reason: "test" })).toEqual({ status: "not_running" });
+ expect(session.snapshot().activeTurn?.turnId).toBe(started.status === "accepted" ? started.turnId : "unreachable");
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+});
+
+describe("backend-owned delivery behavior", () => {
+ it("writes AGENTS.md and the CLAUDE.md alias for non-empty instructions", async () => {
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-instructions-"));
+ try {
+ const { session } = makeSession("claude", { workingDirectory, instructions: "Be useful." });
+ await session.start({ id: "one", kind: "user", text: "start" });
+ expect(readFileSync(join(workingDirectory, "AGENTS.md"), "utf8")).toBe("Be useful.");
+ expect(lstatSync(join(workingDirectory, "CLAUDE.md")).isSymbolicLink()).toBe(true);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ } finally {
+ rmSync(workingDirectory, { recursive: true, force: true });
+ }
+ });
+
+ it.each(["claude", "codex"] as const)("%s queues mid-turn and flushes at a safe boundary", async (backend) => {
+ const { session, driver } = makeSession(backend);
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ expect(await session.send({ id: "two", kind: "user", text: "follow" })).toEqual({ status: "queued", reason: "unsafe_boundary", commandId: "two" });
+ expect(session.snapshot().queuedCommands).toEqual([{ commandId: "two", kind: "user" }]);
+ expect(driver.writes).toEqual([]);
+ await emit(driver, { kind: "compaction_finished" });
+ expect(driver.writes).toEqual(["follow"]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it.each(["claude", "codex"] as const)("%s preserves FIFO and distinct ids for identical queued text", async (backend) => {
+ const { session, driver } = makeSession(backend);
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ expect(await session.send({ id: "same-a", kind: "user", text: "same" })).toMatchObject({ status: "queued" });
+ expect(await session.send({ id: "same-b", kind: "user", text: "same" })).toMatchObject({ status: "queued" });
+ await emit(driver, { kind: "compaction_finished" });
+ expect(driver.writes).toEqual(["same", "same"]);
+ const accepted: string[] = [];
+ while (accepted.length < 2) {
+ const next = await iterator.next();
+ if (next.done) break;
+ if (next.value.type === "command_accepted" && next.value.commandId.startsWith("same-")) {
+ accepted.push(next.value.commandId);
+ }
+ }
+ expect(accepted).toEqual(["same-a", "same-b"]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it.each(["claude", "codex"] as const)("%s flushes a message that arrives at an already-safe boundary", async (backend) => {
+ const { session, driver } = makeSession(backend);
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+
+ expect(await session.send({ id: "two", kind: "user", text: "follow" })).toEqual({
+ status: "queued",
+ reason: "unsafe_boundary",
+ commandId: "two",
+ });
+ await vi.waitFor(() => expect(driver.writes).toEqual(["follow"]));
+ expect(session.snapshot()).toMatchObject({
+ activeTurn: { commandIds: ["one", "two"] },
+ queuedCommands: [],
+ });
+ const events = await take(iterator as never, 4);
+ expect(events.filter((event) => event.type === "command_accepted" && event.commandId === "two"))
+ .toHaveLength(1);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("flushes a safe-boundary message queued while the persistent lane is still starting", async () => {
+ const { session, driver } = makeSession("claude");
+ const gate = deferred();
+ driver.spawnGate = gate.promise;
+ const starting = session.start({ id: "one", kind: "user", text: "start" });
+ await Promise.resolve();
+ expect(await session.send({ id: "two", kind: "user", text: "follow" })).toEqual({
+ status: "queued",
+ reason: "unsafe_boundary",
+ commandId: "two",
+ });
+ gate.resolve();
+ await expect(starting).resolves.toMatchObject({ status: "accepted" });
+ await vi.waitFor(() => expect(driver.writes).toEqual(["follow"]));
+ expect(session.snapshot()).toMatchObject({
+ activeTurn: { commandIds: ["one", "two"] },
+ queuedCommands: [],
+ });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("starts OpenCode immediately and admits later system/user input as FIFO steers", async () => {
+ const { session, driver } = makeSession("opencode");
+ const iterator = session.events[Symbol.asyncIterator]();
+ expect(await session.start({ id: "system-a", kind: "system", text: "a" })).toMatchObject({ status: "accepted", delivery: "prompt" });
+ expect(await session.send({ id: "system-b", kind: "system", text: "b" })).toMatchObject({ status: "accepted", delivery: "steer" });
+ expect(await session.send({ id: "user", kind: "user", text: "go" })).toMatchObject({ status: "accepted", delivery: "steer" });
+ const events = await take(iterator as never, 4);
+ expect(events.filter((event) => event.type === "command_accepted").map((event) => event.commandId))
+ .toEqual(["system-a", "system-b", "user"]);
+ expect(session.snapshot().activeTurn).toMatchObject({ commandIds: ["system-a", "system-b", "user"] });
+ expect(driver.writes).toEqual(["b", "go"]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("derives deferred first-message behavior from the adapter execution declaration", async () => {
+ const { session, driver } = makeSession("cursor", {
+ execution: {
+ lifetime: "turn",
+ transport: { kind: "one_shot_cli", protocol: "test.deferred.v1" },
+ wakeStart: "deferred",
+ terminalOwnership: "lane_generation",
+ },
+ });
+ expect(await session.start({ id: "system", kind: "system", text: "standing" })).toEqual({
+ status: "queued",
+ reason: "waiting_for_message",
+ commandId: "system",
+ });
+ expect(driver.processes).toHaveLength(0);
+ expect(await session.send({ id: "user", kind: "user", text: "go" })).toMatchObject({ status: "accepted" });
+ expect(driver.processes).toHaveLength(1);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("reuses an open SDK lane for the next physical turn", async () => {
+ const { session, driver } = makeSession("pi");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "turn_end", sessionId: "sdk-session" });
+ expect(await session.send({ id: "two", kind: "user", text: "next" })).toMatchObject({
+ status: "accepted",
+ commandId: "two",
+ });
+ expect(driver.sdkHandle!.prompt).toHaveBeenCalledTimes(2);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("reports an adapter interrupt rejection without changing the active turn", async () => {
+ const { session, driver } = makeSession("pi");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ driver.failAbort = new Error("abort rejected");
+ driver.sdkHandle!.isStreaming = true;
+ expect(await session.interrupt({ requestId: "interrupt", reason: "user" })).toMatchObject({
+ status: "failed",
+ error: { code: "interrupt_failed" },
+ });
+ expect(session.snapshot().activeTurn?.commandIds).toEqual(["one"]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("normalizes progress, diagnostics, telemetry, and circular telemetry details", async () => {
+ const { session, driver } = makeSession("pi");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ const circular: Record<string, unknown> = {};
+ circular.self = circular;
+ await emit(driver, { kind: "internal_progress", source: "pi", itemType: "working", payloadBytes: 12 });
+ await emit(driver, { kind: "runtime_diagnostic", severity: "notice", source: "pi", message: "heads up" });
+ await emit(driver, { kind: "telemetry", name: "token_usage", source: "pi", attrs: circular } as never);
+ await emit(driver, { kind: "telemetry", name: "rate_limits", source: "pi", attrs: { remaining: 1 } });
+ const events = await take(iterator as never, 7);
+ expect(events.map((event) => event.type)).toEqual([
+ "command_accepted",
+ "turn_started",
+ "session_started",
+ "internal_progress",
+ "diagnostic",
+ "token_usage",
+ "rate_limits",
+ ]);
+ expect(events[4]).toMatchObject({ severity: "info", message: "heads up" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("forwards process stderr as raw output and a warning diagnostic", async () => {
+ const { session, driver, host } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ driver.processes[0]!.stderr.write("warning text\n");
+ await Promise.resolve();
+ const events = await take(iterator as never, 3);
+ expect(events.at(-1)).toMatchObject({ type: "diagnostic", severity: "warning", message: "warning text" });
+ expect(host.rawOutput.at(-1)).toMatchObject({ stream: "stderr", text: "warning text" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("fails every still-queued command when the session stops", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ await session.send({ id: "two", kind: "user", text: "follow" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ const events = await take(iterator as never, 6);
+ expect(events.filter((event) => event.type === "command_failed")).toMatchObject([
+ { commandId: "two", error: { code: "session_stopping" } },
+ ]);
+ });
+
+ it("emits command_failed for every safe-boundary delivery rejection", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ await session.send({ id: "two", kind: "user", text: "follow two" });
+ await session.send({ id: "three", kind: "user", text: "follow three" });
+ driver.rejectWrites = true;
+ await emit(driver, { kind: "compaction_finished" });
+ const events = await take(iterator as never, 8);
+ expect(events.filter((event) => event.type === "command_failed").map((event) => event.commandId))
+ .toEqual(["two", "three"]);
+ expect(session.snapshot().queuedCommands).toEqual([]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("single-flights same-tick safe boundaries and delivers queued commands exactly once in FIFO order", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ await session.send({ id: "two", kind: "user", text: "follow two" });
+ await session.send({ id: "three", kind: "user", text: "follow three" });
+ emitNow(driver, { kind: "compaction_finished" });
+ emitNow(driver, { kind: "review_finished" });
+ const events = await take(iterator as never, 9);
+ expect(driver.writes).toEqual(["follow two", "follow three"]);
+ expect(events.filter((event) => event.type === "command_accepted").map((event) => event.commandId))
+ .toEqual(["one", "two", "three"]);
+ expect(session.snapshot()).toMatchObject({
+ activeTurn: { commandIds: ["one", "two", "three"] },
+ queuedCommands: [],
+ });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("single-flights same-tick rejected safe boundaries and fails each queued command exactly once", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ await session.send({ id: "two", kind: "user", text: "follow two" });
+ await session.send({ id: "three", kind: "user", text: "follow three" });
+ driver.rejectWrites = true;
+ emitNow(driver, { kind: "compaction_finished" });
+ emitNow(driver, { kind: "review_finished" });
+ const events = await take(iterator as never, 9);
+ expect(driver.writes).toEqual(["follow two", "follow three"]);
+ expect(events.filter((event) => event.type === "command_failed").map((event) => event.commandId))
+ .toEqual(["two", "three"]);
+ expect(session.snapshot()).toMatchObject({
+ activeTurn: { commandIds: ["one"] },
+ queuedCommands: [],
+ });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("cancels an in-flight safe-boundary admission once before a same-tick terminal stop", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ await session.send({ id: "two", kind: "user", text: "follow two" });
+ emitNow(driver, { kind: "compaction_finished" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ const events = await take(iterator as never, 99);
+ const admission = events.filter((event) =>
+ (event.type === "command_accepted" || event.type === "command_failed")
+ && event.commandId === "two"
+ );
+ expect(driver.writes).toEqual(["follow two"]);
+ expect(admission).toMatchObject([{
+ type: "command_failed",
+ commandId: "two",
+ error: { code: "session_stopping" },
+ }]);
+ expect(events.findIndex((event) => event === admission[0]))
+ .toBeLessThan(events.findIndex((event) => event.type === "turn_completed"));
+ expect(events.find((event) => event.type === "turn_completed"))
+ .toMatchObject({ commandIds: ["one"] });
+ expect(events.findIndex((event) => event.type === "turn_completed"))
+ .toBeLessThan(events.findIndex((event) => event.type === "session_closed"));
+ });
+
+ it("keeps stop bounded when a safe-boundary continuation never settles", async () => {
+ const { session } = makeSession("claude");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ Object.assign(session, { safeBoundaryFlush: new Promise<void>(() => {}) });
+ const stopped = await Promise.race([
+ session.stop({ reason: "shutdown", forceAfterMs: 10 }),
+ new Promise<"timed_out">((resolve) => setTimeout(() => resolve("timed_out"), 50)),
+ ]);
+ expect(stopped).toMatchObject({ status: "accepted" });
+ await expect(session.closed).resolves.toMatchObject({ outcome: "stopped" });
+ });
+
+ it("fails an in-flight boundary command before a same-tick turn completion", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ await session.send({ id: "two", kind: "user", text: "follow two" });
+ emitNow(driver, { kind: "compaction_finished" });
+ emitNow(driver, { kind: "turn_end" });
+ const events = await take(iterator as never, 7);
+ const admission = events.filter((event) =>
+ (event.type === "command_accepted" || event.type === "command_failed")
+ && event.commandId === "two"
+ );
+ expect(driver.writes).toEqual(["follow two"]);
+ expect(admission).toMatchObject([{
+ type: "command_failed",
+ commandId: "two",
+ error: { code: "turn_completed_before_command_acceptance" },
+ }]);
+ expect(events.findIndex((event) => event === admission[0]))
+ .toBeLessThan(events.findIndex((event) => event.type === "turn_completed"));
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("settles a rejected in-flight boundary command once before same-tick turn completion", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ await session.send({ id: "two", kind: "user", text: "follow two" });
+ driver.rejectWrites = true;
+ emitNow(driver, { kind: "compaction_finished" });
+ emitNow(driver, { kind: "turn_end" });
+ const events = await take(iterator as never, 7);
+ const admission = events.filter((event) =>
+ (event.type === "command_accepted" || event.type === "command_failed")
+ && event.commandId === "two"
+ );
+ expect(driver.writes).toEqual(["follow two"]);
+ expect(admission).toMatchObject([{
+ type: "command_failed",
+ commandId: "two",
+ error: { code: "turn_completed_before_command_acceptance" },
+ }]);
+ expect(events.findIndex((event) => event === admission[0]))
+ .toBeLessThan(events.findIndex((event) => event.type === "turn_completed"));
+ expect(events.find((event) => event.type === "turn_completed"))
+ .toMatchObject({ commandIds: ["one"] });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("does not start the next turn while a cancelled boundary send is still physically in flight", async () => {
+ const { session, driver } = makeSession("claude");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ const internals = session as unknown as {
+ sendLane(text: string, mode: "busy" | "idle"): Promise<unknown>;
+ };
+ const sendLane = internals.sendLane.bind(session);
+ let settleBoundary = () => {};
+ const boundary = new Promise<void>((resolve) => { settleBoundary = resolve; });
+ const startedBoundaryWrites: string[] = [];
+ vi.spyOn(internals, "sendLane").mockImplementation((text, mode) => {
+ if (mode === "busy") {
+ startedBoundaryWrites.push(text);
+ return boundary;
+ }
+ return sendLane(text, mode);
+ });
+ await session.send({ id: "two", kind: "user", text: "follow two" });
+ emitNow(driver, { kind: "compaction_finished" });
+ await session.send({ id: "three", kind: "user", text: "follow three" });
+ emitNow(driver, { kind: "turn_end" });
+ await Promise.resolve();
+ expect(startedBoundaryWrites).toEqual(["follow two"]);
+ expect(driver.writes).toEqual([]);
+ expect(session.snapshot()).toMatchObject({ state: "idle", queuedCommands: [{ commandId: "three" }] });
+ settleBoundary();
+ await boundary;
+ await vi.waitFor(() => expect(driver.writes).toEqual(["follow three"]));
+ expect(session.snapshot()).toMatchObject({ activeTurn: { commandIds: ["three"] }, queuedCommands: [] });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("waits for the final nested tool output before flushing a gated command", async () => {
+ const { session, driver } = makeSession("claude");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "tool_call", name: "one", input: {} });
+ await emit(driver, { kind: "tool_call", name: "two", input: {} });
+ await session.send({ id: "two", kind: "user", text: "follow" });
+ await emit(driver, { kind: "tool_output", name: "one" });
+ expect(driver.writes).toEqual([]);
+ await emit(driver, { kind: "tool_output", name: "two" });
+ expect(driver.writes).toEqual(["follow"]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("flushes after review finishes but not while review is active", async () => {
+ const { session, driver } = makeSession("codex");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "review_started" });
+ await session.send({ id: "two", kind: "user", text: "follow" });
+ expect(driver.writes).toEqual([]);
+ await emit(driver, { kind: "review_finished" });
+ expect(driver.writes).toEqual(["follow"]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("projects ordinary compaction and runtime diagnostics for the active turn", async () => {
+ const { session, driver } = makeSession("codex");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "compaction_started" });
+ await emit(driver, { kind: "compaction_finished" });
+ await emit(driver, {
+ kind: "runtime_diagnostic",
+ severity: "warning",
+ source: "codex",
+ message: "careful",
+ });
+ const events = await take(iterator as never, 5);
+ expect(events.map((event) => event.type)).toEqual([
+ "command_accepted",
+ "turn_started",
+ "compaction_started",
+ "compaction_finished",
+ "diagnostic",
+ ]);
+ expect(events.at(-1)).toMatchObject({ severity: "warning", message: "careful" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("does not tool-boundary flush after an error in the same turn", async () => {
+ const { session, driver } = makeSession("claude");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "tool_call", name: "one", input: {} });
+ await session.send({ id: "two", kind: "user", text: "follow" });
+ await emit(driver, { kind: "error", message: "failed" });
+ await emit(driver, { kind: "tool_output", name: "one" });
+ expect(driver.writes).toEqual([]);
+ await emit(driver, { kind: "turn_end", sessionId: "s1" });
+ await vi.waitFor(() => expect(driver.writes).toEqual(["follow"]));
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("opencode keeps one persistent lane and admits busy input as steer", async () => {
+ const { session, driver } = makeSession("opencode");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ expect(await session.send({ id: "two", kind: "user", text: "steer" })).toMatchObject({
+ status: "accepted",
+ delivery: "steer",
+ commandId: "two",
+ });
+ expect(driver.processes).toHaveLength(1);
+ await emit(driver, { kind: "turn_end", sessionId: "s1" });
+ await expect(session.send({ id: "three", kind: "user", text: "next" })).resolves.toMatchObject({
+ status: "accepted",
+ delivery: "prompt",
+ });
+ expect(driver.processes).toHaveLength(1);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("Pi accepts a busy send as an in-turn steer", async () => {
+ const { session } = makeSession("pi");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ expect(await session.send({ id: "two", kind: "user", text: "steer" })).toMatchObject({ status: "accepted", delivery: "steer", commandId: "two" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+});
+
+describe("logical-session terminal facts", () => {
+ it("reports unsupported extensions without backend-specific core logic", async () => {
+ const { session } = makeSession("claude");
+ await expect((session as any).invokeExtension("unknown", {})).resolves.toMatchObject({
+ ok: false,
+ error: { code: "unsupported_extension" },
+ });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("starts an idle persistent-process turn on the existing lane", async () => {
+ const { session, driver } = makeSession("claude");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await emit(driver, { kind: "turn_end", sessionId: "session-1" });
+ await expect(session.send({ id: "two", kind: "user", text: "next" })).resolves.toMatchObject({
+ status: "accepted",
+ delivery: "prompt",
+ });
+ expect(driver.writes).toEqual(["next"]);
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("normalizes lane errors into runtime diagnostics", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ driver.processes[0].emit("error", new Error("lane exploded"));
+ const events = await take(iterator as never, 3);
+ expect(events.at(-1)).toMatchObject({
+ type: "diagnostic",
+ severity: "error",
+ message: "lane exploded",
+ });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("fails and releases a session when its unread event buffer overflows", async () => {
+ const { session, driver, host } = makeSession("pi");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ driver.lane!.emitEvents([{ kind: "text", text: "x".repeat(session.events.maxBufferedBytes) }]);
+ await expect(session.closed).resolves.toMatchObject({
+ outcome: "crashed",
+ error: { code: "event_buffer_overflow" },
+ cleanup: { status: "released" },
+ });
+ expect(host.releases).toHaveLength(1);
+ });
+
+ it("bounds overflow teardown when an SDK dispose never settles", async () => {
+ vi.useFakeTimers();
+ try {
+ const { session, driver, host } = makeSession("pi", { timeout: 10 });
+ const iterator = session.events[Symbol.asyncIterator]();
+ driver.hangDispose = true;
+ await session.start({ id: "one", kind: "user", text: "start" });
+ driver.lane!.emitEvents([{ kind: "text", text: "x".repeat(session.events.maxBufferedBytes) }]);
+ await expect(session.stop({ reason: "shutdown", forceAfterMs: 10 })).resolves.toMatchObject({
+ status: "already_stopping",
+ requestId: expect.any(String),
+ });
+ await vi.advanceTimersByTimeAsync(11);
+ await expect(session.closed).resolves.toMatchObject({
+ outcome: "crashed",
+ error: { code: "event_buffer_overflow" },
+ cleanup: { status: "released" },
+ });
+ const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ for await (const event of { [Symbol.asyncIterator]: () => iterator }) observed.push(event);
+ expect(observed.at(-1)).toMatchObject({
+ type: "session_closed",
+ result: { error: { code: "event_buffer_overflow" } },
+ });
+ expect(host.releases).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("returns the interrupted turn id when an SDK abort emits turn_end before resolving", async () => {
+ const { session, driver } = makeSession("pi");
+ const iterator = session.events[Symbol.asyncIterator]();
+ const started = await session.start({ id: "one", kind: "user", text: "start" });
+ expect(started).toMatchObject({ status: "accepted" });
+ driver.sdkHandle!.isStreaming = true;
+ driver.sdkHandle!.abort.mockImplementation(async () => {
+ driver.lane!.emitEvents([{
+ kind: "turn_end",
+ sessionId: "sdk-session",
+ turnOwner: driver.currentTerminalOwner,
+ }]);
+ });
+
+ await expect(session.interrupt({ requestId: "interrupt-one", reason: "test" })).resolves.toEqual({
+ status: "accepted",
+ requestId: "interrupt-one",
+ turnId: started.status === "accepted" ? started.turnId : "unreachable",
+ });
+ const events = await take(iterator as never, 4);
+ expect(events.find((event) => event.type === "turn_completed")).toMatchObject({
+ type: "turn_completed",
+ result: { outcome: "interrupted" },
+ });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("normalizes an accepted process interrupt followed by SIGINT exit as an interrupted turn", async () => {
+ const { session, driver } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ const started = await session.start({ id: "one", kind: "user", text: "start" });
+ expect(await session.interrupt({ requestId: "interrupt-process", reason: "test" })).toMatchObject({
+ status: "accepted",
+ turnId: started.status === "accepted" ? started.turnId : "unreachable",
+ });
+
+ driver.processes[0]!.emit("exit", null, "SIGINT");
+ await expect(session.closed).resolves.toMatchObject({ outcome: "crashed", signal: "SIGINT" });
+ const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ for await (const event of { [Symbol.asyncIterator]: () => iterator }) observed.push(event);
+ expect(observed.find((event) => event.type === "turn_completed")).toMatchObject({
+ type: "turn_completed",
+ result: { outcome: "interrupted" },
+ });
+ });
+
+ it("keeps admission closed while a stop-triggered SDK turn_end races a pending abort", async () => {
+ const { session, driver } = makeSession("pi");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ const abortGate = deferred();
+ driver.sdkHandle!.isStreaming = true;
+ driver.sdkHandle!.abort.mockImplementation(() => {
+ driver.lane!.emitEvents([{
+ kind: "turn_end",
+ sessionId: "sdk-session",
+ turnOwner: driver.currentTerminalOwner,
+ }]);
+ return abortGate.promise;
+ });
+
+ const stopping = session.stop({ reason: "owner_request", forceAfterMs: 1_000 });
+ expect(session.snapshot().state).toBe("stopping");
+ await expect(session.send({ id: "two", kind: "user", text: "must not start" })).resolves.toEqual({
+ status: "rejected",
+ reason: "closed",
+ });
+ expect(driver.sdkHandle!.prompt).toHaveBeenCalledOnce();
+ abortGate.resolve();
+ await expect(stopping).resolves.toMatchObject({ status: "accepted" });
+ await expect(session.closed).resolves.toMatchObject({ outcome: "stopped" });
+ });
+
+ it.each(["claude", "pi"] as const)("cleans up a late %s open after stop has already closed the session", async (backend) => {
+ const gate = deferred();
+ const { session, driver } = makeSession(backend, { timeout: 25 });
+ if (backend === "pi") driver.sdkOpenGate = gate.promise;
+ else driver.spawnGate = gate.promise;
+
+ const starting = session.start({ id: "one", kind: "user", text: "start" });
+ await Promise.resolve();
+ await expect(session.stop({ reason: "owner_request", forceAfterMs: 10 })).resolves.toMatchObject({ status: "accepted" });
+ await expect(session.closed).resolves.toMatchObject({ outcome: "stopped" });
+ gate.resolve();
+ await expect(starting).resolves.toEqual({ status: "rejected", reason: "closed" });
+ if (backend === "pi") expect(driver.sdkHandle!.dispose).toHaveBeenCalledOnce();
+ else expect(driver.processes[0].kill).toHaveBeenCalledWith("SIGTERM");
+ });
+
+ it("absorbs a rejected process-lane stop while cleaning up a late open", async () => {
+ const gate = deferred();
+ const stop = vi.spyOn(ProcessLane.prototype, "stop")
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new Error("stop rejected"));
+ try {
+ const { session, driver } = makeSession("claude", { timeout: 25 });
+ driver.spawnGate = gate.promise;
+ const starting = session.start({ id: "one", kind: "user", text: "start" });
+ await Promise.resolve();
+ await expect(session.stop({ reason: "owner_request", forceAfterMs: 10 })).resolves.toMatchObject({ status: "accepted" });
+ gate.resolve();
+ await expect(starting).resolves.toEqual({ status: "rejected", reason: "closed" });
+ expect(stop).toHaveBeenCalledTimes(2);
+ } finally {
+ stop.mockRestore();
+ }
+ });
+
+ it("keeps a late spawn rejection closed after a racing stop", async () => {
+ const gate = deferred();
+ const { session, driver } = makeSession("claude");
+ driver.spawnGate = gate.promise;
+ driver.failSpawn = new Error("late spawn failure");
+ const starting = session.start({ id: "one", kind: "user", text: "start" });
+ await Promise.resolve();
+ await session.stop({ reason: "owner_request", forceAfterMs: 10 });
+ gate.resolve();
+ await expect(starting).resolves.toEqual({ status: "rejected", reason: "closed" });
+ });
+
+ it("does not revive an SDK session after the first prompt fails synchronously", async () => {
+ const { session, driver } = makeSession("pi");
+ driver.failPrompt = new Error("prompt failed");
+ const iterator = session.events[Symbol.asyncIterator]();
+ expect(await session.start({ id: "one", kind: "user", text: "start" })).toMatchObject({ status: "accepted" });
+ const observed = await take(iterator as never, 5);
+ expect(observed.find((event) => event.type === "turn_completed")).toMatchObject({
+ result: { outcome: "failed" },
+ });
+ expect(session.snapshot().state).toBe("idle");
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("bounds a hung SDK dispose and still settles closed", async () => {
+ vi.useFakeTimers();
+ try {
+ const { session, driver, host } = makeSession("pi");
+ driver.hangDispose = true;
+ await session.start({ id: "one", kind: "user", text: "start" });
+ const stopped = session.stop({ reason: "owner_request", forceAfterMs: 25 });
+ await vi.advanceTimersByTimeAsync(130);
+ expect(await stopped).toMatchObject({ status: "accepted" });
+ expect(await session.closed).toMatchObject({ outcome: "forced" });
+ expect(host.releases).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("does not close or release after the outer stop deadline until hard teardown settles", async () => {
+ vi.useFakeTimers();
+ try {
+ const lane = new ControlledRuntimeLane();
+ const gate = deferred();
+ lane.stop.mockImplementation(() => gate.promise);
+ const { session, host } = makeSession("claude", { lane, timeout: 50 });
+ await session.start({ id: "one", kind: "user", text: "start" });
+ let closed = false;
+ void session.closed.then(() => { closed = true; });
+
+ const stopped = session.stop({ reason: "owner_request", forceAfterMs: 10 });
+ await vi.advanceTimersByTimeAsync(11);
+ expect(closed).toBe(false);
+ expect(host.releases).toHaveLength(0);
+
+ gate.resolve();
+ await expect(stopped).resolves.toMatchObject({ status: "accepted" });
+ await expect(session.closed).resolves.toMatchObject({ outcome: "forced" });
+ expect(host.releases).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("surfaces a hard teardown rejection that arrives after the outer stop deadline", async () => {
+ vi.useFakeTimers();
+ try {
+ const lane = new ControlledRuntimeLane();
+ let rejectStop!: (error: Error) => void;
+ const laneStop = new Promise<void>((_resolve, reject) => { rejectStop = reject; });
+ lane.stop.mockImplementation(() => laneStop);
+ const { session, host } = makeSession("claude", { lane, timeout: 50 });
+ await session.start({ id: "one", kind: "user", text: "start" });
+ let closed = false;
+ void session.closed.then(() => { closed = true; });
+
+ const stopped = session.stop({ reason: "owner_request", forceAfterMs: 10 });
+ await vi.advanceTimersByTimeAsync(11);
+ expect(closed).toBe(false);
+ expect(host.releases).toHaveLength(0);
+
+ rejectStop(new Error("tree kill denied"));
+ await expect(stopped).resolves.toMatchObject({ status: "failed", error: { code: "stop_failed" } });
+ await expect(session.closed).resolves.toMatchObject({
+ outcome: "forced",
+ error: { code: "stop_failed" },
+ });
+ expect(host.releases).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("settles closed and releases resources when lane stop rejects", async () => {
+ const { session, driver, host } = makeSession("pi");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ driver.failDispose = new Error("dispose failed");
+ await expect(session.stop({ reason: "owner_request", forceAfterMs: 25 })).resolves.toMatchObject({
+ status: "failed",
+ error: { code: "stop_failed" },
+ });
+ await expect(session.closed).resolves.toMatchObject({
+ outcome: "forced",
+ error: { code: "stop_failed" },
+ cleanup: { status: "released" },
+ });
+ expect(session.snapshot().state).toBe("closed");
+ expect(host.releases).toHaveLength(1);
+ await expect(session.stop({ reason: "shutdown", forceAfterMs: 25 })).resolves.toMatchObject({ status: "closed" });
+ });
+
+ it("releases host resources as consumer_closed when the event consumer cancels", async () => {
+ const { session, host } = makeSession("claude");
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await iterator.return?.();
+ await session.closed;
+ expect(host.releases).toHaveLength(1);
+ expect(host.releases[0].reason).toBe("consumer_closed");
+ });
+
+ it("passes an exact resume id to the physical adapter", async () => {
+ const { session, driver } = makeSession("codex", { resumeSessionId: "resume-exact" });
+ await session.start({ id: "one", kind: "user", text: "start" });
+ expect(driver.spawnContexts[0].config.sessionId).toBe("resume-exact");
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+
+ it("classifies failed start and releases the host resource once", async () => {
+ const { session, driver, host } = makeSession("claude");
+ driver.failSpawn = new Error("spawn failed");
+ expect(await session.start({ id: "one", kind: "user", text: "start" })).toMatchObject({ status: "rejected", reason: "runtime_unavailable" });
+ expect(await session.closed).toMatchObject({ outcome: "failed_to_start", cleanup: { status: "released" } });
+ expect(host.releases).toHaveLength(1);
+ });
+
+ it("settles closed and releases resources when lane stop throws", async () => {
+ const lane = new ControlledRuntimeLane();
+ lane.stop.mockImplementation(() => { throw new Error("stop threw"); });
+ const { session, host } = makeSession("claude", { lane });
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await expect(session.stop({ reason: "owner_request", forceAfterMs: 25 })).resolves.toMatchObject({
+ status: "failed",
+ error: { code: "stop_failed" },
+ });
+ await expect(session.closed).resolves.toMatchObject({ outcome: "forced", error: { code: "stop_failed" } });
+ expect(host.releases).toHaveLength(1);
+ });
+
+ it("classifies an unexpected physical exit as a crash", async () => {
+ const { session, driver } = makeSession("claude");
+ await session.start({ id: "one", kind: "user", text: "start" });
+ driver.processes[0].emit("exit", 7, null);
+ expect(await session.closed).toMatchObject({ outcome: "crashed", exitCode: 7, signal: null });
+ });
+
+ it("holds a terminal-root lane through group cleanup when owner stop races its exit", async () => {
+ const lane = new ControlledRuntimeLane();
+ const cleanupGate = deferred();
+ lane.stop.mockImplementation(() => cleanupGate.promise);
+ const { session, host } = makeSession("claude", { lane, timeout: 1_000 });
+ await session.start({ id: "one", kind: "user", text: "start" });
+
+ lane.events.emit("exit", { code: 0, signal: null, reason: "runtime_exit" });
+ await Promise.resolve();
+
+ expect(lane.stop).toHaveBeenCalledWith({ reason: "runtime_exit", forceAfterMs: 0 });
+ await expect(session.stop({ reason: "owner_request", forceAfterMs: 10 })).resolves.toMatchObject({
+ status: "already_stopping",
+ });
+ expect(session.snapshot()).toMatchObject({ state: "stopping", queuedCommands: [] });
+ expect(host.releases).toHaveLength(0);
+
+ cleanupGate.resolve();
+ await expect(session.closed).resolves.toMatchObject({ outcome: "crashed", exitCode: 0, signal: null });
+ expect(lane.stop).toHaveBeenCalledOnce();
+ expect(host.releases).toHaveLength(1);
+ });
+
+ it("closes admission immediately while crash cleanup is pending", async () => {
+ const releaseGate = deferred();
+ const prepared: PreparedExecutionResource = {
+ environmentLayers: { base: {}, hostStatic: {}, identityProtected: {}, platformProtected: {}, runtimeProtected: {}, networkProtected: {}, credentialSensitive: {} },
+ release: vi.fn(() => releaseGate.promise),
+ };
+ const { session, driver } = makeSession("claude", { prepared, timeout: 1_000 });
+ await session.start({ id: "one", kind: "user", text: "start" });
+ driver.processes[0].emit("exit", 7, null);
+ await expect(session.send({ id: "two", kind: "user", text: "must not queue" })).resolves.toEqual({
+ status: "rejected",
+ reason: "closed",
+ });
+ expect(session.snapshot()).toMatchObject({ state: "stopping", queuedCommands: [] });
+ releaseGate.resolve();
+ await expect(session.closed).resolves.toMatchObject({ outcome: "crashed" });
+ });
+
+ it("bounds a hung host release and still closes the iterator", async () => {
+ vi.useFakeTimers();
+ try {
+ const prepared: PreparedExecutionResource = {
+ environmentLayers: { base: {}, hostStatic: {}, identityProtected: {}, platformProtected: {}, runtimeProtected: {}, networkProtected: {}, credentialSensitive: {} },
+ release: () => new Promise(() => {}),
+ };
+ const { session } = makeSession("claude", { prepared, timeout: 25 });
+ await session.start({ id: "one", kind: "user", text: "start" });
+ const stopped = session.stop({ reason: "owner_request", forceAfterMs: 10 });
+ await vi.advanceTimersByTimeAsync(30);
+ await stopped;
+ expect(await session.closed).toMatchObject({ outcome: "stopped", cleanup: { status: "timed_out" } });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it.each(["throw", "reject"] as const)("settles one failed cleanup diagnostic when host release %ss", async (mode) => {
+ const prepared: PreparedExecutionResource = {
+ environmentLayers: { base: {}, hostStatic: {}, identityProtected: {}, platformProtected: {}, runtimeProtected: {}, networkProtected: {}, credentialSensitive: {} },
+ release: vi.fn(() => {
+ if (mode === "throw") throw new Error("private release detail");
+ return Promise.reject(new Error("private release detail"));
+ }),
+ };
+ const { session } = makeSession("claude", { prepared });
+ const iterator = session.events[Symbol.asyncIterator]();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ await expect(session.stop({ reason: "owner_request", forceAfterMs: 10 })).resolves.toMatchObject({ status: "accepted" });
+ await expect(session.closed).resolves.toMatchObject({
+ outcome: "stopped",
+ cleanup: { status: "failed", error: { code: "host_release_failed" } },
+ });
+ const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ for await (const event of { [Symbol.asyncIterator]: () => iterator }) observed.push(event);
+ expect(observed.filter((event) => event.type === "diagnostic" && event.source === "host")).toHaveLength(1);
+ expect(observed.at(-1)?.type).toBe("session_closed");
+ expect(prepared.release).toHaveBeenCalledOnce();
+ });
+
+ it("shares one terminal cleanup across concurrent stop calls", async () => {
+ let release!: () => void;
+ const releaseGate = new Promise<void>((resolve) => { release = resolve; });
+ const prepared: PreparedExecutionResource = {
+ environmentLayers: { base: {}, hostStatic: {}, identityProtected: {}, platformProtected: {}, runtimeProtected: {}, networkProtected: {}, credentialSensitive: {} },
+ release: vi.fn(() => releaseGate),
+ };
+ const { session } = makeSession("claude", { prepared, timeout: 1_000 });
+ await session.start({ id: "one", kind: "user", text: "start" });
+ const first = session.stop({ reason: "owner_request", forceAfterMs: 10 });
+ expect(await session.stop({ reason: "shutdown", forceAfterMs: 10 })).toMatchObject({ status: "already_stopping" });
+ release();
+ expect(await first).toMatchObject({ status: "accepted" });
+ await session.closed;
+ expect(prepared.release).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/daemon/agent-driver/src/controller/logical-session.ts b/src/daemon/agent-driver/src/controller/logical-session.ts
new file mode 100644
index 000000000..a190f9a1e
--- /dev/null
+++ b/src/daemon/agent-driver/src/controller/logical-session.ts
@@ -0,0 +1,1373 @@
+import type {
+ AgentDriverError,
+ AgentEvent,
+ AgentMessage,
+ AgentSession,
+ AgentSessionResult,
+ AgentSessionSnapshot,
+ BackendId,
+ CapabilitiesOf,
+ ConfigOf,
+ CoreAgentEventPayload,
+ DeliveryReceipt,
+ ExtensionResult,
+ HostCleanupResult,
+ InterruptResult,
+ JsonObject,
+ JsonValue,
+ PreparedExecutionResource,
+ StopInput,
+ StopReceipt,
+} from "../contract.js";
+import type { AgentDriverHost } from "../contract.js";
+import type {
+ BackendAdapter,
+ AdapterLaunchContext,
+ AdapterEvent,
+ LaneAdmission,
+ RuntimeLane,
+} from "../internal/adapter.js";
+import { BufferedEventQueue } from "./event-queue.js";
+import { writeAgentFile } from "../internal/agentFile.js";
+import { scrubDriverErrorMessage } from "../internal/errors.js";
+import { mkdirSync } from "node:fs";
+
+type SessionState = AgentSessionSnapshot["state"];
+
+interface QueuedCommand {
+ message: AgentMessage;
+ reason: "unsafe_boundary" | "runtime_busy" | "waiting_for_message";
+ queuedAt: number;
+}
+
+interface CommandRecord {
+ method: "start" | "send";
+ canonical: string;
+ promise: Promise<DeliveryReceipt>;
+}
+
+interface SafeBoundaryDelivery {
+ item: QueuedCommand;
+ activeTurn: { turnId: string; commandIds: string[] };
+ finalized: boolean;
+}
+
+interface SteeringDelivery {
+ message: AgentMessage;
+ activeTurn: ActiveTurn;
+ finalized: boolean;
+ failure?: AgentDriverError;
+ cancel(error: AgentDriverError): void;
+ cancellation: Promise<never>;
+}
+
+interface TurnAdmission {
+ messages: AgentMessage[];
+ turnId: string;
+ delivery: "prompt" | "steer";
+ finalized: boolean;
+ accepted: boolean;
+ pendingEvents: Array<{
+ event: AdapterEvent;
+ physicalOwner: RuntimeLane;
+ generation: number;
+ }>;
+}
+
+interface ActiveTurn {
+ turnId: string;
+ commandIds: string[];
+ terminalOwner?: string;
+}
+
+interface ClosedLaneTombstone {
+ sessionInstanceId: string;
+ localTurnId: string;
+ commandIds: string[];
+ terminalOwner?: string;
+ physicalOwner: RuntimeLane;
+ generation: number;
+ state: "closed" | "reopened_after_terminal";
+}
+
+function driverError(
+ category: AgentDriverError["category"],
+ code: string,
+ message: string,
+ retryable = false,
+): AgentDriverError {
+ return { category, code, message: scrubDriverErrorMessage(message), retryable };
+}
+
+class StructuredLaneAdmissionError extends Error {
+ constructor(readonly code: "reset_required" | "incompatible_configuration", message: string) {
+ super(message);
+ }
+}
+
+function jsonValue(value: unknown): JsonValue {
+ if (value === undefined) return null;
+ try {
+ return JSON.parse(JSON.stringify(value)) as JsonValue;
+ } catch {
+ return String(value);
+ }
+}
+
+export class LogicalAgentSession<Specs, Id extends BackendId<Specs>>
+implements AgentSession<Specs, Id> {
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+ readonly sessionInstanceId: string;
+ readonly events;
+ readonly closed: Promise<AgentSessionResult>;
+
+ private state: SessionState = "new";
+ private backendSessionId?: string;
+ private lane: RuntimeLane | null = null;
+ private activeTurn?: ActiveTurn;
+ private readonly queued: QueuedCommand[] = [];
+ private readonly commands = new Map<string, CommandRecord>();
+ private readonly commandAdmittedAt = new Map<string, number>();
+ private startedAdmitted = false;
+ private eventSequence = 0;
+ private resolveClosed!: (result: AgentSessionResult) => void;
+ private terminalResult?: AgentSessionResult;
+ private finishing = false;
+ private finishPromise?: Promise<void>;
+ private turnError?: AgentDriverError;
+ private interruptedTurnId?: string;
+ private processTurnEnded = false;
+ private stopRequestId?: string;
+ private outstandingToolUses = 0;
+ private compacting = false;
+ private reviewing = false;
+ private readonly steeringDeliveries = new Set<SteeringDelivery>();
+ private laneAdmissionTail: Promise<void> = Promise.resolve();
+ private laneAdmissionPending = 0;
+ private toolBoundaryFlushDisabled = false;
+ private safeBoundaryFlush?: Promise<void>;
+ private safeBoundaryDelivery?: SafeBoundaryDelivery;
+ private turnAdmission?: TurnAdmission;
+ private instructionsMaterialized = false;
+ private lifecycleGeneration = 0;
+ private closedLaneTombstone?: ClosedLaneTombstone;
+ private physicalOpenCount = 0;
+ private turnCount = 0;
+ private commandAdmissionCount = 0;
+ private commandAdmissionLatencyTotalMs = 0;
+ private queueDwellCount = 0;
+ private queueDwellTotalMs = 0;
+ private sseReconnectCount = 0;
+ private resumeOutcome: AgentSessionSnapshot["diagnostics"]["metrics"]["resumeOutcome"];
+
+ private readonly eventQueue: BufferedEventQueue<AgentEvent<Specs, Id>>;
+ private readonly behavior;
+
+ constructor(
+ readonly backend: Id,
+ private readonly config: ConfigOf<Specs, Id>,
+ private readonly launch: {
+ workingDirectory: string;
+ instructions: string;
+ resumeSessionId?: string;
+ launchId: string;
+ },
+ private readonly adapter: BackendAdapter<Id, ConfigOf<Specs, Id>>,
+ capabilities: CapabilitiesOf<Specs, Id>,
+ private readonly host: AgentDriverHost,
+ private readonly prepared: PreparedExecutionResource,
+ private readonly hostReleaseTimeoutMs: number,
+ ) {
+ this.capabilities = capabilities;
+ this.behavior = this.capabilities as import("../contract.js").BackendCapabilities;
+ this.resumeOutcome = launch.resumeSessionId ? "pending" : "not_requested";
+ this.sessionInstanceId = host.createId();
+ this.closed = new Promise((resolve) => { this.resolveClosed = resolve; });
+ this.eventQueue = new BufferedEventQueue(
+ () => { void this.stopForConsumer(); },
+ () => { void this.failBufferOverflow(); },
+ );
+ this.events = this.eventQueue.stream;
+ }
+
+ start(message: AgentMessage): Promise<DeliveryReceipt> {
+ return this.admit("start", message);
+ }
+
+ send(message: AgentMessage): Promise<DeliveryReceipt> {
+ return this.admit("send", message);
+ }
+
+ async interrupt(input: { readonly requestId: string; readonly reason: string }): Promise<InterruptResult> {
+ if (this.state === "closed" || this.state === "stopping" || this.finishing) return { status: "closed" };
+ if (!this.activeTurn || !this.lane) return { status: "not_running" };
+ const turnId = this.activeTurn.turnId;
+ this.interruptedTurnId = turnId;
+ try {
+ const accepted = await this.lane.interrupt(input);
+ if (!accepted) {
+ if (this.interruptedTurnId === turnId) this.interruptedTurnId = undefined;
+ return { status: "not_running" };
+ }
+ return { status: "accepted", requestId: input.requestId, turnId };
+ } catch (error) {
+ if (this.interruptedTurnId === turnId) this.interruptedTurnId = undefined;
+ return {
+ status: "failed",
+ error: driverError("process", "interrupt_failed", String(error), true),
+ };
+ }
+ }
+
+ async stop(input: StopInput): Promise<StopReceipt> {
+ return this.stopWithRelease(input, "requested_stop");
+ }
+
+ private async stopWithRelease(
+ input: StopInput,
+ releaseReason: "requested_stop" | "consumer_closed",
+ ): Promise<StopReceipt> {
+ if (this.terminalResult) return { status: "closed", result: this.terminalResult };
+ if (this.state === "stopping" || this.finishing) {
+ return { status: "already_stopping", requestId: this.enterStopping() };
+ }
+ const stopRequestId = this.enterStopping();
+ this.failTurnAdmission("cancelled", "session_stopping", "Session is stopping");
+ this.failSafeBoundaryDelivery("cancelled", "session_stopping", "Session is stopping");
+ this.failSteeringDeliveries("cancelled", "session_stopping", "Session is stopping");
+ this.failQueued("cancelled", "session_stopping", "Session is stopping");
+ let forced = false;
+ let stopFailure: AgentDriverError | undefined;
+ if (this.lane) {
+ const settlement = await this.settleLaneStop(input.reason, input.forceAfterMs);
+ forced = settlement.forced;
+ stopFailure = settlement.failure;
+ }
+ if (stopFailure) {
+ const error = stopFailure;
+ await this.finish(
+ (cleanup) => ({
+ outcome: "forced",
+ requested: true,
+ backendSessionId: this.backendSessionId,
+ error,
+ cleanup,
+ }),
+ releaseReason,
+ );
+ return { status: "failed", error };
+ } else if (forced) {
+ await this.finish(
+ (cleanup) => ({
+ outcome: "forced",
+ requested: true,
+ backendSessionId: this.backendSessionId,
+ error: driverError("timeout", "force_stop_deadline", "Runtime did not stop before the force deadline"),
+ cleanup,
+ }),
+ releaseReason,
+ );
+ } else {
+ await this.finish(
+ (cleanup) => ({
+ outcome: "stopped",
+ requested: true,
+ backendSessionId: this.backendSessionId,
+ cleanup,
+ }),
+ releaseReason,
+ );
+ }
+ return { status: "accepted", requestId: stopRequestId };
+ }
+
+ snapshot(): AgentSessionSnapshot {
+ return {
+ sessionInstanceId: this.sessionInstanceId,
+ state: this.state,
+ backendSessionId: this.backendSessionId,
+ activeTurn: this.activeTurn
+ ? { turnId: this.activeTurn.turnId, commandIds: this.activeTurn.commandIds }
+ : undefined,
+ queuedCommands: this.queued.map(({ message }) => ({
+ commandId: message.id,
+ kind: message.kind,
+ })),
+ lastEventSequence: this.eventSequence,
+ diagnostics: {
+ deliveryPhase: this.deliveryPhase(),
+ metrics: {
+ physicalOpenCount: this.metricValue(this.physicalOpenCount),
+ turnCount: this.metricValue(this.turnCount),
+ commandAdmissionCount: this.metricValue(this.commandAdmissionCount),
+ commandAdmissionLatencyTotalMs: this.metricValue(this.commandAdmissionLatencyTotalMs),
+ queueDwellCount: this.metricValue(this.queueDwellCount),
+ queueDwellTotalMs: this.metricValue(this.queueDwellTotalMs),
+ sseReconnectCount: this.metricValue(this.sseReconnectCount),
+ resumeOutcome: this.resumeOutcome,
+ terminalOwnerKind: this.adapter.execution.terminalOwnership,
+ },
+ },
+ };
+ }
+
+ async invokeExtension(): Promise<ExtensionResult<never>> {
+ return {
+ ok: false,
+ error: driverError("configuration", "unsupported_extension", "Backend has no public extensions"),
+ };
+ }
+
+ private admit(method: "start" | "send", message: AgentMessage): Promise<DeliveryReceipt> {
+ const canonical = JSON.stringify(message);
+ const existing = this.commands.get(message.id);
+ if (existing) {
+ if (existing.method === method && existing.canonical === canonical) return existing.promise;
+ return Promise.resolve({ status: "rejected", reason: "duplicate_conflict" });
+ }
+ this.commandAdmittedAt.set(message.id, this.metricNow());
+ const promise = this.admitFresh(method, message).then((receipt) => {
+ if (receipt.status === "rejected") this.commandAdmittedAt.delete(message.id);
+ return receipt;
+ });
+ this.commands.set(message.id, { method, canonical, promise });
+ return promise;
+ }
+
+ private async admitFresh(
+ method: "start" | "send",
+ message: AgentMessage,
+ ): Promise<DeliveryReceipt> {
+ if (!message.id || !message.text) return { status: "rejected", reason: "invalid_input" };
+ if (this.state === "closed" || this.state === "stopping" || this.finishing) {
+ return { status: "rejected", reason: "closed" };
+ }
+ if (method === "start") {
+ if (this.startedAdmitted) return { status: "rejected", reason: "already_started" };
+ this.startedAdmitted = true;
+ if (
+ this.adapter.execution.lifetime === "turn"
+ && this.adapter.execution.wakeStart === "deferred"
+ && message.kind === "system"
+ ) {
+ return this.queue(message, "waiting_for_message", "awaiting_first_message");
+ }
+ return this.startTurn([message], "prompt");
+ }
+ if (!this.startedAdmitted) return { status: "rejected", reason: "not_started" };
+ if (this.state === "awaiting_first_message") {
+ if (message.kind === "system") return this.queue(message, "waiting_for_message");
+ const prefix = this.queued.splice(0).map((item) => {
+ this.recordQueueDwell(item);
+ return item.message;
+ });
+ return this.startTurn([...prefix, message], "prompt");
+ }
+ if (this.state === "working" || this.state === "starting") {
+ if (this.behavior.midTurnDelivery === "steer" && this.activeTurn && this.lane) {
+ return this.deliverSteer(message, this.activeTurn);
+ }
+ const reason = this.behavior.midTurnDelivery === "safe_boundary_queue"
+ ? "unsafe_boundary"
+ : "runtime_busy";
+ const receipt = this.queue(message, reason);
+ if (this.behavior.midTurnDelivery === "safe_boundary_queue") {
+ void this.flushSafeBoundaryQueue();
+ }
+ return receipt;
+ }
+ if (
+ this.state === "idle"
+ && (this.queued.length > 0 || this.safeBoundaryFlush !== undefined || this.safeBoundaryDelivery !== undefined)
+ ) {
+ return this.queue(message, "runtime_busy");
+ }
+ return this.startTurn([message], "prompt");
+ }
+
+ private queue(
+ message: AgentMessage,
+ reason: QueuedCommand["reason"],
+ nextState?: SessionState,
+ ): DeliveryReceipt {
+ this.queued.push({ message, reason, queuedAt: this.metricNow() });
+ if (nextState) this.state = nextState;
+ this.emit({ type: "command_queued", commandId: message.id, reason });
+ return { status: "queued", reason, commandId: message.id };
+ }
+
+ private async startTurn(
+ messages: AgentMessage[],
+ delivery: "prompt" | "steer",
+ ): Promise<DeliveryReceipt> {
+ const turnId = this.host.createId();
+ const commandIds = messages.map((message) => message.id);
+ const terminalOwner = this.adapter.beginTurn?.();
+ this.activeTurn = { turnId, commandIds: [...commandIds], ...(terminalOwner ? { terminalOwner } : {}) };
+ this.turnError = undefined;
+ this.interruptedTurnId = undefined;
+ this.processTurnEnded = false;
+ this.state = "starting";
+ const generation = this.lifecycleGeneration;
+ const text = messages.map((message) => message.text).join("\n\n");
+ const admission: TurnAdmission = {
+ messages,
+ turnId,
+ delivery,
+ finalized: false,
+ accepted: false,
+ pendingEvents: [],
+ };
+ this.turnAdmission = admission;
+ const current = messages.at(-1)!;
+ const acceptedReceipt: DeliveryReceipt = {
+ status: "accepted",
+ delivery,
+ commandId: current.id,
+ turnId,
+ };
+ const admit = async (reuseExistingLane: boolean): Promise<DeliveryReceipt> => {
+ try {
+ let laneAdmission: LaneAdmission;
+ if (reuseExistingLane) {
+ laneAdmission = await this.sendLane(text, "idle");
+ } else {
+ const opened = await this.openLane(text, generation);
+ if (!opened) {
+ // A racing stop owns terminal settlement. Preserve the historical
+ // contract that session_closed is observable before start resolves.
+ if (this.finishPromise) await this.finishPromise;
+ return { status: "rejected", reason: "closed" };
+ }
+ laneAdmission = opened;
+ }
+ if (!this.isStartCurrent(generation, turnId)) {
+ return { status: "rejected", reason: "closed" };
+ }
+ this.acceptTurnAdmission(admission, laneAdmission);
+ void this.flushSafeBoundaryQueue();
+ return acceptedReceipt;
+ } catch (error) {
+ if (!this.isStartCurrent(generation, turnId) || admission.finalized) {
+ return admission.accepted ? acceptedReceipt : { status: "rejected", reason: "closed" };
+ }
+ const failure = error instanceof StructuredLaneAdmissionError
+ ? driverError("configuration", error.code, error.message, false)
+ : driverError("process", "failed_to_start", String(error), true);
+ if (this.launch.resumeSessionId && this.resumeOutcome === "pending") {
+ this.resumeOutcome = error instanceof StructuredLaneAdmissionError && error.code === "reset_required"
+ ? "reset_required"
+ : "failed";
+ }
+ this.failTurnAdmissionWithError(failure);
+ this.activeTurn = undefined;
+ const failedLane = this.lane;
+ if (failedLane) {
+ this.lane = null;
+ await this.stopLaneInstanceBounded(failedLane, "failed_start", this.hostReleaseTimeoutMs);
+ }
+ this.emit({ type: "session_failed", error: failure });
+ await this.finish(
+ (cleanup) => ({ outcome: "failed_to_start", requested: false, error: failure, cleanup }),
+ "failed_start",
+ );
+ return { status: "rejected", reason: "runtime_unavailable", error: failure };
+ }
+ };
+ const reuseExistingLane = this.adapter.execution.lifetime === "session" && this.lane !== null;
+ return this.enqueueLaneAdmission(() => admit(reuseExistingLane));
+ }
+
+ private internalContext(prompt: string): AdapterLaunchContext<Id, ConfigOf<Specs, Id>> {
+ return {
+ backend: this.backend,
+ agentId: this.launch.launchId,
+ launchId: this.launch.launchId,
+ workingDirectory: this.launch.workingDirectory,
+ standingPrompt: this.launch.instructions,
+ prompt,
+ prepared: this.prepared,
+ config: {
+ sessionId: this.backendSessionId ?? this.launch.resumeSessionId,
+ runtimeConfig: this.config,
+ },
+ };
+ }
+
+ private async openLane(
+ prompt: string,
+ generation: number,
+ ): Promise<LaneAdmission | null> {
+ if (!this.instructionsMaterialized) {
+ // The public controller owns the workspace precondition shared by every
+ // adapter. Fresh daemon agents do not have an agent-specific directory
+ // yet, and both workspace-file materialization and child-process cwd
+ // require it to exist before the physical lane opens.
+ mkdirSync(this.launch.workingDirectory, { recursive: true });
+ const strategy = this.adapter.instructionDelivery;
+ if (strategy.kind === "workspace_file" && this.launch.instructions) {
+ writeAgentFile(this.launch.workingDirectory, this.launch.instructions, strategy);
+ }
+ this.instructionsMaterialized = true;
+ }
+ const ctx = this.internalContext(prompt);
+ const lane = await this.adapter.openLane(ctx, {
+ onRawStdoutLine: (text) => this.host.onRawOutput({
+ backend: this.backend,
+ launchId: this.launch.launchId,
+ stream: "stdout",
+ text,
+ }),
+ });
+ this.physicalOpenCount += 1;
+ this.lane = lane;
+ this.attachLane(lane, generation);
+ if (!this.isOpenCurrent(generation)) {
+ await this.stopLaneInstanceBounded(lane, "stale_open", this.hostReleaseTimeoutMs);
+ if (this.lane === lane) this.lane = null;
+ return null;
+ }
+ const admission = await lane.start({
+ text: prompt,
+ sessionId: ctx.config.sessionId,
+ terminalOwner: this.activeTurn?.terminalOwner,
+ });
+ if (!admission.ok) {
+ if (admission.reason === "reset_required" || admission.reason === "incompatible_configuration") {
+ throw new StructuredLaneAdmissionError(admission.reason, admission.error ?? admission.reason);
+ }
+ throw new Error(admission.error ?? admission.reason);
+ }
+ if (!this.isOpenCurrent(generation)) {
+ await this.stopLaneInstanceBounded(lane, "stale_open", this.hostReleaseTimeoutMs);
+ if (this.lane === lane) this.lane = null;
+ return null;
+ }
+ return admission;
+ }
+
+ private attachLane(lane: RuntimeLane, generation: number): void {
+ const current = () => this.lane === lane && this.lifecycleGeneration === generation;
+ lane.on("runtime_event", (event: unknown) => {
+ if (!current()) return;
+ const admission = this.turnAdmission;
+ if (admission && !admission.finalized && admission.turnId === this.activeTurn?.turnId) {
+ admission.pendingEvents.push({ event: event as AdapterEvent, physicalOwner: lane, generation });
+ return;
+ }
+ this.onAdapterEvent(event as AdapterEvent, lane, generation);
+ });
+ lane.on("stderr", (value: unknown) => {
+ if (!current()) return;
+ const text = String(value);
+ this.host.onRawOutput({
+ backend: this.backend,
+ launchId: this.launch.launchId,
+ stream: "stderr",
+ text,
+ });
+ this.emit({
+ type: "diagnostic",
+ severity: "warning",
+ source: this.backend,
+ message: scrubDriverErrorMessage(text, "Runtime emitted a warning"),
+ });
+ });
+ lane.on("error", (error: unknown) => {
+ if (current()) this.onLaneError(error, lane, generation);
+ });
+ lane.on("exit", (info: unknown) => {
+ if (current()) void this.onLaneExit(lane, info);
+ });
+ }
+
+ private onAdapterEvent(
+ event: AdapterEvent,
+ physicalOwner: RuntimeLane,
+ generation: number,
+ ): void {
+ if (this.state === "closed" || this.state === "stopping" || this.finishing) return;
+ if (this.isClosedPerTurnLaneTail(physicalOwner, generation)) return;
+ const turnId = this.activeTurn?.turnId ?? this.reopenClosedLaneForWork(event, physicalOwner, generation);
+ switch (event.kind) {
+ case "session_init":
+ if (this.launch.resumeSessionId && this.resumeOutcome === "pending") {
+ this.resumeOutcome = event.sessionId === this.launch.resumeSessionId ? "resumed" : "failed";
+ }
+ if (this.backendSessionId !== event.sessionId) {
+ this.backendSessionId = event.sessionId;
+ this.emit({ type: "session_started", backendSessionId: event.sessionId });
+ }
+ return;
+ case "turn_owner":
+ if (!this.activeTurn || !event.receipt.trim()) return;
+ if (this.activeTurn.terminalOwner && this.activeTurn.terminalOwner !== event.receipt) {
+ this.turnError = driverError(
+ "process",
+ "terminal_owner_mismatch",
+ "Runtime acknowledged a terminal owner that did not match command admission",
+ );
+ this.emit({
+ type: "diagnostic",
+ turnId: this.activeTurn.turnId,
+ severity: "error",
+ source: this.backend,
+ message: "Runtime terminal ownership did not match command admission",
+ });
+ return;
+ }
+ this.activeTurn.terminalOwner = event.receipt;
+ return;
+ case "thinking":
+ if (turnId) this.emit({ type: "thinking_delta", turnId, text: event.text });
+ return;
+ case "text":
+ if (turnId) this.emit({ type: "text_delta", turnId, text: event.text });
+ return;
+ case "tool_call":
+ this.outstandingToolUses += 1;
+ if (turnId) this.emit({ type: "tool_started", turnId, name: event.name, input: jsonValue(event.input) });
+ return;
+ case "tool_output":
+ this.outstandingToolUses = Math.max(0, this.outstandingToolUses - 1);
+ if (turnId) this.emit({ type: "tool_finished", turnId, name: event.name });
+ if (this.outstandingToolUses === 0 && !this.toolBoundaryFlushDisabled) void this.flushSafeBoundaryQueue();
+ return;
+ case "compaction_started":
+ case "compaction_finished":
+ case "review_started":
+ case "review_finished":
+ if (event.kind === "compaction_started") this.compacting = true;
+ if (event.kind === "compaction_finished") this.compacting = false;
+ if (event.kind === "review_started") this.reviewing = true;
+ if (event.kind === "review_finished") this.reviewing = false;
+ if (turnId) this.emit({ type: event.kind, turnId });
+ if (event.kind.endsWith("finished")) void this.flushSafeBoundaryQueue();
+ return;
+ case "internal_progress":
+ this.emit({ type: "internal_progress", turnId, source: event.source, itemType: event.itemType, payloadBytes: event.payloadBytes });
+ return;
+ case "runtime_diagnostic":
+ this.emit({
+ type: "diagnostic",
+ turnId,
+ severity: event.severity === "error" || event.severity === "warning" || event.severity === "debug"
+ ? event.severity
+ : "info",
+ source: event.source,
+ message: scrubDriverErrorMessage(event.message, "Runtime diagnostic"),
+ });
+ return;
+ case "runtime_metric":
+ if (event.name === "sse_reconnect" && event.increment === 1) this.sseReconnectCount += 1;
+ return;
+ case "telemetry": {
+ const details = jsonValue(event.attrs) as JsonObject;
+ if (event.name === "token_usage") {
+ this.emit({ type: "token_usage", turnId, source: event.source, usage: {}, details });
+ } else {
+ this.emit({ type: "rate_limits", turnId, source: event.source, details });
+ }
+ return;
+ }
+ case "error":
+ this.toolBoundaryFlushDisabled = true;
+ this.turnError = driverError("process", "runtime_error", event.message, true);
+ this.emit({
+ type: "diagnostic",
+ turnId,
+ severity: "error",
+ source: this.backend,
+ message: scrubDriverErrorMessage(event.message),
+ });
+ return;
+ case "turn_end":
+ this.completeTurn(event.sessionId, physicalOwner, generation, event.turnOwner);
+ return;
+ }
+ }
+
+ private isClosedPerTurnLaneTail(
+ physicalOwner: RuntimeLane,
+ generation: number,
+ ): boolean {
+ if (this.adapter.execution.lifetime !== "turn" || this.activeTurn) return false;
+ const tombstone = this.closedLaneTombstone;
+ return tombstone?.state === "closed"
+ && tombstone.sessionInstanceId === this.sessionInstanceId
+ && tombstone.physicalOwner === physicalOwner
+ && tombstone.generation === generation;
+ }
+
+ private reopenClosedLaneForWork(
+ event: AdapterEvent,
+ physicalOwner: RuntimeLane,
+ generation: number,
+ ): string | undefined {
+ // Defense in depth for direct/internal callers. Normal event delivery drops
+ // every event from a closed per-turn transport before any shared-state side
+ // effect in onAdapterEvent's switch can run.
+ if (this.adapter.execution.lifetime === "turn") return undefined;
+ const isRootWork = event.kind === "thinking"
+ || event.kind === "text"
+ || event.kind === "tool_call"
+ || event.kind === "tool_output"
+ || event.kind === "compaction_started"
+ || event.kind === "compaction_finished"
+ || event.kind === "review_started"
+ || event.kind === "review_finished"
+ || event.kind === "internal_progress";
+ if (!isRootWork) return undefined;
+ const tombstone = this.closedLaneTombstone;
+ if (
+ !tombstone
+ || tombstone.sessionInstanceId !== this.sessionInstanceId
+ || tombstone.physicalOwner !== physicalOwner
+ || tombstone.generation !== generation
+ ) return undefined;
+ tombstone.state = "reopened_after_terminal";
+ this.activeTurn = {
+ turnId: tombstone.localTurnId,
+ commandIds: tombstone.commandIds,
+ ...(tombstone.terminalOwner ? { terminalOwner: tombstone.terminalOwner } : {}),
+ };
+ this.state = "working";
+ return tombstone.localTurnId;
+ }
+
+ private completeTurn(
+ sessionId?: string,
+ physicalOwner = this.lane,
+ generation = this.lifecycleGeneration,
+ terminalOwner?: string,
+ ): void {
+ const active = this.activeTurn;
+ if (!active) {
+ return;
+ }
+ if (!active.terminalOwner || terminalOwner !== active.terminalOwner) return;
+ this.failTurnAdmission(
+ "cancelled",
+ "turn_completed_before_command_acceptance",
+ "Turn completed before command acceptance",
+ );
+ this.failSafeBoundaryDelivery(
+ "cancelled",
+ "turn_completed_before_command_acceptance",
+ "Turn completed before command acceptance",
+ );
+ this.failSteeringDeliveries(
+ "cancelled",
+ "turn_completed_before_command_acceptance",
+ "Turn completed before command acceptance",
+ active,
+ );
+ if (sessionId && this.backendSessionId !== sessionId) {
+ this.backendSessionId = sessionId;
+ this.emit({ type: "session_started", backendSessionId: sessionId });
+ }
+ this.emit({
+ type: "turn_completed",
+ turnId: active.turnId,
+ commandIds: active.commandIds,
+ result: this.interruptedTurnId === active.turnId
+ ? { outcome: "interrupted", backendSessionId: this.backendSessionId }
+ : this.turnError
+ ? { outcome: "failed", backendSessionId: this.backendSessionId, error: this.turnError }
+ : { outcome: "success", backendSessionId: this.backendSessionId ?? "" },
+ });
+ if (physicalOwner) {
+ this.closedLaneTombstone = {
+ sessionInstanceId: this.sessionInstanceId,
+ localTurnId: active.turnId,
+ commandIds: active.commandIds,
+ terminalOwner: active.terminalOwner,
+ physicalOwner,
+ generation,
+ state: "closed",
+ };
+ }
+ this.activeTurn = undefined;
+ this.turnError = undefined;
+ this.interruptedTurnId = undefined;
+ this.outstandingToolUses = 0;
+ this.compacting = false;
+ this.reviewing = false;
+ this.toolBoundaryFlushDisabled = false;
+ this.state = "idle";
+ if (this.adapter.execution.lifetime === "turn") {
+ this.processTurnEnded = true;
+ } else {
+ void Promise.resolve()
+ .then(() => this.safeBoundaryFlush)
+ .then(() => this.startNextQueued());
+ }
+ }
+
+ private flushSafeBoundaryQueue(): Promise<void> {
+ if (this.safeBoundaryFlush) return this.safeBoundaryFlush;
+ if (!this.canFlushSafeBoundaryQueue()) return Promise.resolve();
+ this.safeBoundaryFlush = this.drainSafeBoundaryQueue().finally(() => {
+ this.safeBoundaryFlush = undefined;
+ if (this.canFlushSafeBoundaryQueue()) void this.flushSafeBoundaryQueue();
+ });
+ return this.safeBoundaryFlush;
+ }
+
+ private canFlushSafeBoundaryQueue(): boolean {
+ return this.state === "working"
+ && this.behavior.midTurnDelivery === "safe_boundary_queue"
+ && this.outstandingToolUses === 0
+ && !this.compacting
+ && !this.reviewing
+ && this.activeTurn !== undefined
+ && this.lane !== null
+ && this.queued.length > 0;
+ }
+
+ private async drainSafeBoundaryQueue(): Promise<void> {
+ while (this.canFlushSafeBoundaryQueue()) {
+ const item = this.queued.shift()!;
+ this.recordQueueDwell(item);
+ const activeTurn = this.activeTurn!;
+ const delivery: SafeBoundaryDelivery = { item, activeTurn, finalized: false };
+ this.safeBoundaryDelivery = delivery;
+ try {
+ await this.sendLane(item.message.text, "busy");
+ } catch (error) {
+ if (!delivery.finalized) {
+ delivery.finalized = true;
+ this.emit({
+ type: "command_failed",
+ commandId: item.message.id,
+ turnId: activeTurn.turnId,
+ error: driverError("process", "delivery_failed", String(error), true),
+ });
+ }
+ continue;
+ } finally {
+ if (this.safeBoundaryDelivery === delivery) this.safeBoundaryDelivery = undefined;
+ }
+ if (delivery.finalized) continue;
+ delivery.finalized = true;
+ activeTurn.commandIds.push(item.message.id);
+ this.emit({
+ type: "command_accepted",
+ commandId: item.message.id,
+ turnId: activeTurn.turnId,
+ delivery: "steer",
+ });
+ }
+ }
+
+ private failSafeBoundaryDelivery(
+ category: AgentDriverError["category"],
+ code: string,
+ message: string,
+ ): void {
+ const delivery = this.safeBoundaryDelivery;
+ if (!delivery || delivery.finalized) return;
+ delivery.finalized = true;
+ this.emit({
+ type: "command_failed",
+ commandId: delivery.item.message.id,
+ turnId: delivery.activeTurn.turnId,
+ error: driverError(category, code, message),
+ });
+ }
+
+ private failTurnAdmission(
+ category: AgentDriverError["category"],
+ code: string,
+ message: string,
+ ): void {
+ this.failTurnAdmissionWithError(driverError(category, code, message));
+ }
+
+ private failTurnAdmissionWithError(error: AgentDriverError): void {
+ const admission = this.turnAdmission;
+ if (!admission || admission.finalized) return;
+ admission.finalized = true;
+ admission.pendingEvents.length = 0;
+ if (this.turnAdmission === admission) this.turnAdmission = undefined;
+ for (const message of admission.messages) {
+ this.emit({ type: "command_failed", commandId: message.id, turnId: admission.turnId, error });
+ }
+ }
+
+ private acceptTurnAdmission(admission: TurnAdmission, laneAdmission: LaneAdmission): void {
+ if (!laneAdmission.ok) throw new Error(laneAdmission.error ?? laneAdmission.reason);
+ const receipt = laneAdmission.receipt.trim();
+ if (!receipt) throw new Error("runtime admitted a command without a terminal receipt");
+ const active = this.activeTurn;
+ if (!active || active.turnId !== admission.turnId) {
+ throw new Error("runtime admitted a command for a stale turn");
+ }
+ if (active.terminalOwner && active.terminalOwner !== receipt) {
+ throw new Error("runtime admission receipt did not match the prepared terminal owner");
+ }
+ active.terminalOwner = receipt;
+ admission.finalized = true;
+ admission.accepted = true;
+ if (this.turnAdmission === admission) this.turnAdmission = undefined;
+ this.state = "working";
+ this.turnCount += 1;
+ for (const message of admission.messages) {
+ this.emit({
+ type: "command_accepted",
+ commandId: message.id,
+ turnId: admission.turnId,
+ delivery: admission.delivery,
+ });
+ }
+ this.emit({
+ type: "turn_started",
+ turnId: admission.turnId,
+ commandIds: admission.messages.map((message) => message.id),
+ });
+ for (const pending of admission.pendingEvents.splice(0)) {
+ this.onAdapterEvent(pending.event, pending.physicalOwner, pending.generation);
+ }
+ }
+
+ private async startNextQueued(): Promise<void> {
+ if (this.state !== "idle" || this.queued.length === 0) return;
+ const item = this.queued.shift()!;
+ this.recordQueueDwell(item);
+ await this.startTurn([item.message], "prompt");
+ }
+
+ private onLaneError(
+ error: unknown,
+ physicalOwner: RuntimeLane,
+ generation: number,
+ ): void {
+ const message = error instanceof Error ? error.message : String(error);
+ this.onAdapterEvent({ kind: "error", message }, physicalOwner, generation);
+ }
+
+ private async onLaneExit(lane: RuntimeLane, info: unknown): Promise<void> {
+ if (this.lane !== lane || this.state === "closed") return;
+ const stoppingBeforeExit = this.state === "stopping" || this.finishing;
+ const expectedTurnExit = this.adapter.execution.lifetime === "turn" && this.processTurnEnded;
+ if (!stoppingBeforeExit && !expectedTurnExit) this.enterStopping();
+ await this.stopLaneInstanceBounded(lane, "runtime_exit", this.hostReleaseTimeoutMs);
+ if (this.lane === lane) this.lane = null;
+ if (this.terminalResult || stoppingBeforeExit) return;
+ if (expectedTurnExit) {
+ this.processTurnEnded = false;
+ await this.startNextQueued();
+ return;
+ }
+ const facts = info as { code?: number | null; signal?: string | null } | undefined;
+ const error = driverError("process", "runtime_exit", "Runtime exited unexpectedly", true);
+ this.emit({ type: "session_failed", error });
+ await this.finish(
+ (cleanup) => ({
+ outcome: "crashed",
+ requested: false,
+ backendSessionId: this.backendSessionId,
+ exitCode: facts?.code ?? null,
+ signal: facts?.signal ?? null,
+ error,
+ cleanup,
+ }),
+ "crash",
+ );
+ }
+
+ private emit(payload: CoreAgentEventPayload): void {
+ const at = this.metricNow();
+ if (payload.type === "command_accepted" || payload.type === "command_failed") {
+ const admittedAt = this.commandAdmittedAt.get(payload.commandId);
+ if (admittedAt !== undefined) {
+ this.commandAdmittedAt.delete(payload.commandId);
+ this.commandAdmissionCount += 1;
+ this.commandAdmissionLatencyTotalMs += Math.max(0, at - admittedAt);
+ }
+ }
+ const event = {
+ ...payload,
+ sequence: ++this.eventSequence,
+ sessionInstanceId: this.sessionInstanceId,
+ at,
+ } as AgentEvent<Specs, Id>;
+ this.eventQueue.push(event, payload.type === "session_closed");
+ }
+
+ private failQueued(category: AgentDriverError["category"], code: string, message: string): void {
+ const error = driverError(category, code, message);
+ for (const item of this.queued.splice(0)) {
+ this.recordQueueDwell(item);
+ this.emit({ type: "command_failed", commandId: item.message.id, error });
+ }
+ }
+
+ private deliveryPhase(): AgentSessionSnapshot["diagnostics"]["deliveryPhase"] {
+ if (this.state === "stopping" || this.state === "closed") return "idle";
+ if (this.turnAdmission) return "admission_wait";
+ if (this.steeringDeliveries.size > 0 || this.safeBoundaryDelivery) return "steering";
+ if (this.behavior.midTurnDelivery === "next_turn_queue" && this.queued.length > 0) return "next_turn_queued";
+ if (this.compacting) return "compacting";
+ if (this.reviewing) return "reviewing";
+ if (this.outstandingToolUses > 0) return "tool_wait";
+ if (this.activeTurn) return "working";
+ return "idle";
+ }
+
+ private metricNow(): number {
+ const now = this.host.now();
+ return Number.isFinite(now) && now >= 0 ? now : 0;
+ }
+
+ private metricValue(value: number): number {
+ return Number.isFinite(value) && value >= 0 ? value : 0;
+ }
+
+ private recordQueueDwell(item: QueuedCommand): void {
+ this.queueDwellCount += 1;
+ this.queueDwellTotalMs += Math.max(0, this.metricNow() - item.queuedAt);
+ }
+
+ private enqueueLaneAdmission<T>(operation: () => Promise<T>): Promise<T> {
+ // Reserve the lane-wide FIFO slot synchronously. Preserve the historical
+ // immediate first admission while every later root/steer waits on its tail.
+ const startsImmediately = this.laneAdmissionPending === 0;
+ this.laneAdmissionPending += 1;
+ let reserved: Promise<T>;
+ if (startsImmediately) {
+ try {
+ reserved = operation();
+ } catch (error) {
+ reserved = Promise.reject(error);
+ }
+ } else {
+ reserved = this.laneAdmissionTail.then(operation);
+ }
+ const tail = reserved.then(() => {}, () => {});
+ this.laneAdmissionTail = tail;
+ void tail.then(() => {
+ this.laneAdmissionPending = Math.max(0, this.laneAdmissionPending - 1);
+ });
+ return reserved;
+ }
+
+ private async deliverSteer(message: AgentMessage, activeTurn: ActiveTurn): Promise<DeliveryReceipt> {
+ let rejectCancellation!: (error: AgentDriverError) => void;
+ const cancellation = new Promise<never>((_resolve, reject) => { rejectCancellation = reject; });
+ const delivery: SteeringDelivery = {
+ message,
+ activeTurn,
+ finalized: false,
+ cancellation,
+ cancel(error) {
+ rejectCancellation(error);
+ },
+ };
+ this.steeringDeliveries.add(delivery);
+ const physical = this.enqueueLaneAdmission(async (): Promise<DeliveryReceipt> => {
+ try {
+ if (delivery.finalized || this.activeTurn !== activeTurn) {
+ throw delivery.failure ?? driverError(
+ "cancelled",
+ "turn_closed_before_command_acceptance",
+ "Turn closed before command acceptance",
+ );
+ }
+ await this.sendLane(message.text, "busy");
+ if (delivery.finalized || this.activeTurn !== activeTurn) {
+ throw delivery.failure ?? driverError(
+ "cancelled",
+ "turn_closed_before_command_acceptance",
+ "Turn closed before command acceptance",
+ );
+ }
+ delivery.finalized = true;
+ activeTurn.commandIds.push(message.id);
+ this.emit({ type: "command_accepted", commandId: message.id, turnId: activeTurn.turnId, delivery: "steer" });
+ return { status: "accepted", delivery: "steer", commandId: message.id, turnId: activeTurn.turnId };
+ } catch (error) {
+ const failure = delivery.failure ?? (typeof error === "object" && error !== null && "category" in error
+ ? error as AgentDriverError
+ : driverError("process", "delivery_failed", String(error), true));
+ if (!delivery.finalized) {
+ delivery.finalized = true;
+ this.emit({ type: "command_failed", commandId: message.id, turnId: activeTurn.turnId, error: failure });
+ }
+ return { status: "rejected", reason: "runtime_unavailable", error: failure };
+ }
+ });
+ try {
+ return await Promise.race([physical, cancellation]);
+ } catch (error) {
+ const failure = delivery.failure ?? (typeof error === "object" && error !== null && "category" in error
+ ? error as AgentDriverError
+ : driverError("process", "delivery_failed", String(error), true));
+ if (!delivery.finalized) {
+ delivery.finalized = true;
+ this.emit({ type: "command_failed", commandId: message.id, turnId: activeTurn.turnId, error: failure });
+ }
+ return { status: "rejected", reason: "runtime_unavailable", error: failure };
+ } finally {
+ this.steeringDeliveries.delete(delivery);
+ }
+ }
+
+ private failSteeringDeliveries(
+ category: AgentDriverError["category"],
+ code: string,
+ message: string,
+ activeTurn?: ActiveTurn,
+ ): void {
+ const error = driverError(category, code, message);
+ for (const delivery of this.steeringDeliveries) {
+ if (activeTurn && delivery.activeTurn !== activeTurn) continue;
+ if (delivery.finalized) continue;
+ delivery.finalized = true;
+ delivery.failure = error;
+ this.emit({
+ type: "command_failed",
+ commandId: delivery.message.id,
+ turnId: delivery.activeTurn.turnId,
+ error,
+ });
+ delivery.cancel(error);
+ }
+ }
+
+ private async cleanupResource(
+ reason: Parameters<PreparedExecutionResource["release"]>[0]["reason"],
+ ): Promise<HostCleanupResult> {
+ const abort = new AbortController();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeoutError = driverError("timeout", "host_release_timeout", "Host resource release timed out");
+ try {
+ const timeout = new Promise<HostCleanupResult>((resolve) => {
+ timer = setTimeout(() => {
+ abort.abort();
+ resolve({ status: "timed_out", error: timeoutError });
+ }, this.hostReleaseTimeoutMs);
+ timer.unref?.();
+ });
+ const release = Promise.resolve()
+ .then(() => this.prepared.release({
+ reason,
+ signal: abort.signal,
+ deadlineAt: this.host.now() + this.hostReleaseTimeoutMs,
+ }))
+ .then((): HostCleanupResult => ({ status: "released" }))
+ .catch((error): HostCleanupResult => ({
+ status: "failed",
+ error: driverError("internal", "host_release_failed", String(error)),
+ }));
+ const result = await Promise.race([release, timeout]);
+ release.catch(() => {});
+ if (result.status === "failed" || result.status === "timed_out") {
+ this.emit({
+ type: "diagnostic",
+ severity: "error",
+ source: "host",
+ message: result.error.message,
+ });
+ }
+ return result;
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ }
+
+ private async finish(
+ buildResult: (cleanup: HostCleanupResult) => AgentSessionResult,
+ releaseReason: Parameters<PreparedExecutionResource["release"]>[0]["reason"],
+ ): Promise<void> {
+ if (this.terminalResult) return;
+ if (!this.finishPromise) {
+ this.finishing = true;
+ this.enterStopping();
+ this.finishPromise = (async () => {
+ this.failTurnAdmission(
+ "cancelled",
+ "session_closed",
+ "Session closed before command acceptance",
+ );
+ this.failSafeBoundaryDelivery(
+ "cancelled",
+ "session_closed",
+ "Session closed before command acceptance",
+ );
+ this.failSteeringDeliveries(
+ "cancelled",
+ "session_closed",
+ "Session closed before command acceptance",
+ );
+ this.failQueued("cancelled", "session_closed", "Session closed before command acceptance");
+ if (this.activeTurn) {
+ const active = this.activeTurn;
+ const interrupted = releaseReason === "requested_stop"
+ || releaseReason === "consumer_closed"
+ || this.interruptedTurnId === active.turnId;
+ const error = this.turnError ?? driverError(
+ interrupted ? "cancelled" : "process",
+ interrupted ? "turn_interrupted" : "session_closed",
+ interrupted ? "Turn interrupted by session stop" : "Session closed before turn completion",
+ !interrupted,
+ );
+ this.emit({
+ type: "turn_completed",
+ turnId: active.turnId,
+ commandIds: active.commandIds,
+ result: interrupted
+ ? { outcome: "interrupted", backendSessionId: this.backendSessionId ?? "" }
+ : { outcome: "failed", backendSessionId: this.backendSessionId, error },
+ });
+ this.activeTurn = undefined;
+ this.interruptedTurnId = undefined;
+ }
+ const cleanup = await this.cleanupResource(releaseReason);
+ const result = buildResult(cleanup);
+ this.terminalResult = result;
+ this.state = "closed";
+ this.emit({ type: "session_closed", result });
+ this.eventQueue.close();
+ this.resolveClosed(result);
+ this.finishing = false;
+ })();
+ }
+ await this.finishPromise;
+ }
+
+ private async failBufferOverflow(): Promise<void> {
+ if (this.terminalResult || this.finishing) return;
+ const error = driverError("buffer_overflow", "event_buffer_overflow", "Event buffer exceeded 4 MiB");
+ this.enterStopping();
+ if (this.lane) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const stopped = this.stopLane("event_buffer_overflow", 0).catch(() => {});
+ const deadline = new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, this.hostReleaseTimeoutMs);
+ timer.unref?.();
+ });
+ await Promise.race([stopped, deadline]);
+ stopped.catch(() => {});
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ }
+ this.emit({ type: "session_failed", error });
+ await this.finish(
+ (cleanup) => ({ outcome: "crashed", requested: false, exitCode: null, signal: null, error, cleanup }),
+ "crash",
+ );
+ }
+
+ private async stopForConsumer(): Promise<void> {
+ if (this.state === "closed" || this.state === "stopping") return;
+ await this.stopWithRelease({ reason: "shutdown", forceAfterMs: 5_000 }, "consumer_closed");
+ }
+
+ private sendLane(text: string, mode: "busy" | "idle"): Promise<LaneAdmission> {
+ if (!this.lane) return Promise.reject(new Error("runtime lane is not open"));
+ return this.lane.send({
+ text,
+ mode,
+ sessionId: this.backendSessionId ?? this.launch.resumeSessionId,
+ terminalOwner: mode === "idle" ? this.activeTurn?.terminalOwner : undefined,
+ })
+ .then((result) => {
+ if (!result.ok) throw new Error(String("reason" in result ? result.reason : "runtime rejected delivery"));
+ return result;
+ });
+ }
+
+ private stopLane(reason: string, forceAfterMs: number): Promise<unknown> {
+ if (!this.lane) return Promise.resolve();
+ return this.lane.stop({ reason, forceAfterMs });
+ }
+
+ /**
+ * Own physical stop settlement across two bounded windows.
+ *
+ * `forceAfterMs` decides whether the public result is forced, but it is not
+ * permission to release host resources while the lane's already-started hard
+ * teardown is still settling. After that outer deadline, wait one separate
+ * host-owned cleanup window so a tree-kill success/rejection remains visible.
+ * A truly hung SDK lane is still bounded by the second window.
+ */
+ private async settleLaneStop(
+ reason: string,
+ forceAfterMs: number,
+ ): Promise<{ forced: boolean; failure?: AgentDriverError }> {
+ type StopSettlement = { kind: "stopped" } | { kind: "failed"; error: unknown };
+ const stopped: Promise<StopSettlement> = Promise.resolve()
+ .then(() => this.stopLane(reason, forceAfterMs))
+ .then(
+ () => ({ kind: "stopped" }),
+ (error: unknown) => ({ kind: "failed", error }),
+ );
+ let outerTimer: ReturnType<typeof setTimeout> | undefined;
+ const outerDeadline = new Promise<{ kind: "outer_deadline" }>((resolve) => {
+ outerTimer = setTimeout(() => resolve({ kind: "outer_deadline" }), forceAfterMs);
+ outerTimer.unref?.();
+ });
+ const first = await Promise.race([stopped, outerDeadline]);
+ if (outerTimer) clearTimeout(outerTimer);
+ if (first.kind === "stopped") return { forced: false };
+ if (first.kind === "failed") {
+ return { forced: false, failure: driverError("process", "stop_failed", String(first.error), true) };
+ }
+
+ let cleanupTimer: ReturnType<typeof setTimeout> | undefined;
+ const cleanupDeadline = new Promise<{ kind: "cleanup_deadline" }>((resolve) => {
+ cleanupTimer = setTimeout(() => resolve({ kind: "cleanup_deadline" }), this.hostReleaseTimeoutMs);
+ cleanupTimer.unref?.();
+ });
+ const final = await Promise.race([stopped, cleanupDeadline]);
+ if (cleanupTimer) clearTimeout(cleanupTimer);
+ if (final.kind === "failed") {
+ return { forced: true, failure: driverError("process", "stop_failed", String(final.error), true) };
+ }
+ return { forced: true };
+ }
+
+ private enterStopping(): string {
+ if (this.state !== "stopping") {
+ this.state = "stopping";
+ this.lifecycleGeneration += 1;
+ this.closedLaneTombstone = undefined;
+ }
+ this.stopRequestId ??= this.host.createId();
+ return this.stopRequestId;
+ }
+
+ private isOpenCurrent(generation: number): boolean {
+ return generation === this.lifecycleGeneration
+ && this.state === "starting"
+ && !this.finishing
+ && !this.terminalResult;
+ }
+
+ private isStartCurrent(generation: number, turnId: string): boolean {
+ return this.isOpenCurrent(generation) && this.activeTurn?.turnId === turnId;
+ }
+
+ private async stopLaneInstanceBounded(
+ lane: RuntimeLane,
+ reason: string,
+ timeoutMs: number,
+ ): Promise<void> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const stopped = lane.stop({ reason, forceAfterMs: 0 })
+ .catch(() => {});
+ const deadline = new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, timeoutMs);
+ timer.unref?.();
+ });
+ try {
+ await Promise.race([stopped, deadline]);
+ stopped.catch(() => {});
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ }
+}
diff --git a/src/daemon/agent-driver/src/controller/process-host.test.ts b/src/daemon/agent-driver/src/controller/process-host.test.ts
new file mode 100644
index 000000000..a00ddd28c
--- /dev/null
+++ b/src/daemon/agent-driver/src/controller/process-host.test.ts
@@ -0,0 +1,407 @@
+import { describe, it, expect, afterEach, vi } from "vitest";
+import { EventEmitter } from "events";
+import { spawn, type ChildProcess } from "child_process";
+import { PassThrough } from "stream";
+import { ProcessLane, type ProcessAdapterPrimitives } from "./process-host.js";
+import type { AdapterLaunchContext, BackendConfig } from "../internal/adapter.js";
+import { fakeLaunchContext } from "../testing/adapter-fixture.js";
+
+const killProcessTree = vi.hoisted(() => vi.fn(async () => {}));
+
+vi.mock("../internal/killTree.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../internal/killTree.js")>(),
+ killProcessTree,
+}));
+
+/*
+ * Red-line-5(b) of plans/daemon-trace-completeness-charter.md (T1): the synthetic
+ * `session.fire("exit", {...})` tests in managerRuntime.test.ts prove the daemon
+ * THREADS exitCode/exitSignal/abnormal into the FSM/trace. They do NOT prove the
+ * SOURCE is real — that a genuinely killed subprocess actually fills `info.code`
+ * / `info.signal` on the runtime session's `exit` event, which is what the
+ * abnormal predicate (managerRuntime.ts) reads. A real subprocess dies here to
+ * confirm that contract end-to-end (Node fills signal=SIGKILL, code=null; a
+ * non-requested death → reason="runtime_exit"). Without this the "hardest to
+ * reconstruct" blind spot would rest on an unverified assumption.
+ */
+
+const spawned: ChildProcess[] = [];
+
+/** Minimal driver that spawns a real, long-lived child process. */
+function realSpawnDriver(): ProcessAdapterPrimitives<string, BackendConfig> {
+ return {
+ id: "test-real",
+ execution: {
+ lifetime: "turn",
+ transport: { kind: "one_shot_cli", protocol: "test.real.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "lane_generation",
+ },
+ currentSessionId: null,
+ spawn: async () => {
+ const proc = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ spawned.push(proc);
+ return { process: proc };
+ },
+ normalizeLine: () => [],
+ encodeMessage: () => null,
+ };
+}
+
+function minimalCtx(): AdapterLaunchContext {
+ return fakeLaunchContext("claude", process.cwd(), {
+ agentId: "a1",
+ });
+}
+
+function controllableDriver(
+ normalizeLine: ProcessAdapterPrimitives<string, BackendConfig>["normalizeLine"],
+): {
+ driver: ProcessAdapterPrimitives<string, BackendConfig>;
+ stdout: PassThrough;
+ process: ChildProcess;
+ kill: ReturnType<typeof vi.fn>;
+} {
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ const stdin = new PassThrough();
+ const kill = vi.fn(() => true);
+ const proc = Object.assign(new EventEmitter(), {
+ stdout,
+ stderr,
+ stdin,
+ pid: undefined,
+ exitCode: null,
+ signalCode: null,
+ kill,
+ }) as unknown as ChildProcess;
+ const driver = {
+ ...realSpawnDriver(),
+ spawn: async () => ({ process: proc }),
+ normalizeLine,
+ };
+ return { driver, stdout, process: proc, kill };
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ killProcessTree.mockClear();
+ for (const p of spawned.splice(0)) {
+ try { p.kill("SIGKILL"); } catch { /* already dead */ }
+ }
+});
+
+describe("ProcessLane — real subprocess exit fills the physical fact (T1 red-line-5b)", () => {
+ it("a real SIGKILLed subprocess emits exit with signal=SIGKILL, null code, reason=runtime_exit", async () => {
+ // POSIX-only: Windows has no real signals — `process.kill(pid, "SIGKILL")`
+ // terminates the child but Node reports `code=1, signal=null`, so the
+ // `signal === "SIGKILL"` contract this asserts can't hold there. Skip on
+ // win32 (same platform-guard as killTree.test.ts). The clean-exit sibling
+ // below (code=0/signal=null) is cross-platform and still runs.
+ if (process.platform === "win32") return;
+ const session = new ProcessLane(realSpawnDriver(), minimalCtx());
+ const exitInfo = await new Promise<{ code: number | null; signal: string | null; reason?: string }>(
+ (resolve) => {
+ session.on("exit", (...args: unknown[]) => resolve(args[0] as never));
+ void session.start({ text: "go" }).then(() => {
+ // Kill the real child directly (external kill, NOT session.stop()) so
+ // requestedStopReason stays unset → reason="runtime_exit", the crash
+ // shape the abnormal predicate must catch.
+ const pid = session.pid;
+ if (pid) process.kill(pid, "SIGKILL");
+ });
+ },
+ );
+ expect(exitInfo.signal).toBe("SIGKILL");
+ expect(exitInfo.code).toBeNull();
+ expect(exitInfo.reason).toBe("runtime_exit");
+ });
+
+ it("a real clean exit (code 0) emits code=0, null signal", async () => {
+ const cleanDriver = {
+ ...realSpawnDriver(),
+ spawn: async () => {
+ const proc = spawn(process.execPath, ["-e", "process.exit(0)"], { stdio: ["pipe", "pipe", "pipe"] });
+ spawned.push(proc);
+ return { process: proc };
+ },
+ };
+ const session = new ProcessLane(cleanDriver, minimalCtx());
+ const exitInfo = await new Promise<{ code: number | null; signal: string | null; reason?: string }>(
+ (resolve) => {
+ session.on("exit", (...args: unknown[]) => resolve(args[0] as never));
+ void session.start({ text: "go" });
+ },
+ );
+ expect(exitInfo.code).toBe(0);
+ expect(exitInfo.signal).toBeNull();
+ });
+});
+
+describe("ProcessLane — raw stdout tap (P0-1)", () => {
+ it("taps each complete non-empty line before normalizeLine and preserves the original text", async () => {
+ const order: string[] = [];
+ const normalizeLine = vi.fn((line: string) => {
+ order.push(`parse:${line}`);
+ return [];
+ });
+ const { driver, stdout } = controllableDriver(normalizeLine);
+ const session = new ProcessLane(driver, minimalCtx(), {
+ onRawStdoutLine: (line) => order.push(`raw:${line}`),
+ });
+ await session.start({ text: "go" });
+
+ stdout.write(" {\"jsonrpc\":\"2.0\"}");
+ stdout.write(" \n\npartial");
+
+ expect(order).toEqual([
+ 'raw: {"jsonrpc":"2.0"} ',
+ 'parse: {"jsonrpc":"2.0"} ',
+ ]);
+ expect(normalizeLine).toHaveBeenCalledTimes(1);
+ });
+
+ it("continues through normalizeLine and runtime_event when the tap throws", async () => {
+ const parsedEvent = { kind: "text", text: "ok" } as const;
+ const normalizeLine = vi.fn(() => [parsedEvent]);
+ const { driver, stdout } = controllableDriver(normalizeLine);
+ const session = new ProcessLane(driver, minimalCtx(), {
+ onRawStdoutLine: () => {
+ throw new Error("sink failed");
+ },
+ });
+ const events: unknown[] = [];
+ session.on("runtime_event", (event) => events.push(event));
+ await session.start({ text: "go" });
+
+ expect(() => stdout.write('{"type":"message"}\n')).not.toThrow();
+ expect(normalizeLine).toHaveBeenCalledWith('{"type":"message"}');
+ expect(events).toEqual([parsedEvent]);
+ });
+});
+
+describe("ProcessLane prompt admission ownership", () => {
+ it("exposes process state and rejects a second start", async () => {
+ const { driver } = controllableDriver(() => []);
+ Object.assign(driver, { currentSessionId: "session-one" });
+ const session = new ProcessLane(driver, minimalCtx());
+
+ expect(session.currentSessionId).toBe("session-one");
+ expect(session.exitCode).toBeNull();
+ await expect(session.start({ text: "go" })).resolves.toMatchObject({ ok: true });
+ await expect(session.start({ text: "again" })).resolves.toEqual({
+ ok: false,
+ reason: "runtime_error",
+ error: "runtime session already started",
+ });
+ });
+
+ it("waits for a transport-owned turn receipt and returns that exact acknowledgement", async () => {
+ const { driver, stdout } = controllableDriver((line) => [JSON.parse(line)]);
+ Object.assign(driver, {
+ execution: {
+ lifetime: "session",
+ transport: { kind: "stdio_rpc", protocol: "test.rpc.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ },
+ });
+ const session = new ProcessLane(driver, minimalCtx());
+ const observed: unknown[] = [];
+ session.on("runtime_event", (event) => observed.push(event));
+ let settled = false;
+ const starting = session.start({ text: "go" }).then((admission) => {
+ settled = true;
+ return admission;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+
+ stdout.write(`${JSON.stringify({ kind: "turn_owner", receipt: "owner-authoritative" })}\n`);
+ await expect(starting).resolves.toEqual({
+ ok: true,
+ acceptedAs: "prompt",
+ receipt: "owner-authoritative",
+ });
+ stdout.write(`${JSON.stringify({ kind: "turn_end", sessionId: "session-one" })}\n`);
+ expect(observed).toEqual([
+ { kind: "turn_owner", receipt: "owner-authoritative" },
+ { kind: "turn_end", sessionId: "session-one", turnOwner: "owner-authoritative" },
+ ]);
+ });
+
+ it("rejects a second root while authority is pending and settles transport errors", async () => {
+ const { driver, stdout } = controllableDriver((line) => [JSON.parse(line)]);
+ Object.assign(driver, {
+ execution: {
+ lifetime: "session",
+ transport: { kind: "stdio_rpc", protocol: "test.rpc.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ },
+ });
+ const session = new ProcessLane(driver, minimalCtx());
+ const starting = session.start({ text: "go" });
+ await Promise.resolve();
+
+ await expect(session.send({ text: "next", mode: "idle" })).resolves.toEqual({
+ ok: false,
+ reason: "runtime_busy",
+ error: "prompt admission is already pending",
+ });
+ stdout.write(`${JSON.stringify({ kind: "error", message: "transport rejected" })}\n`);
+ await expect(starting).resolves.toEqual({
+ ok: false,
+ reason: "runtime_error",
+ error: "transport rejected",
+ });
+ });
+
+ it("clears idle ownership when stdin throws synchronously", async () => {
+ const { driver, process: proc } = controllableDriver(() => []);
+ Object.assign(driver, {
+ execution: {
+ lifetime: "session",
+ transport: { kind: "stdio_stream", protocol: "test.stream.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "vendor_message",
+ },
+ encodeMessage: () => "encoded",
+ });
+ const session = new ProcessLane(driver, minimalCtx());
+ await session.start({ text: "go", terminalOwner: "owner-start" });
+ vi.spyOn(proc.stdin!, "write").mockImplementation(() => {
+ throw new Error("stdin exploded");
+ });
+
+ await expect(session.send({ text: "next", mode: "idle" })).rejects.toThrow("stdin exploded");
+ });
+
+ it.each(["missing", "destroyed", "ended"] as const)(
+ "rejects start when persistent runtime stdin is %s",
+ async (state) => {
+ const { driver, process: proc } = controllableDriver(() => []);
+ Object.assign(driver, {
+ execution: {
+ lifetime: "session",
+ transport: { kind: "stdio_stream", protocol: "test.stream.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "vendor_message",
+ },
+ });
+ if (state === "missing") Object.assign(proc, { stdin: null });
+ else if (state === "destroyed") proc.stdin?.destroy();
+ else proc.stdin?.end();
+
+ const session = new ProcessLane(driver, minimalCtx());
+ await expect(session.start({ text: "go", terminalOwner: "owner-prebound" })).resolves.toEqual({
+ ok: false,
+ reason: "stdin_unavailable",
+ error: "runtime stdin is not writable",
+ });
+ },
+ );
+
+ it.each(["missing", "destroyed", "ended"] as const)(
+ "rejects idle prompts and busy steers when persistent runtime stdin becomes %s",
+ async (state) => {
+ const { driver, process: proc } = controllableDriver(() => []);
+ Object.assign(driver, {
+ execution: {
+ lifetime: "session",
+ transport: { kind: "stdio_stream", protocol: "test.stream.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "vendor_message",
+ },
+ });
+ const session = new ProcessLane(driver, minimalCtx());
+ await expect(session.start({ text: "go", terminalOwner: "owner-start" })).resolves.toMatchObject({ ok: true });
+ if (state === "missing") Object.assign(proc, { stdin: null });
+ else if (state === "destroyed") proc.stdin?.destroy();
+ else proc.stdin?.end();
+
+ await expect(session.send({ text: "next", mode: "idle", terminalOwner: "owner-next" })).resolves.toEqual({
+ ok: false,
+ reason: "stdin_unavailable",
+ error: "runtime stdin is not writable",
+ });
+ await expect(session.send({ text: "steer", mode: "busy", terminalOwner: "owner-start" })).resolves.toEqual({
+ ok: false,
+ reason: "stdin_unavailable",
+ error: "runtime stdin is not writable",
+ });
+ },
+ );
+
+ it("times out a silent transport authority and stops the lane", async () => {
+ vi.useFakeTimers();
+ const { driver, kill } = controllableDriver(() => []);
+ Object.assign(driver, {
+ execution: {
+ lifetime: "session",
+ transport: { kind: "stdio_rpc", protocol: "test.rpc.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ },
+ });
+ const session = new ProcessLane(driver, minimalCtx(), { promptAdmissionTimeoutMs: 25 });
+ const starting = session.start({ text: "go" });
+ await Promise.resolve();
+
+ await vi.advanceTimersByTimeAsync(25);
+ await expect(starting).resolves.toEqual({
+ ok: false,
+ reason: "admission_timeout",
+ error: "runtime did not acknowledge command admission before the deadline",
+ });
+ expect(kill).toHaveBeenCalledOnce();
+ expect(kill).toHaveBeenCalledWith("SIGTERM");
+ });
+});
+
+describe("ProcessLane interrupt", () => {
+ it("sends SIGINT only while the process is open", async () => {
+ const { driver, process: proc, kill } = controllableDriver(() => []);
+ const session = new ProcessLane(driver, minimalCtx());
+ await expect(session.interrupt()).resolves.toBe(false);
+ await session.start({ text: "go" });
+ expect(session.signalCode).toBeNull();
+ await expect(session.interrupt()).resolves.toBe(true);
+ expect(kill).toHaveBeenCalledWith("SIGINT");
+ Object.assign(proc, { exitCode: 0 });
+ await expect(session.interrupt()).resolves.toBe(false);
+ });
+});
+
+describe("ProcessLane stop", () => {
+ it("idempotently kills the detached process group when its root handle is already terminal", async () => {
+ const { driver, process: proc, kill } = controllableDriver(() => []);
+ Object.defineProperty(proc, "pid", { value: 41_002, configurable: true });
+ const session = new ProcessLane(driver, minimalCtx());
+ await session.start({ text: "go" });
+ Object.assign(proc, { exitCode: 0 });
+
+ await Promise.all([
+ session.stop({ reason: "shutdown", forceAfterMs: 0 }),
+ session.stop({ reason: "shutdown", forceAfterMs: 0 }),
+ ]);
+
+ expect(killProcessTree).toHaveBeenCalledOnce();
+ expect(killProcessTree).toHaveBeenCalledWith(41_002, { graceMs: 0 });
+ expect(kill).not.toHaveBeenCalled();
+ });
+
+ it("does not fall back to direct handle kill for a terminal root without a pid", async () => {
+ const { driver, process: proc, kill } = controllableDriver(() => []);
+ const session = new ProcessLane(driver, minimalCtx());
+ await session.start({ text: "go" });
+ Object.assign(proc, { exitCode: 0 });
+
+ await session.stop({ reason: "runtime_exit", forceAfterMs: 0 });
+
+ expect(killProcessTree).not.toHaveBeenCalled();
+ expect(kill).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/daemon/agent-driver/src/controller/process-host.ts b/src/daemon/agent-driver/src/controller/process-host.ts
new file mode 100644
index 000000000..10a85832b
--- /dev/null
+++ b/src/daemon/agent-driver/src/controller/process-host.ts
@@ -0,0 +1,299 @@
+/**
+ * ProcessLane — the generic child-process host for CLI adapters.
+ *
+ * It owns the spawned process, line-buffers stdout, runs each complete line
+ * through `driver.normalizeLine`, and re-emits the resulting `AdapterEvent`s. The
+ * driver supplies the runtime-specific behavior; this class is the uniform
+ * plumbing (start / send / stop / event fan-out) the daemon talks to.
+ *
+ * In-process SDK adapters (Pi) do not use this helper; their `openLane()`
+ * returns a runtime lane backed directly by the vendor session.
+ */
+import { EventEmitter } from "events";
+import type {
+ BackendConfig,
+ AdapterLaunchContext,
+ BackendExecution,
+ LaneAdmission,
+ LaneSendInput,
+ LaneStartInput,
+ LaneStopInput,
+ RuntimeLane,
+ RuntimeLaneEventMap,
+ SpawnedProcess,
+ SpawnedProcessHandle,
+} from "../internal/adapter.js";
+import type { BuiltinBackendId } from "../contract.js";
+import { killProcessTree, SESSION_STOP_GRACE_MS } from "../internal/killTree.js";
+
+const DEFAULT_PROMPT_ADMISSION_TIMEOUT_MS = 60_000;
+
+interface ProcessLaneOptions {
+ /** Observability-only tap for each complete non-empty stdout line, before parsing. */
+ onRawStdoutLine?: (line: string) => void;
+ /** One-shot adapters that do not exit promptly after terminal output. */
+ stopAfterTurn?: boolean;
+ /** Maximum time to wait for a vendor/transport-owned turn receipt. */
+ promptAdmissionTimeoutMs?: number;
+}
+
+export interface ProcessAdapterPrimitives<Id extends string, Config> {
+ readonly id: Id;
+ readonly execution: BackendExecution;
+ readonly currentSessionId: string | null;
+ spawn(ctx: AdapterLaunchContext<Id, Config>): Promise<SpawnedProcess>;
+ normalizeLine(line: string): import("../internal/adapter.js").AdapterEvent[];
+ encodeMessage(
+ text: string,
+ sessionId: string | null,
+ opts?: import("../internal/adapter.js").EncodeMessageOptions,
+ ): string | null;
+}
+
+export class ProcessLane<Id extends string = BuiltinBackendId, Config = BackendConfig> implements RuntimeLane {
+ private readonly events = new EventEmitter();
+ private process: SpawnedProcessHandle | null = null;
+ private started = false;
+ private stdoutBuffer = "";
+ private requestedStopReason?: string;
+ private admissionSequence = 0;
+ private activeTerminalReceipt?: string;
+ private stopPromise?: Promise<void>;
+ private pendingPromptAdmission?: {
+ resolve(admission: LaneAdmission): void;
+ timer?: ReturnType<typeof setTimeout>;
+ };
+
+ constructor(
+ private readonly driver: ProcessAdapterPrimitives<Id, Config>,
+ private readonly ctx: AdapterLaunchContext<Id, Config>,
+ private readonly opts: ProcessLaneOptions = {},
+ ) {}
+
+ get pid(): number | undefined {
+ return this.process?.pid;
+ }
+ get currentSessionId(): string | null {
+ return this.driver.currentSessionId;
+ }
+ get exitCode(): number | null {
+ return this.process?.exitCode ?? null;
+ }
+ get signalCode(): string | null {
+ return this.process?.signalCode ?? null;
+ }
+ get closed(): boolean {
+ return this.process ? this.process.exitCode != null || this.process.signalCode != null : false;
+ }
+
+ on<K extends keyof RuntimeLaneEventMap>(
+ event: K,
+ listener: (value: RuntimeLaneEventMap[K]) => void,
+ ): void {
+ this.events.on(event, listener);
+ }
+
+ /** Spawn the process and deliver the initial prompt (handled inside spawn). */
+ async start(input: LaneStartInput): Promise<LaneAdmission> {
+ if (this.started) {
+ return { ok: false, reason: "runtime_error", error: "runtime session already started" };
+ }
+ this.started = true;
+ const launchCtx: AdapterLaunchContext<Id, Config> = {
+ ...this.ctx,
+ prompt: input.text,
+ config: { ...this.ctx.config, sessionId: input.sessionId ?? this.ctx.config.sessionId },
+ };
+ const pendingAuthority = !input.terminalOwner && this.requiresAuthoritativeOwner()
+ ? this.admitPrompt(undefined, `${this.driver.id}:process:${this.ctx.launchId}`)
+ : undefined;
+ let spawned: SpawnedProcess;
+ try {
+ spawned = await this.driver.spawn(launchCtx);
+ } catch (error) {
+ this.settlePendingPrompt({ ok: false, reason: "runtime_error", error: String(error) });
+ throw error;
+ }
+ const { process: proc } = spawned;
+ this.process = proc;
+ this.attachProcess(proc);
+ this.armPendingPromptTimeout();
+ if (this.driver.execution.lifetime === "session" && !this.writableStdin(proc)) {
+ const rejection = this.stdinUnavailableAdmission();
+ this.settlePendingPrompt(rejection);
+ return pendingAuthority ?? rejection;
+ }
+ return pendingAuthority
+ ?? this.admitPrompt(input.terminalOwner, `${this.driver.id}:process:${proc.pid ?? this.ctx.launchId}`);
+ }
+
+ /** Write a mid-session message (idle prompt or busy steer) to stdin. */
+ async send(input: LaneSendInput): Promise<LaneAdmission> {
+ const proc = this.process;
+ if (!proc || this.closed) return { ok: false, reason: "closed" };
+ const stdin = this.writableStdin(proc);
+ if (!stdin) return this.stdinUnavailableAdmission();
+ if (input.mode === "idle" && this.pendingPromptAdmission) {
+ return { ok: false, reason: "runtime_busy", error: "prompt admission is already pending" };
+ }
+ const encoded = this.driver.encodeMessage(input.text, input.sessionId ?? null, { mode: input.mode });
+ if (!encoded) return { ok: false, reason: "unsupported" };
+ if (input.mode === "idle") {
+ const admission = this.admitPrompt(input.terminalOwner, `${this.driver.id}:send:${++this.admissionSequence}`);
+ try {
+ stdin.write(encoded + "\n");
+ } catch (error) {
+ this.activeTerminalReceipt = undefined;
+ this.settlePendingPrompt({ ok: false, reason: "runtime_error", error: String(error) });
+ throw error;
+ }
+ return admission;
+ }
+ stdin.write(encoded + "\n");
+ const receipt = input.terminalOwner ?? `${this.driver.id}:send:${++this.admissionSequence}`;
+ return {
+ ok: true,
+ acceptedAs: "steer",
+ receipt,
+ };
+ }
+
+ private admitPrompt(terminalOwner: string | undefined, fallbackReceipt: string): Promise<LaneAdmission> {
+ if (terminalOwner) {
+ this.activeTerminalReceipt = terminalOwner;
+ return Promise.resolve({ ok: true, acceptedAs: "prompt", receipt: terminalOwner });
+ }
+ if (!this.requiresAuthoritativeOwner()) {
+ this.activeTerminalReceipt = fallbackReceipt;
+ return Promise.resolve({ ok: true, acceptedAs: "prompt", receipt: fallbackReceipt });
+ }
+ return new Promise<LaneAdmission>((resolve) => {
+ this.pendingPromptAdmission = { resolve };
+ this.armPendingPromptTimeout();
+ });
+ }
+
+ private armPendingPromptTimeout(): void {
+ const pending = this.pendingPromptAdmission;
+ if (!this.process || !pending || pending.timer) return;
+ pending.timer = setTimeout(() => {
+ if (this.pendingPromptAdmission !== pending) return;
+ this.settlePendingPrompt({
+ ok: false,
+ reason: "admission_timeout",
+ error: "runtime did not acknowledge command admission before the deadline",
+ });
+ void this.stop({ reason: "admission_timeout", forceAfterMs: 0 }).catch(() => {});
+ }, this.opts.promptAdmissionTimeoutMs ?? DEFAULT_PROMPT_ADMISSION_TIMEOUT_MS);
+ pending.timer.unref?.();
+ }
+
+ private writableStdin(proc: SpawnedProcessHandle): NonNullable<SpawnedProcessHandle["stdin"]> | null {
+ const stdin = proc.stdin;
+ return stdin && !stdin.destroyed && !stdin.writableEnded && stdin.writable !== false ? stdin : null;
+ }
+
+ private stdinUnavailableAdmission(): LaneAdmission {
+ return {
+ ok: false,
+ reason: "stdin_unavailable",
+ error: "runtime stdin is not writable",
+ };
+ }
+
+ private requiresAuthoritativeOwner(): boolean {
+ return this.driver.execution.terminalOwnership === "vendor_message"
+ || this.driver.execution.terminalOwnership === "transport_request";
+ }
+
+ private settlePendingPrompt(admission: LaneAdmission): void {
+ const pending = this.pendingPromptAdmission;
+ if (!pending) return;
+ this.pendingPromptAdmission = undefined;
+ if (pending.timer) clearTimeout(pending.timer);
+ if (admission.ok) this.activeTerminalReceipt = admission.receipt;
+ pending.resolve(admission);
+ }
+
+ stop(opts: LaneStopInput = {}): Promise<void> {
+ this.settlePendingPrompt({ ok: false, reason: "closed", error: "runtime lane stopped before command admission" });
+ if (!this.process) return Promise.resolve();
+ this.stopPromise ??= this.stopProcess(opts);
+ return this.stopPromise;
+ }
+
+ private async stopProcess(opts: LaneStopInput): Promise<void> {
+ const proc = this.process;
+ if (!proc) return;
+ this.requestedStopReason = opts?.reason;
+ const pid = proc.pid;
+ if (pid) {
+ await killProcessTree(pid, { graceMs: opts?.forceAfterMs ?? SESSION_STOP_GRACE_MS });
+ } else if (!this.closed) {
+ proc.kill(opts?.signal ?? "SIGTERM");
+ }
+ }
+
+ async interrupt(): Promise<boolean> {
+ const proc = this.process;
+ if (!proc || this.closed) return false;
+ return proc.kill("SIGINT");
+ }
+
+ /** Wire stdout line-buffering → normalizeLine → runtime_event, plus lifecycle. */
+ private attachProcess(proc: SpawnedProcessHandle): void {
+ proc.stdout?.on("data", (chunk) => {
+ const chunkText = chunk.toString();
+ this.events.emit("stdout", chunkText);
+ this.stdoutBuffer += chunkText;
+ const lines = this.stdoutBuffer.split("\n");
+ this.stdoutBuffer = lines.pop() || "";
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ try {
+ this.opts.onRawStdoutLine?.(line);
+ } catch {
+ /* an observability tap cannot alter runtime parsing */
+ }
+ for (const event of this.driver.normalizeLine(line)) {
+ if (event.kind === "turn_owner" && event.receipt.trim()) {
+ this.settlePendingPrompt({ ok: true, acceptedAs: "prompt", receipt: event.receipt });
+ } else if (event.kind === "error" && this.pendingPromptAdmission) {
+ this.settlePendingPrompt({ ok: false, reason: "runtime_error", error: event.message });
+ }
+ const ownedEvent = event.kind === "turn_end" && !event.turnOwner && this.activeTerminalReceipt
+ ? { ...event, turnOwner: this.activeTerminalReceipt }
+ : event;
+ this.events.emit("runtime_event", ownedEvent);
+ const ownsTerminal = ownedEvent.kind === "turn_end"
+ && Boolean(this.activeTerminalReceipt)
+ && ownedEvent.turnOwner === this.activeTerminalReceipt;
+ if (ownsTerminal) this.activeTerminalReceipt = undefined;
+ if (ownsTerminal && this.opts.stopAfterTurn) {
+ void this.stop({ reason: "turn_complete", forceAfterMs: 2_000 });
+ }
+ }
+ }
+ });
+ proc.stderr?.on("data", (chunk) => {
+ const text = chunk.toString().trim();
+ if (text) this.events.emit("stderr", text);
+ });
+ proc.on("error", (err) => {
+ this.settlePendingPrompt({ ok: false, reason: "runtime_error", error: String(err) });
+ this.events.emit("error", err);
+ });
+ proc.on("exit", (code, signal) => {
+ this.settlePendingPrompt({ ok: false, reason: "closed", error: "runtime exited before command admission" });
+ this.events.emit("exit", { code, signal, reason: this.requestedStopReason ? "requested" : "runtime_exit" });
+ });
+ }
+}
+
+export function createProcessLane<Id extends string, Config>(
+ driver: ProcessAdapterPrimitives<Id, Config>,
+ ctx: AdapterLaunchContext<Id, Config>,
+ opts?: ProcessLaneOptions,
+): ProcessLane<Id, Config> {
+ return new ProcessLane(driver, ctx, opts);
+}
diff --git a/src/daemon/src/runtime/sdkRuntimeSession.test.ts b/src/daemon/agent-driver/src/controller/sdk-host.test.ts
similarity index 57%
rename from src/daemon/src/runtime/sdkRuntimeSession.test.ts
rename to src/daemon/agent-driver/src/controller/sdk-host.test.ts
index 2c05b839a..f4cd94b1b 100644
--- a/src/daemon/src/runtime/sdkRuntimeSession.test.ts
+++ b/src/daemon/agent-driver/src/controller/sdk-host.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from "vitest";
-import { SdkRuntimeSession, type SdkSessionHandle } from "./sdkRuntimeSession.js";
+import { SdkLane } from "./sdk-host.js";
+import type { VendorSessionHandle } from "../internal/adapter.js";
/**
* See plans/sdk-runtime-session-live-isstreaming-guard.md — `send()`'s idle
@@ -14,15 +15,60 @@ function fakeHandle(isStreaming = false) {
isStreaming,
prompt: vi.fn().mockResolvedValue(undefined),
steer: vi.fn().mockResolvedValue(undefined),
- } as SdkSessionHandle & { isStreaming: boolean; prompt: ReturnType<typeof vi.fn>; steer: ReturnType<typeof vi.fn> };
+ } as VendorSessionHandle & { isStreaming: boolean; prompt: ReturnType<typeof vi.fn>; steer: ReturnType<typeof vi.fn> };
}
-describe("SdkRuntimeSession.send", () => {
+describe("SdkLane.send", () => {
+ it("resolves admission before the vendor prompt promise settles", async () => {
+ let settlePrompt!: () => void;
+ const handle = fakeHandle(false);
+ handle.prompt.mockImplementation(() => new Promise<void>((resolve) => { settlePrompt = resolve; }));
+ const session = new SdkLane(handle, "s1");
+
+ await expect(session.send({ text: "hi", mode: "idle" })).resolves.toEqual({
+ ok: true,
+ acceptedAs: "prompt",
+ receipt: "s1:sdk:1",
+ });
+ expect(handle.prompt).toHaveBeenCalledWith("hi");
+ settlePrompt();
+ });
+
+ it("emits the exact invocation owner only when its prompt promise settles", async () => {
+ const pending: Array<{ resolve: () => void; promise: Promise<void> }> = [];
+ const handle = fakeHandle(false);
+ handle.prompt.mockImplementation(() => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => { resolve = done; });
+ pending.push({ resolve, promise });
+ return promise;
+ });
+ const session = new SdkLane(handle, "s1", { terminalOnPromptSettled: true });
+ const received: unknown[] = [];
+ session.on("runtime_event", (event) => received.push(event));
+
+ await session.send({ text: "same", mode: "idle", terminalOwner: "pi:1" });
+ expect(received).toEqual([]);
+ pending[0]!.resolve();
+ await pending[0]!.promise;
+ await Promise.resolve();
+ expect(received).toEqual([
+ { kind: "session_init", sessionId: "s1" },
+ { kind: "turn_end", sessionId: "s1", turnOwner: "pi:1" },
+ ]);
+
+ await session.send({ text: "same", mode: "idle", terminalOwner: "pi:2" });
+ pending[1]!.resolve();
+ await pending[1]!.promise;
+ await Promise.resolve();
+ expect(received.at(-1)).toEqual({ kind: "turn_end", sessionId: "s1", turnOwner: "pi:2" });
+ });
+
it("idle send while not streaming calls prompt() directly, no wait", async () => {
const handle = fakeHandle(false);
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
- await session.send("hi", "idle");
+ await session.send({ text: "hi", mode: "idle" });
expect(handle.prompt).toHaveBeenCalledWith("hi");
expect(handle.steer).not.toHaveBeenCalled();
@@ -30,9 +76,9 @@ describe("SdkRuntimeSession.send", () => {
it('busy send always steers, even while not streaming (mode: "busy" never calls prompt)', async () => {
const handle = fakeHandle(false);
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
- await session.send("hi", "busy");
+ await session.send({ text: "hi", mode: "busy" });
expect(handle.steer).toHaveBeenCalledWith("hi");
expect(handle.prompt).not.toHaveBeenCalled();
@@ -42,9 +88,9 @@ describe("SdkRuntimeSession.send", () => {
vi.useFakeTimers();
try {
const handle = fakeHandle(true);
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
- const pending = session.send("hi", "idle");
+ const pending = session.send({ text: "hi", mode: "idle" });
await vi.advanceTimersByTimeAsync(50);
// Still streaming for the first couple of polls — must not have prompted yet.
expect(handle.prompt).not.toHaveBeenCalled();
@@ -64,9 +110,9 @@ describe("SdkRuntimeSession.send", () => {
vi.useFakeTimers();
try {
const handle = fakeHandle(true); // stays streaming forever
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
- const pending = session.send("hi", "idle");
+ const pending = session.send({ text: "hi", mode: "idle" });
await vi.advanceTimersByTimeAsync(1100);
await pending;
@@ -77,11 +123,34 @@ describe("SdkRuntimeSession.send", () => {
}
});
+ it("fails an owned root invocation instead of rebinding it to a still-streaming steer", async () => {
+ vi.useFakeTimers();
+ try {
+ const handle = fakeHandle(true);
+ const session = new SdkLane(handle, "s1", { terminalOnPromptSettled: true });
+ const received: unknown[] = [];
+ session.on("runtime_event", (event) => received.push(event));
+
+ await session.send({ text: "hi", mode: "idle", terminalOwner: "pi:2" });
+ await vi.advanceTimersByTimeAsync(1100);
+
+ expect(handle.prompt).not.toHaveBeenCalled();
+ expect(handle.steer).not.toHaveBeenCalled();
+ expect(received).toEqual([
+ { kind: "session_init", sessionId: "s1" },
+ { kind: "error", message: "SDK remained busy before the next owned prompt" },
+ { kind: "turn_end", sessionId: "s1", turnOwner: "pi:2" },
+ ]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("a handle with no isStreaming getter goes straight to prompt() for idle sends (backward compatible)", async () => {
const handle = { prompt: vi.fn().mockResolvedValue(undefined), steer: vi.fn().mockResolvedValue(undefined) };
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
- await session.send("hi", "idle");
+ await session.send({ text: "hi", mode: "idle" });
expect(handle.prompt).toHaveBeenCalledWith("hi");
});
@@ -89,11 +158,11 @@ describe("SdkRuntimeSession.send", () => {
it("a thrown prompt() surfaces as a runtime_event error instead of rejecting send()", async () => {
const handle = fakeHandle(false);
handle.prompt.mockRejectedValue(new Error("boom"));
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
const received: unknown[] = [];
session.on("runtime_event", (e) => received.push(e));
- await expect(session.send("hi", "idle")).resolves.toEqual({ ok: true });
+ await expect(session.send({ text: "hi", mode: "idle" })).resolves.toMatchObject({ ok: true });
expect(received).toContainEqual({ kind: "error", message: "boom" });
});
@@ -102,33 +171,33 @@ describe("SdkRuntimeSession.send", () => {
// will ever say it's over, unlike a failed steer() (see below), which
// injects into an already-running turn that still emits its own real
// turn_end later. Without this synthetic turn_end, the caller (e.g.
- // `SdkManagedSession.start()`, which fires the very first turn this way)
+ // `logical session.start()`, which fires the very first turn this way)
// keeps the agent looking busy/running until the stall watchdog eventually
// notices and terminates it, minutes later.
it("a thrown prompt() also emits a synthetic turn_end right after the error, so the caller doesn't stay stuck 'running'", async () => {
const handle = fakeHandle(false);
handle.prompt.mockRejectedValue(new Error("boom"));
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
const received: unknown[] = [];
session.on("runtime_event", (e) => received.push(e));
- await session.send("hi", "idle");
+ await session.send({ text: "hi", mode: "idle" });
expect(received).toEqual([
{ kind: "session_init", sessionId: "s1" },
{ kind: "error", message: "boom" },
- { kind: "turn_end", sessionId: "s1" },
+ { kind: "turn_end", sessionId: "s1", turnOwner: "s1:sdk:1" },
]);
});
it("a thrown steer() surfaces as a runtime_event error instead of rejecting send()", async () => {
const handle = fakeHandle(false);
handle.steer.mockRejectedValue(new Error("nope"));
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
const received: unknown[] = [];
session.on("runtime_event", (e) => received.push(e));
- await expect(session.send("hi", "busy")).resolves.toEqual({ ok: true });
+ await expect(session.send({ text: "hi", mode: "busy" })).resolves.toMatchObject({ ok: true });
expect(received).toContainEqual({ kind: "error", message: "nope" });
});
@@ -139,11 +208,11 @@ describe("SdkRuntimeSession.send", () => {
it("a thrown steer() does NOT emit a synthetic turn_end (the underlying turn is still running)", async () => {
const handle = fakeHandle(false);
handle.steer.mockRejectedValue(new Error("nope"));
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
const received: unknown[] = [];
session.on("runtime_event", (e) => received.push(e));
- await session.send("hi", "busy");
+ await session.send({ text: "hi", mode: "busy" });
expect(received).not.toContainEqual(expect.objectContaining({ kind: "turn_end" }));
});
@@ -156,11 +225,11 @@ describe("SdkRuntimeSession.send", () => {
try {
const handle = fakeHandle(true); // stays streaming forever
handle.steer.mockRejectedValue(new Error("nope"));
- const session = new SdkRuntimeSession(handle, "s1");
+ const session = new SdkLane(handle, "s1");
const received: unknown[] = [];
session.on("runtime_event", (e) => received.push(e));
- const pending = session.send("hi", "idle");
+ const pending = session.send({ text: "hi", mode: "idle" });
await vi.advanceTimersByTimeAsync(1100);
await pending;
diff --git a/src/daemon/agent-driver/src/controller/sdk-host.ts b/src/daemon/agent-driver/src/controller/sdk-host.ts
new file mode 100644
index 000000000..b606f636b
--- /dev/null
+++ b/src/daemon/agent-driver/src/controller/sdk-host.ts
@@ -0,0 +1,132 @@
+/** In-process lane with live-streaming prompt/steer protection. */
+import { EventEmitter } from "events";
+import type {
+ AdapterEvent,
+ InputMode,
+ LaneAdmission,
+ LaneSendInput,
+ LaneStartInput,
+ RuntimeLane,
+ RuntimeLaneEventMap,
+ VendorSessionHandle,
+} from "../internal/adapter.js";
+
+/** Poll briefly before degrading an idle prompt to a safe steer. */
+const IDLE_PROMPT_RETRY_MS = 25;
+const IDLE_PROMPT_MAX_WAIT_MS = 1000;
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function errorMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+export class SdkLane implements RuntimeLane {
+ private readonly events = new EventEmitter();
+ private sentInit = false;
+ private admissionSequence = 0;
+
+ constructor(
+ private readonly handle: VendorSessionHandle,
+ private readonly sessionId: string,
+ private readonly options: { terminalOnPromptSettled?: boolean } = {},
+ ) {}
+
+ on<K extends keyof RuntimeLaneEventMap>(
+ event: K,
+ listener: (value: RuntimeLaneEventMap[K]) => void,
+ ): void {
+ this.events.on(event, listener);
+ }
+
+ reportUnexpectedExit(info: { code?: number | null; signal?: string | null } = {}): void {
+ this.events.emit("exit", {
+ code: info.code ?? null,
+ signal: info.signal ?? null,
+ reason: "runtime_exit",
+ });
+ }
+
+ emitEvents(events: AdapterEvent[]): void {
+ if (!this.sentInit && events.length > 0) {
+ this.sentInit = true;
+ this.events.emit("runtime_event", { kind: "session_init", sessionId: this.sessionId } as AdapterEvent);
+ }
+ for (const e of events) this.events.emit("runtime_event", e);
+ }
+
+ start(input: LaneStartInput): Promise<LaneAdmission> {
+ return this.send({ ...input, mode: "idle" });
+ }
+
+ /** Delivers immediately; failures return through normalized events. */
+ send(input: LaneSendInput): Promise<LaneAdmission> {
+ const receipt = input.terminalOwner ?? `${this.sessionId}:sdk:${++this.admissionSequence}`;
+ void this.deliver(input.text, input.mode, receipt);
+ return Promise.resolve({
+ ok: true,
+ acceptedAs: input.mode === "busy" ? "steer" : "prompt",
+ receipt,
+ });
+ }
+
+ private async deliver(text: string, mode: InputMode, terminalOwner?: string): Promise<void> {
+ try {
+ if (mode === "busy") {
+ await this.handle.steer(text);
+ return;
+ }
+ const stillStreaming = this.handle.isStreaming && !(await this.waitForStreamingToClear());
+ if (stillStreaming) {
+ if (this.options.terminalOnPromptSettled) {
+ this.emitEvents([
+ { kind: "error", message: "SDK remained busy before the next owned prompt" },
+ { kind: "turn_end", sessionId: this.sessionId, turnOwner: terminalOwner },
+ ]);
+ return;
+ }
+ await this.handle.steer(text);
+ return;
+ }
+ try {
+ await this.handle.prompt(text);
+ if (this.options.terminalOnPromptSettled) {
+ this.emitEvents([{ kind: "turn_end", sessionId: this.sessionId, turnOwner: terminalOwner }]);
+ }
+ } catch (err) {
+ this.emitEvents([
+ { kind: "error", message: errorMessage(err) },
+ { kind: "turn_end", sessionId: this.sessionId, turnOwner: terminalOwner },
+ ]);
+ }
+ } catch (err) {
+ this.emitEvents([{ kind: "error", message: errorMessage(err) }]);
+ }
+ }
+
+ private async waitForStreamingToClear(): Promise<boolean> {
+ const deadline = Date.now() + IDLE_PROMPT_MAX_WAIT_MS;
+ while (this.handle.isStreaming) {
+ if (Date.now() >= deadline) return false;
+ await delay(IDLE_PROMPT_RETRY_MS);
+ }
+ return true;
+ }
+
+ async stop(): Promise<void> {
+ if (this.handle.isStreaming && this.handle.abort) await this.handle.abort();
+ await this.handle.dispose?.();
+ }
+
+ async interrupt(): Promise<boolean> {
+ if (!this.handle.isStreaming || !this.handle.abort) return false;
+ await this.handle.abort();
+ return true;
+ }
+
+ get currentSessionId(): string {
+ return this.sessionId;
+ }
+}
diff --git a/src/daemon/agent-driver/src/host.ts b/src/daemon/agent-driver/src/host.ts
new file mode 100644
index 000000000..628758272
--- /dev/null
+++ b/src/daemon/agent-driver/src/host.ts
@@ -0,0 +1,14 @@
+/** Stable host-integration boundary for daemon/runtime embedders. */
+export type * from "./public-contract.js";
+export { createAgentDriverSdk as createBuiltinAgentDriverSdk } from "./sdk.js";
+export { createDefaultAgentDriverHost } from "./host/default-host.js";
+export { scrubDriverErrorMessage as scrubAgentDriverDiagnosticText } from "./internal/errors.js";
+export type {
+ AgentDriverHost,
+ CreateAgentDriverSdkOptions,
+ DefaultAgentDriverHostOptions,
+ PrepareExecutionInput,
+ PrepareExecutionResult,
+ PreparedExecutionResource,
+ RawOutputEvent,
+} from "./contract.js";
diff --git a/src/daemon/agent-driver/src/host/default-host.test.ts b/src/daemon/agent-driver/src/host/default-host.test.ts
new file mode 100644
index 000000000..c315f115a
--- /dev/null
+++ b/src/daemon/agent-driver/src/host/default-host.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it, vi } from "vitest";
+import { createDefaultAgentDriverHost } from "./default-host.js";
+
+describe("createDefaultAgentDriverHost", () => {
+ it("prepares an isolated environment snapshot and forwards raw output", async () => {
+ const environment = { TEST_VALUE: "before" };
+ const onRawOutput = vi.fn();
+ const host = createDefaultAgentDriverHost({ environment, onRawOutput });
+ environment.TEST_VALUE = "after";
+
+ const prepared = await host.prepareExecution({ backend: "claude", launchId: "launch", workingDirectory: "/tmp" });
+ expect(prepared).toMatchObject({ ok: true });
+ if (!prepared.ok) throw new Error("expected a prepared resource");
+ expect(prepared.resource.environmentLayers.base).toEqual({ TEST_VALUE: "before" });
+ await expect(prepared.resource.release({
+ reason: "normal",
+ signal: new AbortController().signal,
+ deadlineAt: Date.now() + 1_000,
+ })).resolves.toBeUndefined();
+
+ const event = { backend: "claude", launchId: "launch", stream: "stdout" as const, text: "line" };
+ host.onRawOutput(event);
+ expect(onRawOutput).toHaveBeenCalledWith(event);
+ expect(host.now()).toBeTypeOf("number");
+ expect(host.createId()).toMatch(/^[0-9a-f-]{36}$/);
+ });
+
+ it("works with default options and without a raw-output subscriber", async () => {
+ const host = createDefaultAgentDriverHost();
+ const prepared = await host.prepareExecution({ backend: "codex", launchId: "launch", workingDirectory: "/tmp" });
+ expect(prepared.ok).toBe(true);
+ expect(() => host.onRawOutput({ backend: "codex", launchId: "launch", stream: "stderr", text: "line" }))
+ .not.toThrow();
+ });
+});
diff --git a/src/daemon/agent-driver/src/host/default-host.ts b/src/daemon/agent-driver/src/host/default-host.ts
new file mode 100644
index 000000000..230a5d62c
--- /dev/null
+++ b/src/daemon/agent-driver/src/host/default-host.ts
@@ -0,0 +1,34 @@
+import { randomUUID } from "node:crypto";
+import type {
+ AgentDriverHost,
+ DefaultAgentDriverHostOptions,
+ PreparedExecutionResource,
+} from "../contract.js";
+
+export function createDefaultAgentDriverHost(
+ options: DefaultAgentDriverHostOptions = {},
+): AgentDriverHost {
+ const environment = { ...(options.environment ?? process.env) };
+ return {
+ async prepareExecution() {
+ const resource: PreparedExecutionResource = {
+ environmentLayers: {
+ base: environment,
+ hostStatic: {},
+ identityProtected: {},
+ platformProtected: {},
+ runtimeProtected: {},
+ networkProtected: {},
+ credentialSensitive: {},
+ },
+ async release() {},
+ };
+ return { ok: true, resource };
+ },
+ onRawOutput(event) {
+ options.onRawOutput?.(event);
+ },
+ now: () => Date.now(),
+ createId: () => randomUUID(),
+ };
+}
diff --git a/src/daemon/agent-driver/src/index.ts b/src/daemon/agent-driver/src/index.ts
new file mode 100644
index 000000000..0e460ffc4
--- /dev/null
+++ b/src/daemon/agent-driver/src/index.ts
@@ -0,0 +1,9 @@
+export * from "./public-contract.js";
+export { createAgentDriverSdk } from "./public-sdk.js";
+export type { PublicAgentDriverSdkOptions } from "./public-sdk.js";
+export { toBuiltinBackendSelection } from "./builtin-config.js";
+export type { BuiltinBackendSelection, BuiltinRuntimeConfigInput } from "./builtin-config.js";
+export {
+ BUILTIN_BACKEND_IDS,
+ capabilitiesFor as getBuiltinBackendCapabilities,
+} from "./registry.js";
diff --git a/src/daemon/agent-driver/src/internal/adapter.ts b/src/daemon/agent-driver/src/internal/adapter.ts
new file mode 100644
index 000000000..a9040caa3
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/adapter.ts
@@ -0,0 +1,189 @@
+import type {
+ BuiltinBackendId,
+ ClaudeConfig,
+ CodexConfig,
+ CursorConfig,
+ OpenCodeConfig,
+ PiConfig,
+ PreparedExecutionResource,
+ JsonValue,
+} from "../contract.js";
+
+export type BackendConfig = ClaudeConfig | CodexConfig | CursorConfig | OpenCodeConfig | PiConfig;
+
+export type WellKnownTransportKind =
+ | "stdio_stream"
+ | "stdio_rpc"
+ | "http_sse"
+ | "in_process_sdk"
+ | "one_shot_cli";
+
+export interface AdapterTransport {
+ readonly kind: WellKnownTransportKind | (string & {});
+ readonly protocol: string;
+ readonly metadata?: Readonly<Record<string, JsonValue>>;
+}
+
+export type TerminalOwnership =
+ | "transport_request"
+ | "vendor_message"
+ | "prompt_invocation"
+ | "lane_generation";
+
+export interface BackendExecution {
+ readonly lifetime: "session" | "turn";
+ readonly transport: AdapterTransport;
+ readonly wakeStart: "immediate" | "deferred";
+ readonly terminalOwnership: TerminalOwnership;
+}
+
+export type InputMode = "busy" | "idle";
+export interface EncodeMessageOptions { mode?: InputMode }
+
+export type AdapterEvent =
+ | { kind: "session_init"; sessionId: string }
+ | { kind: "thinking"; text: string }
+ | { kind: "text"; text: string }
+ | { kind: "tool_call"; name: string; input: unknown }
+ | { kind: "tool_output"; name: string }
+ | { kind: "compaction_started" }
+ | { kind: "compaction_finished" }
+ | { kind: "review_started" }
+ | { kind: "review_finished" }
+ | { kind: "internal_progress"; source?: string; itemType?: string; payloadBytes?: number }
+ | { kind: "runtime_diagnostic"; severity?: string; source?: string; message: string }
+ | { kind: "runtime_metric"; name: "sse_reconnect"; increment: 1 }
+ | { kind: "turn_owner"; receipt: string }
+ | { kind: "turn_end"; sessionId?: string; turnOwner?: string }
+ | { kind: "error"; message: string }
+ | { kind: "telemetry"; name: "token_usage" | "rate_limits"; source: string; usageKind?: string; attrs: Record<string, unknown> };
+
+export interface LaneStartInput {
+ readonly text: string;
+ readonly sessionId?: string;
+ readonly terminalOwner?: string;
+}
+
+export interface LaneSendInput extends LaneStartInput {
+ readonly mode: InputMode;
+}
+
+export type LaneAdmission =
+ | { readonly ok: true; readonly acceptedAs: "prompt" | "steer"; readonly receipt: string }
+ | { readonly ok: false; readonly reason: string; readonly error?: string };
+
+export interface LaneInterruptInput {
+ readonly requestId?: string;
+ readonly reason?: string;
+}
+
+export interface LaneStopInput {
+ readonly reason?: string;
+ readonly signal?: "SIGTERM" | "SIGINT" | "SIGKILL";
+ readonly forceAfterMs?: number;
+}
+
+export interface RuntimeLaneExit {
+ readonly code: number | null;
+ readonly signal: string | null;
+ readonly reason: "requested" | "runtime_exit";
+}
+
+export interface RuntimeLaneEventMap {
+ readonly runtime_event: AdapterEvent;
+ readonly stderr: string;
+ readonly error: unknown;
+ readonly exit: RuntimeLaneExit;
+}
+
+export interface RuntimeLane {
+ readonly currentSessionId: string | null;
+ start(input: LaneStartInput): Promise<LaneAdmission>;
+ send(input: LaneSendInput): Promise<LaneAdmission>;
+ interrupt(input: LaneInterruptInput): Promise<boolean>;
+ stop(input: LaneStopInput): Promise<void>;
+ on<K extends keyof RuntimeLaneEventMap>(
+ event: K,
+ listener: (value: RuntimeLaneEventMap[K]) => void,
+ ): void;
+}
+
+export interface RuntimeLaneOpenOptions {
+ readonly onRawStdoutLine?: (line: string) => void;
+}
+
+export interface AdapterRuntimeContext {
+ agentId: string;
+ serverId: string;
+ computerId: string;
+ computerName: string;
+ hostname: string;
+ os: string;
+ daemonVersion: string;
+ workspacePath: string;
+}
+
+export interface AdapterLaunchConfig<Config = BackendConfig> {
+ sessionId?: string;
+ runtimeConfig?: Config;
+ description?: string;
+ runtimeContext?: AdapterRuntimeContext;
+ agentName?: string;
+ agentDiscriminator?: string;
+ agentHandle?: string;
+ ownerHandle?: string;
+}
+
+export interface AdapterLaunchContext<Id extends string = BuiltinBackendId, Config = BackendConfig> {
+ backend: Id;
+ agentId: string;
+ launchId: string;
+ workingDirectory: string;
+ standingPrompt: string;
+ prompt: string;
+ prepared: PreparedExecutionResource;
+ config: AdapterLaunchConfig<Config>;
+}
+
+export interface SpawnedProcessHandle {
+ readonly stdout?: { on(event: "data", listener: (chunk: { toString(): string }) => void): unknown } | null;
+ readonly stderr?: { on(event: "data", listener: (chunk: { toString(): string }) => void): unknown } | null;
+ readonly stdin?: {
+ readonly destroyed?: boolean;
+ readonly writable?: boolean;
+ readonly writableEnded?: boolean;
+ write(chunk: string): unknown;
+ } | null;
+ readonly pid?: number;
+ readonly exitCode: number | null;
+ readonly signalCode: string | null;
+ kill(signal?: "SIGTERM" | "SIGINT" | "SIGKILL"): boolean;
+ on(event: "error", listener: (error: unknown) => void): unknown;
+ on(event: "exit" | "close", listener: (code: number | null, signal: string | null) => void): unknown;
+}
+
+export interface SpawnedProcess { process: SpawnedProcessHandle }
+export interface ProbeResult { status: "healthy" | "unhealthy"; version?: string; lastError?: string }
+
+export interface VendorSessionHandle {
+ prompt(text: string): void | Promise<void>;
+ steer(text: string): void | Promise<void>;
+ abort?(): void | Promise<void>;
+ dispose?(): void | Promise<void>;
+ readonly isStreaming?: boolean;
+}
+
+export interface BackendAdapter<Id extends string = BuiltinBackendId, Config = BackendConfig> {
+ readonly id: Id;
+ readonly instructionDelivery:
+ | { readonly kind: "native" }
+ | { readonly kind: "workspace_file"; readonly canonical: string; readonly aliases: readonly string[] };
+ readonly execution: BackendExecution;
+ probe(command?: string): ProbeResult | Promise<ProbeResult>;
+ openLane(
+ ctx: AdapterLaunchContext<Id, Config>,
+ options?: RuntimeLaneOpenOptions,
+ ): Promise<RuntimeLane>;
+ /** Binds a logical turn to an authoritative vendor/transport invocation. */
+ beginTurn?(): string;
+}
diff --git a/src/daemon/src/drivers/agentFile.test.ts b/src/daemon/agent-driver/src/internal/agentFile.test.ts
similarity index 76%
rename from src/daemon/src/drivers/agentFile.test.ts
rename to src/daemon/agent-driver/src/internal/agentFile.test.ts
index 49d81b76f..2ce2102e3 100644
--- a/src/daemon/src/drivers/agentFile.test.ts
+++ b/src/daemon/agent-driver/src/internal/agentFile.test.ts
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from "vitest";
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
-import { writeAgentFile, ensureSymlinks, CANONICAL_FILE, SYMLINK_ALIASES } from "./agentFile";
+import { writeAgentFile, ensureSymlinks, CANONICAL_FILE, SYMLINK_ALIASES } from "./agentFile.js";
let tmpDir: string;
@@ -47,6 +47,19 @@ describe("writeAgentFile", () => {
expect(stat.isSymbolicLink()).toBe(true);
expect(fs.readlinkSync(path.join(tmpDir, SYMLINK_ALIASES[0]))).toBe(CANONICAL_FILE);
});
+
+ it("materializes the adapter's declared canonical file and aliases", () => {
+ writeAgentFile(tmpDir, "custom", { canonical: "SYSTEM.md", aliases: ["BOT.md", "CLAUDE.md"] });
+ expect(fs.readFileSync(path.join(tmpDir, "SYSTEM.md"), "utf8")).toBe("custom");
+ expect(fs.readlinkSync(path.join(tmpDir, "BOT.md"))).toBe("SYSTEM.md");
+ expect(fs.readlinkSync(path.join(tmpDir, "CLAUDE.md"))).toBe("SYSTEM.md");
+ });
+
+ it("rejects adapter-declared instruction paths that escape the workspace", () => {
+ expect(() => writeAgentFile(tmpDir, "unsafe", { canonical: "../outside.md", aliases: [] }))
+ .toThrow("plain workspace basenames");
+ expect(fs.existsSync(path.join(tmpDir, "..", "outside.md"))).toBe(false);
+ });
});
describe("ensureSymlinks", () => {
diff --git a/src/daemon/src/drivers/agentFile.ts b/src/daemon/agent-driver/src/internal/agentFile.ts
similarity index 70%
rename from src/daemon/src/drivers/agentFile.ts
rename to src/daemon/agent-driver/src/internal/agentFile.ts
index e0fa21747..6f68127df 100644
--- a/src/daemon/src/drivers/agentFile.ts
+++ b/src/daemon/agent-driver/src/internal/agentFile.ts
@@ -37,19 +37,25 @@ function hasContentChanged(filePath: string, newContent: string): boolean {
}
}
-export function ensureSymlinks(workDir: string): void {
- const canonicalPath = join(workDir, CANONICAL_FILE);
+export function ensureSymlinks(
+ workDir: string,
+ canonical = CANONICAL_FILE,
+ aliases: readonly string[] = SYMLINK_ALIASES,
+): void {
+ assertInstructionFileName(canonical);
+ const canonicalPath = join(workDir, canonical);
if (!existsSync(canonicalPath)) return;
- for (const alias of SYMLINK_ALIASES) {
- if (alias === CANONICAL_FILE) continue;
+ for (const alias of aliases) {
+ assertInstructionFileName(alias);
+ if (alias === canonical) continue;
const aliasPath = join(workDir, alias);
try {
const stat = lstatSync(aliasPath);
if (stat.isSymbolicLink()) {
const target = readlinkSync(aliasPath);
- if (target === CANONICAL_FILE) continue;
+ if (target === canonical) continue;
unlinkSync(aliasPath);
} else {
const aliasContent = readFileSync(aliasPath, "utf-8");
@@ -62,7 +68,7 @@ export function ensureSymlinks(workDir: string): void {
}
try {
- symlinkSync(CANONICAL_FILE, aliasPath);
+ symlinkSync(canonical, aliasPath);
} catch (err: unknown) {
const code = (err as NodeJS.ErrnoException)?.code;
if (code === "EEXIST") {
@@ -81,12 +87,26 @@ export function ensureSymlinks(workDir: string): void {
* symlinks to it. Only writes if content has changed (avoids unnecessary fs churn).
* Returns true if the file was actually written.
*/
-export function writeAgentFile(workDir: string, systemPromptContent: string): boolean {
- const filePath = join(workDir, CANONICAL_FILE);
+export function writeAgentFile(
+ workDir: string,
+ systemPromptContent: string,
+ strategy: { readonly canonical: string; readonly aliases: readonly string[] } = {
+ canonical: CANONICAL_FILE,
+ aliases: SYMLINK_ALIASES,
+ },
+): boolean {
+ assertInstructionFileName(strategy.canonical);
+ const filePath = join(workDir, strategy.canonical);
const changed = hasContentChanged(filePath, systemPromptContent);
if (changed) {
writeFileSync(filePath, systemPromptContent, "utf-8");
}
- ensureSymlinks(workDir);
+ ensureSymlinks(workDir, strategy.canonical, strategy.aliases);
return changed;
}
+
+function assertInstructionFileName(name: string): void {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || name === "." || name === "..") {
+ throw new Error("Instruction file names must be plain workspace basenames");
+ }
+}
diff --git a/src/daemon/src/drivers/cliLink.test.ts b/src/daemon/agent-driver/src/internal/cliLink.test.ts
similarity index 98%
rename from src/daemon/src/drivers/cliLink.test.ts
rename to src/daemon/agent-driver/src/internal/cliLink.test.ts
index a766ff719..f18be7a91 100644
--- a/src/daemon/src/drivers/cliLink.test.ts
+++ b/src/daemon/agent-driver/src/internal/cliLink.test.ts
@@ -2,7 +2,7 @@ import { describe, it, expect, afterEach } from "vitest";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
-import { writeCliLink } from "./cliLink";
+import { writeCliLink } from "./cliLink.js";
const tmpDirs: string[] = [];
function mkTmp(): string {
diff --git a/src/daemon/src/drivers/cliLink.ts b/src/daemon/agent-driver/src/internal/cliLink.ts
similarity index 100%
rename from src/daemon/src/drivers/cliLink.ts
rename to src/daemon/agent-driver/src/internal/cliLink.ts
diff --git a/src/daemon/agent-driver/src/internal/cliTransport.test.ts b/src/daemon/agent-driver/src/internal/cliTransport.test.ts
new file mode 100644
index 000000000..e3efab87b
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/cliTransport.test.ts
@@ -0,0 +1,123 @@
+import { afterEach, describe, expect, it } from "vitest";
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+import { prepareCliTransport, type CliTransportConfig } from "./cliTransport.js";
+import type { ClaudeConfig } from "../contract.js";
+import type { AdapterLaunchContext } from "./adapter.js";
+import { fakeLaunchContext, fakePrepared } from "../testing/adapter-fixture.js";
+
+const tmpDirs: string[] = [];
+function mkTmp(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "clitransport-"));
+ tmpDirs.push(dir);
+ return dir;
+}
+
+afterEach(() => {
+ for (const dir of tmpDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+function baseCtx(workingDirectory: string, overrides: Partial<AdapterLaunchContext> = {}): AdapterLaunchContext {
+ return fakeLaunchContext("claude", workingDirectory, {
+ prepared: fakePrepared({
+ base: { PATH: "/host/bin", KEEP: "base" },
+ platformProtected: {
+ ALOOK_ID: "agent_1",
+ ALOOK_CLI: "alook",
+ ALOOK_LAUNCH_ID: "launch_1",
+ },
+ networkProtected: {
+ ALOOK_PROXY_URL: "http://127.0.0.1:9/proxy",
+ NO_PROXY: "127.0.0.1,localhost",
+ },
+ credentialSensitive: { ALOOK_PROXY_TOKEN_FILE: "/tmp/voucher" },
+ }),
+ ...overrides,
+ });
+}
+
+describe("prepareCliTransport", () => {
+ it("prepends the per-launch bin dir to PATH", async () => {
+ const { spawnEnv, stateDir } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
+ expect((spawnEnv.PATH ?? "").split(path.delimiter)[0]).toBe(path.join(stateDir, "bin"));
+ });
+
+ it("injects the host-owned platform, network, and credential layers", async () => {
+ const { spawnEnv, tokenFile } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
+ expect(spawnEnv.ALOOK_ID).toBe("agent_1");
+ expect(spawnEnv.ALOOK_CLI).toBe("alook");
+ expect(spawnEnv.ALOOK_LAUNCH_ID).toBe("launch_1");
+ expect(spawnEnv.ALOOK_PROXY_URL).toBe("http://127.0.0.1:9/proxy");
+ expect(spawnEnv.ALOOK_PROXY_TOKEN_FILE).toBe(tokenFile);
+ });
+
+ it("provider-derived keys remain protected from driver and user environment", async () => {
+ const runtimeConfig: ClaudeConfig = {
+ model: { kind: "default" },
+ provider: { kind: "custom_endpoint", apiUrl: "https://endpoint.test", apiKey: "sk_provider" },
+ mode: "default",
+ environment: { ANTHROPIC_API_KEY: "sk_user" },
+ };
+ const ctx = baseCtx(mkTmp(), { config: { runtimeConfig } });
+ const { spawnEnv } = await prepareCliTransport(ctx, { ANTHROPIC_API_KEY: "sk_driver" }, undefined, "linux");
+ expect(spawnEnv.ANTHROPIC_BASE_URL).toBe("https://endpoint.test");
+ expect(spawnEnv.ANTHROPIC_API_KEY).toBe("sk_provider");
+ });
+
+ it("preserves non-colliding base, user, and driver values", async () => {
+ const runtimeConfig: ClaudeConfig = {
+ model: { kind: "default" },
+ provider: { kind: "default" },
+ mode: "default",
+ environment: { USER_VALUE: "user" },
+ };
+ const { spawnEnv } = await prepareCliTransport(
+ baseCtx(mkTmp(), { config: { runtimeConfig } }),
+ { DRIVER_VALUE: "driver" },
+ undefined,
+ "linux",
+ );
+ expect(spawnEnv).toMatchObject({ KEEP: "base", USER_VALUE: "user", DRIVER_VALUE: "driver" });
+ });
+
+ it("sets the color and loopback defaults from protected layers", async () => {
+ const { spawnEnv } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
+ expect(spawnEnv.NO_COLOR).toBe("1");
+ expect(spawnEnv.FORCE_COLOR).toBe("0");
+ expect(spawnEnv.NO_PROXY).toContain("127.0.0.1");
+ expect(spawnEnv.NO_PROXY).toContain("localhost");
+ });
+
+ it("keeps host identity protected from a driver override", async () => {
+ const ctx = baseCtx(mkTmp(), {
+ prepared: fakePrepared({ identityProtected: { GIT_AUTHOR_NAME: "Melisa" } }),
+ });
+ const { spawnEnv } = await prepareCliTransport(ctx, { GIT_AUTHOR_NAME: "Someone Else" }, undefined, "linux");
+ expect(spawnEnv.GIT_AUTHOR_NAME).toBe("Melisa");
+ });
+
+ it("creates a symlink when hostCliPath is set", async () => {
+ const wd = mkTmp();
+ const host = path.join(wd, "real.js");
+ fs.writeFileSync(host, "#!/usr/bin/env node\n", { mode: 0o755 });
+ const cli: CliTransportConfig = { cliName: "alook", envPrefix: "ALOOK", stateDirName: ".alook", hostCliPath: host };
+ const { stateDir } = await prepareCliTransport(baseCtx(wd), {}, cli, "linux");
+ expect(fs.lstatSync(path.join(stateDir, "bin", "alook")).isSymbolicLink()).toBe(true);
+ });
+
+ it("defaults hostCliPath from the prepared execution resource", async () => {
+ const wd = mkTmp();
+ const host = path.join(wd, "agent-cli.js");
+ fs.writeFileSync(host, "#!/usr/bin/env node\n", { mode: 0o755 });
+ const ctx = baseCtx(wd, { prepared: { ...fakePrepared(), executablePath: host } });
+ const { stateDir } = await prepareCliTransport(ctx, {}, undefined, "linux");
+ expect(fs.realpathSync(path.join(stateDir, "bin", "alook"))).toBe(fs.realpathSync(host));
+ });
+
+ it("does not write AGENTS.md for empty instructions", async () => {
+ const wd = mkTmp();
+ await prepareCliTransport(baseCtx(wd), {}, undefined, "linux");
+ expect(fs.existsSync(path.join(wd, "AGENTS.md"))).toBe(false);
+ });
+});
diff --git a/src/daemon/agent-driver/src/internal/cliTransport.ts b/src/daemon/agent-driver/src/internal/cliTransport.ts
new file mode 100644
index 000000000..403e5b170
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/cliTransport.ts
@@ -0,0 +1,151 @@
+/**
+ * Shared CLI transport — the common launch scaffolding for every CLI-style
+ * runtime (Claude, Codex, Cursor, OpenCode).
+ *
+ * The runtime child process talks back to its host platform through a small
+ * **Alook CLI**, reached purely via the exec environment (PATH + env vars). The
+ * agent always invokes a stable `cliName`; a per-launch link in a PATH-prepended
+ * bin dir points it at the host's real `hostCliPath` (POSIX symlink / Windows
+ * `.cmd` shim — see `cliLink.ts`), so the host binary can be renamed/relocated
+ * without touching the agent-facing surface, and no forwarding script is written
+ * on POSIX.
+ *
+ * This module is deliberately host-agnostic: it ships an Alook-branded, swappable
+ * CLI config (`alook` name + `ALOOK_*` env contract, no real `hostCliPath`). A
+ * real deployment passes its own `CliTransportConfig` — the backend never
+ * hardcodes any particular platform.
+ *
+ * `prepareCliTransport` builds the spawn environment from explicit layers (see
+ * `spawnEnv.ts`) so override precedence is data, not spread order; the child can:
+ * - invoke the stable `cliName` (link → host `hostCliPath`) via PATH,
+ * - authenticate back to the host, and
+ * - see the neutral `<PREFIX>_*` runtime-context env vars.
+ *
+ * AUTH IS ZERO-TRUST ONLY. The host prepares the credential-sensitive
+ * environment layer before the adapter runs; this transport only merges that
+ * opaque layer at the highest precedence. The real key never enters the
+ * child's environment and the package has no credential-broker dependency.
+ */
+import * as fs from "fs";
+import * as path from "path";
+import type { AdapterLaunchContext } from "./adapter.js";
+import { resolveLaunchFieldsOrDefault } from "./config.js";
+import { writeCliLink } from "./cliLink.js";
+import { mergeEnvLayers, type EnvLayer } from "./spawnEnv.js";
+
+interface PreparedCliTransport {
+ /** Per-launch state directory created under the working directory. */
+ stateDir: string;
+ /**
+ * Path to the credential file the child reads — the per-launch `vch_` voucher
+ * (never the real key). The child sends it to the proxy, which swaps in the key.
+ */
+ tokenFile: string;
+ spawnEnv: NodeJS.ProcessEnv;
+}
+
+/**
+ * Host-supplied knobs for the CLI transport.
+ *
+ * The transport places a per-launch link named `cliName` in a `bin` dir and
+ * prepends that dir to PATH. The agent always invokes the same stable name
+ * (`cliName`, default `alook`); on POSIX the link is a symlink to `hostCliPath`,
+ * on Windows a `.cmd` shim. This **decouples the agent-facing CLI name from the
+ * host's real binary name** — the backend's prompts/contract never depend on what
+ * the host actually calls its CLI, and the host can rename or relocate its binary
+ * without touching the agent surface.
+ */
+export interface CliTransportConfig {
+ /** Stable command name the agent invokes (the link's filename). */
+ cliName: string;
+ /** Prefix for injected env vars, e.g. "ALOOK" → ALOOK_ID, ALOOK_PROXY_TOKEN_FILE. */
+ envPrefix: string;
+ /** Name of the per-launch state directory under the working directory. */
+ stateDirName: string;
+ /**
+ * Absolute path to the host's real agent CLI entrypoint the link points at.
+ * Decoupled from `cliName`. On POSIX it MUST be a self-executable entrypoint
+ * (shebang + executable bit — an npm `bin` symlink satisfies this); a host that
+ * needs an interpreter prefix (`node script.js`) must ship its own self-exec
+ * wrapper and pass that here. When omitted (the mock), no link is created and
+ * `cliName` won't resolve.
+ */
+ hostCliPath?: string;
+ /** Extra static env vars the host wants every runtime to see. */
+ extraEnv?: Record<string, string>;
+}
+
+/**
+ * The default Alook CLI config template. No `hostCliPath` is wired — a real
+ * deployment overrides it with `{ ...DEFAULT_CLI_CONFIG, hostCliPath }`.
+ */
+const DEFAULT_CLI_CONFIG: CliTransportConfig = {
+ cliName: "alook",
+ envPrefix: "ALOOK",
+ stateDirName: ".alook",
+};
+
+/**
+ * Prepare the launch transport for a runtime child process.
+ *
+ * Creates a per-launch state dir + token file + a `bin/<cliName>` link (POSIX
+ * symlink / Windows `.cmd` shim) prepended to PATH, so the agent always invokes
+ * the stable `cliName` while the host's real `hostCliPath` stays decoupled behind
+ * it. `spawnEnv` is assembled from explicit, precedence-ordered layers (see
+ * `spawnEnv.ts`): base → host static → user env → driver → platform contract →
+ * runtime context → network → provider-protected → credential (sensitive).
+ *
+ * @param ctx launch context (agent id, working dir, config, …)
+ * @param extraEnv runtime-specific extra env (e.g. `{ NO_COLOR: "1" }`)
+ * @param cli CLI transport config (defaults to the Alook mock config)
+ * @param platform override for testing; defaults to process.platform
+ */
+export async function prepareCliTransport(
+ ctx: AdapterLaunchContext,
+ extraEnv: NodeJS.ProcessEnv = {},
+ cli: CliTransportConfig = DEFAULT_CLI_CONFIG,
+ platform: NodeJS.Platform = process.platform,
+): Promise<PreparedCliTransport> {
+ const stateDir = path.join(ctx.workingDirectory, cli.stateDirName);
+ await fs.promises.mkdir(stateDir, { recursive: true });
+ const hostCliPath = cli.hostCliPath ?? ctx.prepared.executablePath;
+ const binDir = writeCliLink(stateDir, cli.cliName, hostCliPath, platform);
+ const resolved = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
+ const resource = ctx.prepared.environmentLayers;
+ const pathValue = [
+ binDir,
+ resource.networkProtected.PATH,
+ resource.base.PATH,
+ ].filter(Boolean).join(path.delimiter);
+ const layers: EnvLayer[] = [
+ {
+ name: "hostStatic",
+ precedence: 10,
+ vars: { ...resource.hostStatic, ...(cli.extraEnv ?? {}) },
+ },
+ { name: "userEnv", precedence: 20, vars: resolved.envVars },
+ { name: "driver", precedence: 30, vars: extraEnv as Record<string, string | undefined> },
+ { name: "identityProtected", precedence: 35, vars: resource.identityProtected },
+ {
+ name: "platformProtected",
+ precedence: 40,
+ vars: { ...resource.platformProtected, FORCE_COLOR: "0", NO_COLOR: "1" },
+ },
+ { name: "runtimeProtected", precedence: 50, vars: resource.runtimeProtected },
+ {
+ name: "networkProtected",
+ precedence: 60,
+ vars: { ...resource.networkProtected, PATH: pathValue },
+ },
+ { name: "providerProtected", precedence: 70, vars: resolved.providerEnv },
+ {
+ name: "credentialSensitive",
+ precedence: 100,
+ sensitive: true,
+ vars: resource.credentialSensitive,
+ },
+ ];
+ const { env: spawnEnv } = mergeEnvLayers(resource.base, layers);
+ const tokenFile = String(resource.credentialSensitive.ALOOK_PROXY_TOKEN_FILE ?? "");
+ return { stateDir, tokenFile, spawnEnv };
+}
diff --git a/src/daemon/agent-driver/src/internal/config.test.ts b/src/daemon/agent-driver/src/internal/config.test.ts
new file mode 100644
index 000000000..c170cc10d
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/config.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+import { resolveLaunchFieldsOrDefault } from "./config.js";
+
+describe("resolveLaunchFieldsOrDefault", () => {
+ it("resolves Claude custom model/provider fields and strips controlled user env", () => {
+ const fields = resolveLaunchFieldsOrDefault({
+ model: { kind: "custom", name: "custom-model" },
+ provider: { kind: "custom_endpoint", apiUrl: "https://example.invalid", apiKey: "secret" },
+ mode: "fast",
+ environment: { SAFE: "yes", ANTHROPIC_API_KEY: "ignored" },
+ });
+ expect(fields).toMatchObject({
+ model: "custom-model",
+ fastMode: true,
+ envVars: { SAFE: "yes" },
+ providerEnv: {
+ ANTHROPIC_CUSTOM_MODEL_OPTION: "custom-model",
+ ANTHROPIC_BASE_URL: "https://example.invalid",
+ ANTHROPIC_API_KEY: "secret",
+ },
+ });
+ });
+
+ it("maps known Pi providers and ignores unknown provider ids", () => {
+ expect(resolveLaunchFieldsOrDefault({
+ model: { kind: "default" },
+ provider: { kind: "builtin", providerId: "google", apiKey: "pi-key" },
+ }).providerEnv).toEqual({ GEMINI_API_KEY: "pi-key" });
+ expect(resolveLaunchFieldsOrDefault({
+ model: { kind: "default" },
+ provider: { kind: "builtin", providerId: "unknown", apiKey: "pi-key" },
+ }).providerEnv).toEqual({});
+ });
+
+ it("keeps non-Claude custom models free of Claude provider environment", () => {
+ expect(resolveLaunchFieldsOrDefault({
+ model: { kind: "custom", name: "custom-codex-model" },
+ mode: "default",
+ })).toMatchObject({
+ model: "custom-codex-model",
+ providerEnv: {},
+ });
+ });
+
+ it("unwraps a complete adapter launch config", () => {
+ expect(resolveLaunchFieldsOrDefault({
+ sessionId: "session-1",
+ runtimeConfig: { model: { kind: "custom", name: "wrapped-model" } },
+ })).toMatchObject({ model: "wrapped-model", fastMode: false });
+ });
+});
diff --git a/src/daemon/agent-driver/src/internal/config.ts b/src/daemon/agent-driver/src/internal/config.ts
new file mode 100644
index 000000000..fb074a78d
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/config.ts
@@ -0,0 +1,72 @@
+import type {
+ BackendConfig,
+ AdapterLaunchConfig,
+} from "./adapter.js";
+import type {
+ ClaudeProvider,
+ PiProvider,
+ ReasoningEffort,
+} from "../contract.js";
+
+interface ResolvedLaunchFields {
+ model?: string;
+ reasoningEffort?: "low" | "medium" | "high";
+ fastMode: boolean;
+ command?: string;
+ disallowedTools?: string;
+ envVars: Record<string, string>;
+ providerEnv: Record<string, string>;
+}
+
+const providerKeys: Record<string, string> = {
+ google: "GEMINI_API_KEY",
+ openai: "OPENAI_API_KEY",
+ openrouter: "OPENROUTER_API_KEY",
+};
+
+const controlled = new Set([
+ "ANTHROPIC_BASE_URL",
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_CUSTOM_MODEL_OPTION",
+ ...Object.values(providerKeys),
+]);
+
+export function resolveLaunchFieldsOrDefault(
+ input: AdapterLaunchConfig | BackendConfig | undefined,
+): ResolvedLaunchFields {
+ const config: BackendConfig | undefined = input && "runtimeConfig" in input
+ ? input.runtimeConfig
+ : input as BackendConfig | undefined;
+ if (!config) return { fastMode: false, envVars: {}, providerEnv: {} };
+ const normalized = config as BackendConfig & {
+ provider?: ClaudeProvider | PiProvider;
+ reasoningEffort?: ReasoningEffort;
+ disallowedTools?: string;
+ };
+ const envVars = Object.fromEntries(
+ Object.entries(normalized.environment ?? {}).filter(([key]) => !controlled.has(key)),
+ );
+ const providerEnv: Record<string, string> = {};
+ const model = normalized.model.kind === "default" ? undefined : normalized.model.name;
+ if (normalized.model.kind === "custom" && normalized.provider?.kind === "custom_endpoint") {
+ providerEnv.ANTHROPIC_CUSTOM_MODEL_OPTION = normalized.model.name;
+ }
+ if (normalized.provider?.kind === "custom_endpoint") {
+ providerEnv.ANTHROPIC_BASE_URL = normalized.provider.apiUrl;
+ providerEnv.ANTHROPIC_API_KEY = normalized.provider.apiKey;
+ } else if (normalized.provider?.kind === "builtin") {
+ const key = providerKeys[normalized.provider.providerId];
+ if (key) providerEnv[key] = normalized.provider.apiKey;
+ }
+ return {
+ model,
+ reasoningEffort: normalized.reasoningEffort,
+ fastMode: "mode" in normalized && normalized.mode === "fast",
+ command: "command" in normalized && typeof normalized.command === "string"
+ ? normalized.command
+ : undefined,
+ disallowedTools: normalized.disallowedTools,
+ envVars,
+ providerEnv,
+ };
+}
diff --git a/src/daemon/agent-driver/src/internal/errors.test.ts b/src/daemon/agent-driver/src/internal/errors.test.ts
new file mode 100644
index 000000000..751f50db1
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/errors.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "vitest";
+import { scrubDriverError, scrubDriverErrorMessage, stableErrorCode } from "./errors.js";
+
+describe("public driver error scrubbing", () => {
+ it("removes credentials, email, query values, and filesystem paths", () => {
+ const message = scrubDriverErrorMessage(
+ "Bearer abc.def sk-proj-secret [email protected] https://api.invalid/x?token=secret at /Users/alice/private/file.json",
+ );
+ expect(message).not.toContain("abc.def");
+ expect(message).not.toContain("sk-proj-secret");
+ expect(message).not.toContain("[email protected]");
+ expect(message).not.toContain("token=secret");
+ expect(message).not.toContain("/Users/alice");
+ });
+
+ it("preserves the typed error classification while scrubbing its message", () => {
+ expect(scrubDriverError({
+ category: "internal",
+ code: "prepare_failed",
+ message: "failed under /Users/alice/private",
+ retryable: false,
+ })).toEqual({
+ category: "internal",
+ code: "prepare_failed",
+ message: "failed under [redacted-path]",
+ retryable: false,
+ });
+ });
+
+ it("scrubs assignment, JSON, Basic auth, whitespace paths, and nested details", () => {
+ const message = scrubDriverErrorMessage(
+ 'apiKey=supersecret {"apiKey":"jsonsecret"} Authorization: Basic abc123 at /Users/Alice Smith/private key.json',
+ );
+ for (const secret of ["supersecret", "jsonsecret", "abc123", "Alice Smith", "private key.json"]) {
+ expect(message).not.toContain(secret);
+ }
+
+ const scrubbed = scrubDriverError({
+ category: "sdk",
+ code: "vendor said /Users/Alice/private",
+ message: "failed",
+ retryable: false,
+ details: {
+ apiKey: "detail-secret",
+ nested: { authorization: "Basic nested-secret", path: "/Users/Alice Smith/private key.json", attempts: 2, absent: null },
+ },
+ });
+ expect(scrubbed.code).toBe("runtime_error");
+ expect(JSON.stringify(scrubbed.details)).not.toMatch(/detail-secret|nested-secret|Alice Smith|private key/);
+ expect(scrubbed.details).toMatchObject({ nested: { attempts: 2, absent: null } });
+ });
+
+ it("scrubs provider-prefixed and compound credential assignment names", () => {
+ const message = scrubDriverErrorMessage(
+ "OPENAI_API_KEY=supersecret ANTHROPIC_API_KEY=othersecret AWS_SECRET_ACCESS_KEY=awssecret client_secret=clientsecret",
+ );
+ expect(message).not.toMatch(/supersecret|othersecret|awssecret|clientsecret/);
+ });
+
+ it("rejects vendor text as a public machine-readable code", () => {
+ expect(stableErrorCode("ENOENT", "probe_failed")).toBe("ENOENT");
+ expect(stableErrorCode("failed at /Users/alice secret", "probe_failed")).toBe("probe_failed");
+ });
+});
diff --git a/src/daemon/agent-driver/src/internal/errors.ts b/src/daemon/agent-driver/src/internal/errors.ts
new file mode 100644
index 000000000..a897f62fc
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/errors.ts
@@ -0,0 +1,63 @@
+import type { AgentDriverError, JsonObject, JsonValue } from "../contract.js";
+
+const MAX_PUBLIC_ERROR_MESSAGE = 1_000;
+const CREDENTIAL_NAME = String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,4}(?:api[_-]?key|access[_-]?key|secret(?:[_-]?access[_-]?key)?|client[_-]?secret|access[_-]?token|auth(?:orization)?|password|passwd|token|voucher)(?:[_-][A-Za-z0-9]{1,32}){0,4}`;
+const QUOTED_CREDENTIAL_ASSIGNMENT = new RegExp(
+ String.raw`(["'])(${CREDENTIAL_NAME})\1\s*[:=]\s*(["'])[^"'\r\n]*\3`,
+ "gi",
+);
+const CREDENTIAL_ASSIGNMENT = new RegExp(
+ String.raw`(?<![A-Za-z0-9_-])((?:${CREDENTIAL_NAME})\s*[:=]\s*)(?!\[redacted\])[^\s,;}\]]+`,
+ "gi",
+);
+
+export function scrubDriverErrorMessage(value: unknown, fallback = "Runtime operation failed"): string {
+ const text = value instanceof Error ? value.message : String(value ?? "");
+ const scrubbed = text
+ .replace(/\b(?:cmk|cmt|crk)_[A-Za-z0-9_-]+\b/g, "[redacted-token]")
+ .replace(/(Authorization\s*:\s*)(?:Bearer|Basic)\s+[^\s,;]+/gi, "$1[redacted]")
+ .replace(/Bearer\s+[A-Za-z0-9._\-]+/gi, "Bearer [redacted]")
+ .replace(/\b(?:sk|sk-ant|sk-proj|xox[abprs])-[A-Za-z0-9._\-]+/gi, "[redacted-token]")
+ .replace(QUOTED_CREDENTIAL_ASSIGNMENT, '$1$2$1:$3[redacted]$3')
+ .replace(CREDENTIAL_ASSIGNMENT, "$1[redacted]")
+ .replace(/(?<![A-Za-z0-9._%+\-])[A-Za-z0-9._%+\-]{1,320}@[A-Za-z0-9.\-]{1,255}\.[A-Za-z]{2,63}/g, "[redacted-email]")
+ .replace(/([?&])([^=\s]+)=([^&\s]+)/g, "$1$2=[redacted]")
+ .replace(/\/(?:Users|home)\/[^\r\n,;]+/g, "[redacted-path]")
+ .replace(/[A-Za-z]:\\Users\\[^\r\n,;]+/gi, "[redacted-path]")
+ .replace(/\\\\[^\\\s]+\\[^\r\n,;]+/g, "[redacted-path]")
+ .replace(/(?:[A-Za-z]:\\|\/)(?:[^\s/:]+[\\/]){1,}[^\s:]*/g, "[redacted-path]")
+ .trim();
+ return (scrubbed || fallback).slice(0, MAX_PUBLIC_ERROR_MESSAGE);
+}
+
+export function scrubDriverError(error: AgentDriverError): AgentDriverError {
+ return {
+ ...error,
+ code: stableErrorCode(error.code, "runtime_error"),
+ message: scrubDriverErrorMessage(error.message),
+ ...(error.details ? { details: scrubDetails(error.details) } : {}),
+ };
+}
+
+function scrubDetails(details: JsonObject): JsonObject {
+ const scrubValue = (value: JsonValue, key?: string): JsonValue => {
+ if (key && /api[_-]?key|access[_-]?token|auth(?:orization)?|password|passwd|secret|token/i.test(key)) {
+ return "[redacted]";
+ }
+ if (typeof value === "string") return scrubDriverErrorMessage(value, "[redacted]");
+ if (Array.isArray(value)) return value.map((item) => scrubValue(item));
+ if (value && typeof value === "object") {
+ return Object.fromEntries(Object.entries(value).map(([childKey, child]) => [
+ childKey,
+ scrubValue(child as JsonValue, childKey),
+ ]));
+ }
+ return value;
+ };
+ return scrubValue(details) as JsonObject;
+}
+
+export function stableErrorCode(value: unknown, fallback: string): string {
+ const code = String(value ?? "");
+ return /^[A-Za-z0-9_.-]{1,100}$/.test(code) ? code : fallback;
+}
diff --git a/src/daemon/agent-driver/src/internal/killTree.test.ts b/src/daemon/agent-driver/src/internal/killTree.test.ts
new file mode 100644
index 000000000..0add3512c
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/killTree.test.ts
@@ -0,0 +1,480 @@
+import { describe, it, expect, afterEach, vi } from "vitest";
+import { execFileSync, spawn, type ChildProcess } from "child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createInterface } from "node:readline";
+import { spawnAgentProcess, killProcessTree, isAlive } from "./killTree.js";
+
+/**
+ * These tests spawn real child processes rather than mocking
+ * `child_process` — the bug this file guards against (silent no-op kill on
+ * a non-detached child, see plans/fix-daemon-agent-process-kill.md) is a
+ * real OS process-group interaction that a mock would trivially hide.
+ */
+
+const spawned: ChildProcess[] = [];
+const spawnedDescendantPids: number[] = [];
+const tempDirs: string[] = [];
+
+/** A child that just idles until signaled. */
+function spawnIdleChild(opts: { detached?: boolean } = {}): ChildProcess {
+ const proc = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
+ stdio: "ignore",
+ detached: opts.detached,
+ });
+ spawned.push(proc);
+ return proc;
+}
+
+/** A child that installs a no-op SIGTERM handler, so only SIGKILL kills it. */
+function spawnSigtermImmuneChild(opts: { detached?: boolean } = {}): ChildProcess {
+ const proc = spawn(
+ process.execPath,
+ ["-e", "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)"],
+ { stdio: "ignore", detached: opts.detached },
+ );
+ spawned.push(proc);
+ return proc;
+}
+
+afterEach(() => {
+ // Belt-and-suspenders cleanup in case a test fails before its own kill.
+ for (const proc of spawned.splice(0)) {
+ if (proc.pid && isAlive(proc.pid)) {
+ try {
+ process.kill(proc.pid, "SIGKILL");
+ } catch {
+ // already dead
+ }
+ }
+ }
+ for (const pid of spawnedDescendantPids.splice(0)) {
+ if (isAlive(pid)) {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ // already dead
+ }
+ }
+ }
+ for (const dir of tempDirs.splice(0)) {
+ rmSync(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
+ }
+});
+
+describe("killProcessTree", () => {
+ it("kills a detached child via the process-group signal", async () => {
+ const proc = spawnAgentProcess(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
+ cwd: process.cwd(),
+ env: process.env,
+ });
+ spawned.push(proc);
+ await new Promise((r) => proc.once("spawn", r));
+ expect(isAlive(proc.pid!)).toBe(true);
+
+ await killProcessTree(proc.pid!, { graceMs: 1000 });
+
+ expect(isAlive(proc.pid!)).toBe(false);
+ });
+
+ it("still kills a NON-detached child — regression test for the ESRCH-treated-as-dead bug", async () => {
+ // Deliberately spawned WITHOUT detached, reproducing every driver's
+ // pre-fix spawn() call. `process.kill(-pid, sig)` throws ESRCH here
+ // because the child isn't its own process-group leader; killProcessTree
+ // must fall back to signaling the pid directly instead of assuming
+ // ESRCH means "already dead".
+ const proc = spawnIdleChild({ detached: false });
+ await new Promise((r) => proc.once("spawn", r));
+ expect(isAlive(proc.pid!)).toBe(true);
+
+ await killProcessTree(proc.pid!, { graceMs: 1000 });
+
+ expect(isAlive(proc.pid!)).toBe(false);
+ });
+
+ it("resolves immediately for an already-dead pid without throwing", async () => {
+ const proc = spawnIdleChild({ detached: false });
+ await new Promise((r) => proc.once("spawn", r));
+ const pid = proc.pid!;
+ process.kill(pid, "SIGKILL");
+ await new Promise((r) => proc.once("exit", r));
+ expect(isAlive(pid)).toBe(false);
+
+ await expect(killProcessTree(pid, { graceMs: 1000 })).resolves.toBeUndefined();
+ });
+
+ it("no-ops on an invalid pid (0 or negative)", async () => {
+ await expect(killProcessTree(0)).resolves.toBeUndefined();
+ await expect(killProcessTree(-1)).resolves.toBeUndefined();
+ });
+
+ it("retains root process-group authority when the POSIX process-table capture fails", async () => {
+ if (process.platform === "win32") return;
+ const proc = spawnAgentProcess(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
+ cwd: process.cwd(),
+ env: process.env,
+ });
+ spawned.push(proc);
+ await new Promise((resolve) => proc.once("spawn", resolve));
+ const emptyPath = mkdtempSync(join(tmpdir(), "agent-driver-empty-path-"));
+ tempDirs.push(emptyPath);
+ const originalPath = process.env.PATH;
+ process.env.PATH = emptyPath;
+ try {
+ await killProcessTree(proc.pid!, { graceMs: 300 });
+ } finally {
+ if (originalPath === undefined) delete process.env.PATH;
+ else process.env.PATH = originalPath;
+ }
+
+ expect(isAlive(proc.pid!)).toBe(false);
+ });
+
+ it("ignores unsafe numeric rows in a POSIX process-table capture", async () => {
+ if (process.platform === "win32") return;
+ const proc = spawnAgentProcess(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
+ cwd: process.cwd(),
+ env: process.env,
+ });
+ spawned.push(proc);
+ await new Promise((resolve) => proc.once("spawn", resolve));
+ const fakeBin = mkdtempSync(join(tmpdir(), "agent-driver-fake-ps-"));
+ tempDirs.push(fakeBin);
+ writeFileSync(
+ join(fakeBin, "ps"),
+ `#!/bin/sh\nprintf '%s\\n' '${String(proc.pid)} ${String(process.pid)} ${String(proc.pid)}' '9007199254740993 ${String(proc.pid)} ${String(proc.pid)}'\n`,
+ { mode: 0o755 },
+ );
+ const originalPath = process.env.PATH;
+ process.env.PATH = fakeBin;
+ try {
+ await killProcessTree(proc.pid!, { graceMs: 300 });
+ } finally {
+ if (originalPath === undefined) delete process.env.PATH;
+ else process.env.PATH = originalPath;
+ }
+
+ expect(isAlive(proc.pid!)).toBe(false);
+ });
+
+ it("escalates to SIGKILL after graceMs when the child ignores SIGTERM", async () => {
+ const proc = spawnSigtermImmuneChild({ detached: false });
+ await new Promise((r) => proc.once("spawn", r));
+ expect(isAlive(proc.pid!)).toBe(true);
+
+ await killProcessTree(proc.pid!, { graceMs: 300 });
+
+ expect(isAlive(proc.pid!)).toBe(false);
+ });
+
+ it("kills runtime descendants before releasing a shell-owning workspace", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "agent-driver-tree-"));
+ tempDirs.push(cwd);
+ const childModule = join(cwd, "child.mjs");
+ const parentModule = join(cwd, "parent.mjs");
+ // The root exits on SIGTERM while this descendant deliberately survives it.
+ // killProcessTree must keep the detached process group as its authority and
+ // escalate before reporting that the tree has stopped.
+ writeFileSync(
+ childModule,
+ "process.on('SIGTERM', () => {}); process.stdout.write('ready\\n'); setInterval(() => {}, 1000);\n",
+ );
+ writeFileSync(parentModule, `
+ import { spawn } from "node:child_process";
+ const child = spawn(process.execPath, [${JSON.stringify(childModule)}], {
+ cwd: process.cwd(),
+ stdio: ["ignore", "pipe", "ignore"],
+ });
+ child.stdout.once("data", () => process.stdout.write(String(child.pid) + "\\n"));
+ setInterval(() => {}, 1000);
+ `);
+ const command = process.platform === "win32" ? join(cwd, "runtime.cmd") : process.execPath;
+ const args = process.platform === "win32" ? [] : [parentModule];
+ if (process.platform === "win32") {
+ writeFileSync(command, `@node "%~dp0\\parent.mjs"\r\n`);
+ }
+ const proc = spawnAgentProcess(command, args, {
+ cwd,
+ env: process.env,
+ // Exercise the `.cmd` launch shape on Windows: the tracked pid is the
+ // command shell, while the runtime and its descendants own the cwd.
+ shell: process.platform === "win32",
+ });
+ spawned.push(proc);
+ await new Promise((resolve) => proc.once("spawn", resolve));
+ const lines = createInterface({ input: proc.stdout! });
+ const childPid = await new Promise<number>((resolve, reject) => {
+ lines.once("line", (line) => resolve(Number(line)));
+ proc.once("exit", () => reject(new Error("parent exited before reporting its child pid")));
+ });
+ lines.close();
+ spawnedDescendantPids.push(childPid);
+ expect(Number.isInteger(childPid)).toBe(true);
+ expect(isAlive(proc.pid!)).toBe(true);
+ expect(isAlive(childPid)).toBe(true);
+
+ await killProcessTree(proc.pid!, { graceMs: 300 });
+
+ expect(isAlive(proc.pid!)).toBe(false);
+ expect(isAlive(childPid)).toBe(false);
+ rmSync(cwd, { recursive: true, force: true });
+ tempDirs.splice(tempDirs.indexOf(cwd), 1);
+ });
+
+ it("kills a Cursor-like MCP subtree that detached into its own process group", async () => {
+ if (process.platform === "win32") return;
+ const cwd = mkdtempSync(join(tmpdir(), "agent-driver-cursor-mcp-tree-"));
+ tempDirs.push(cwd);
+ const leafModule = join(cwd, "context7.mjs");
+ const mcpModule = join(cwd, "mcp.mjs");
+ const cursorModule = join(cwd, "cursor.mjs");
+ writeFileSync(
+ leafModule,
+ "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000);\n",
+ );
+ writeFileSync(mcpModule, `
+ import { spawn } from "node:child_process";
+ const child = spawn(process.execPath, [${JSON.stringify(leafModule)}], {
+ cwd: process.cwd(),
+ stdio: "ignore",
+ });
+ child.once("spawn", () => process.stdout.write(String(process.pid) + " " + String(child.pid) + "\\n"));
+ process.on("SIGTERM", () => {});
+ setInterval(() => {}, 1000);
+ `);
+ writeFileSync(cursorModule, `
+ import { spawn } from "node:child_process";
+ const mcp = spawn(process.execPath, [${JSON.stringify(mcpModule)}], {
+ cwd: process.cwd(),
+ detached: true,
+ stdio: ["ignore", "pipe", "ignore"],
+ });
+ mcp.stdout.once("data", (chunk) => process.stdout.write(String(chunk)));
+ process.on("SIGTERM", () => {});
+ setInterval(() => {}, 1000);
+ `);
+
+ const cursor = spawnAgentProcess(process.execPath, [cursorModule], {
+ cwd,
+ env: process.env,
+ });
+ spawned.push(cursor);
+ await new Promise((resolve) => cursor.once("spawn", resolve));
+ const lines = createInterface({ input: cursor.stdout! });
+ const [mcpPid, context7Pid] = await new Promise<[number, number]>((resolve, reject) => {
+ lines.once("line", (line) => {
+ const [mcp, context7] = line.split(" ").map(Number);
+ resolve([mcp, context7]);
+ });
+ cursor.once("exit", () => reject(new Error("Cursor fixture exited before reporting its MCP subtree")));
+ });
+ lines.close();
+ spawnedDescendantPids.push(mcpPid, context7Pid);
+ const mcpPgid = Number(execFileSync(
+ "ps",
+ ["-o", "pgid=", "-p", String(mcpPid)],
+ { encoding: "utf8" },
+ ).trim());
+ expect(mcpPgid).toBe(mcpPid);
+ expect(mcpPgid).not.toBe(cursor.pid);
+ expect(isAlive(cursor.pid!)).toBe(true);
+ expect(isAlive(mcpPid)).toBe(true);
+ expect(isAlive(context7Pid)).toBe(true);
+
+ await killProcessTree(cursor.pid!, { graceMs: 300 });
+
+ expect(isAlive(cursor.pid!)).toBe(false);
+ expect(isAlive(mcpPid)).toBe(false);
+ expect(isAlive(context7Pid)).toBe(false);
+ });
+
+ it("keeps Windows tree authority when the CLI root exits before its descendant", async () => {
+ if (process.platform !== "win32") return;
+ const cwd = mkdtempSync(join(tmpdir(), "agent-driver-terminal-root-"));
+ tempDirs.push(cwd);
+ const childModule = join(cwd, "child.mjs");
+ const rootModule = join(cwd, "root.mjs");
+ const command = join(cwd, "runtime.cmd");
+ writeFileSync(childModule, "setInterval(() => {}, 1000);\n");
+ writeFileSync(rootModule, `
+ import { spawn } from "node:child_process";
+ const child = spawn(process.execPath, [${JSON.stringify(childModule)}], {
+ cwd: process.cwd(),
+ stdio: "ignore",
+ });
+ child.once("spawn", () => {
+ process.stdout.write(String(process.pid) + " " + String(child.pid) + "\\n");
+ setTimeout(() => process.exit(0), 250);
+ });
+ `);
+ writeFileSync(command, `@node "%~dp0\\root.mjs"\r\n`);
+
+ const proc = spawnAgentProcess(command, [], {
+ cwd,
+ env: process.env,
+ shell: true,
+ });
+ spawned.push(proc);
+ await new Promise((resolve) => proc.once("spawn", resolve));
+ const lines = createInterface({ input: proc.stdout! });
+ const [rootPid, childPid] = await new Promise<[number, number]>((resolve, reject) => {
+ lines.once("line", (line) => {
+ const [root, child] = line.split(" ").map(Number);
+ resolve([root, child]);
+ });
+ proc.once("exit", () => reject(new Error("supervisor exited before the fixture reported its pids")));
+ });
+ lines.close();
+ spawnedDescendantPids.push(rootPid, childPid);
+ expect(isAlive(rootPid)).toBe(true);
+ expect(isAlive(childPid)).toBe(true);
+
+ await new Promise((resolve) => proc.once("exit", resolve));
+
+ // The tracked supervisor exit is the host-release boundary. Descendants
+ // and cwd ownership must already be gone here; waiting after exit would
+ // hide the exact release race this fixture protects against.
+ expect(isAlive(rootPid)).toBe(false);
+ expect(isAlive(childPid)).toBe(false);
+ rmSync(cwd, { recursive: true, force: true });
+ tempDirs.splice(tempDirs.indexOf(cwd), 1);
+ await expect(killProcessTree(proc.pid!, { graceMs: 0 })).resolves.toBeUndefined();
+ });
+
+ it("rejects when forced POSIX termination cannot make the target exit", async () => {
+ if (process.platform === "win32") return;
+ vi.useFakeTimers();
+ const kill = vi.spyOn(process, "kill").mockImplementation(() => true);
+ try {
+ const stopped = killProcessTree(999_999, { graceMs: 0 });
+ const rejection = expect(stopped).rejects.toThrow("remained alive after SIGKILL");
+ await vi.advanceTimersByTimeAsync(2_100);
+ await rejection;
+ } finally {
+ kill.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("spawnAgentProcess", () => {
+ it("spawns detached on POSIX so killProcessTree's group signal has a group to hit", async () => {
+ if (process.platform === "win32") return;
+ const proc = spawnAgentProcess(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
+ cwd: process.cwd(),
+ env: process.env,
+ });
+ spawned.push(proc);
+ await new Promise((r) => proc.once("spawn", r));
+
+ // A detached child is its own process-group leader: pgid === pid.
+ const out = execFileSync("ps", ["-o", "pgid=", "-p", String(proc.pid)], { encoding: "utf8" }).trim();
+ expect(Number(out)).toBe(proc.pid);
+
+ process.kill(proc.pid!, "SIGKILL");
+ });
+
+ it("pipes stdio and forwards cwd/env/shell", () => {
+ const proc = spawnAgentProcess(process.execPath, ["-e", "process.exit(0)"], {
+ cwd: process.cwd(),
+ env: { ...process.env, FOO: "bar" },
+ shell: false,
+ });
+ spawned.push(proc);
+ expect(proc.stdin).not.toBeNull();
+ expect(proc.stdout).not.toBeNull();
+ expect(proc.stderr).not.toBeNull();
+ });
+
+ it("supports a runtime that explicitly ignores stdin", async () => {
+ const proc = spawnAgentProcess(process.execPath, ["-e", "process.exit(0)"], {
+ cwd: process.cwd(),
+ env: process.env,
+ stdin: "ignore",
+ });
+ spawned.push(proc);
+ expect(proc.stdin).toBeNull();
+ await new Promise((resolve, reject) => {
+ proc.once("error", reject);
+ proc.once("exit", resolve);
+ });
+ });
+
+ it("preserves persistent Windows stdin/stdout, cwd/env, and the exact inner exit code", async () => {
+ if (process.platform !== "win32") return;
+ const base = mkdtempSync(join(tmpdir(), "agent-driver-job-stdio-"));
+ tempDirs.push(base);
+ const cwd = join(base, "daemon", "agent-fresh");
+ mkdirSync(cwd, { recursive: true });
+ const runtimeModule = join(base, "runtime.mjs");
+ const command = join(base, "runtime.cmd");
+ writeFileSync(runtimeModule, `
+ import { createInterface } from "node:readline";
+ const lines = createInterface({ input: process.stdin });
+ let request = 0;
+ lines.on("line", (line) => {
+ request += 1;
+ const result = { line, request, cwd: process.cwd(), env: process.env.ALOOK_JOB_FIXTURE };
+ process.stdout.write(JSON.stringify(result) + "\\n", () => {
+ if (request === 2) process.exit(37);
+ });
+ });
+ `);
+ writeFileSync(command, `@node "%~dp0\\runtime.mjs"\r\n`);
+ const proc = spawnAgentProcess(command, ["app-server", "--listen", "stdio://"], {
+ cwd,
+ env: { ...process.env, ALOOK_JOB_FIXTURE: "job-env-ok" },
+ shell: true,
+ });
+ spawned.push(proc);
+ const exited = new Promise<[number | null, NodeJS.Signals | null]>((resolve, reject) => {
+ proc.once("error", reject);
+ proc.once("exit", (code, signal) => resolve([code, signal]));
+ });
+ const lines = createInterface({ input: proc.stdout! });
+ const readResponse = () => new Promise<string>((resolve, reject) => {
+ const onExit = () => {
+ lines.off("line", onLine);
+ reject(new Error("supervisor exited before the stdin roundtrip completed"));
+ };
+ const onLine = (line: string) => {
+ proc.off("exit", onExit);
+ resolve(line);
+ };
+ lines.once("line", onLine);
+ proc.once("exit", onExit);
+ });
+
+ // Keep stdin open across multiple request/response exchanges. Calling
+ // `end()` here would only prove that EOF flushes a buffered pipe, while
+ // Codex/Claude/ACP all require a long-lived bidirectional transport.
+ const firstResponse = readResponse();
+ proc.stdin!.write("stdio-roundtrip-1\n");
+ const first = await firstResponse;
+ const exitStartedAt = Date.now();
+ const secondResponse = readResponse();
+ proc.stdin!.write("stdio-roundtrip-2\n");
+ const second = await secondResponse;
+
+ expect([first, second].map((line) => JSON.parse(line))).toEqual([
+ {
+ line: "stdio-roundtrip-1",
+ request: 1,
+ cwd,
+ env: "job-env-ok",
+ },
+ {
+ line: "stdio-roundtrip-2",
+ request: 2,
+ cwd,
+ env: "job-env-ok",
+ },
+ ]);
+ lines.close();
+ await expect(exited).resolves.toEqual([37, null]);
+ // Releasing the supervisor's own child handle must happen before job
+ // accounting drain; otherwise even this naturally exited tree waits 5s.
+ expect(Date.now() - exitStartedAt).toBeLessThan(4_000);
+ });
+});
diff --git a/src/daemon/agent-driver/src/internal/killTree.ts b/src/daemon/agent-driver/src/internal/killTree.ts
new file mode 100644
index 000000000..128701c21
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/killTree.ts
@@ -0,0 +1,664 @@
+/**
+ * Agent process spawn + process-tree termination with SIGKILL escalation.
+ *
+ * These two live together on purpose: they're opposite ends of the SAME
+ * contract. `spawnAgentProcess` is the ONLY way a driver may start an agent
+ * CLI — it always spawns `detached` on POSIX, making the child the leader of
+ * its own process group (pgid = pid). `killProcessTree` snapshots that exact
+ * root's descendants before signaling, then retains authority over the root
+ * group plus any captured subprocess groups that detached from it. This keeps
+ * independently-grouped MCP servers / tools from becoming orphans.
+ *
+ * BackendAdapter files must NOT call `child_process.spawn` directly for the agent CLI
+ * — always go through `spawnAgentProcess` here, so the detached contract
+ * can't be silently skipped by a new (or edited) driver.
+ *
+ * On POSIX, SIGTERM is a request and we escalate the process group to SIGKILL
+ * after a grace window. On Windows, a kill-on-close Job Object holds the whole
+ * tree even after a `.cmd`/runtime root exits; explicit stop uses `taskkill`
+ * against that supervisor and the kernel job closes over any remaining child.
+ */
+import { execFileSync, spawn, type ChildProcess } from "child_process";
+import { randomUUID } from "node:crypto";
+import { createServer, type Socket } from "node:net";
+import { PassThrough } from "node:stream";
+
+const POLL_MS = 100;
+const FORCE_EXIT_WAIT_MS = 2_000;
+const TASKKILL_WAIT_MS = 2_000;
+const POSIX_TREE_CAPTURE_TIMEOUT_MS = 1_000;
+const POSIX_TREE_CAPTURE_MAX_BUFFER = 1_048_576;
+
+/**
+ * Standard grace before SIGKILL when the manager stops a running session.
+ * Every session-level stop path (logical stop, forced stop,
+ * the process-lane stop fallback) shares this so the "how long
+ * before we kill it hard" answer is one number, not three drifting ones.
+ *
+ * MUST stay strictly below `daemonStart.ts`'s `STOP_GRACE_MS` (the window
+ * `alook daemon stop` gives the DAEMON before SIGKILLing it). The daemon's
+ * SIGTERM handler awaits `manager.stopAll()`, which awaits these per-session
+ * kills — so if the two windows were equal, an agent CLI that ignores SIGTERM
+ * would still be inside its own grace when the outer SIGKILL lands, killing
+ * the daemon before it ever escalates to SIGKILL on the child. The child is
+ * detached (its own process group), so it would survive as an orphan.
+ */
+export const SESSION_STOP_GRACE_MS = 2000;
+const DEFAULT_GRACE_MS = SESSION_STOP_GRACE_MS;
+const isPosix = process.platform !== "win32";
+const WINDOWS_JOB_NODE_ENV = "ALOOK_WINDOWS_JOB_NODE";
+const WINDOWS_JOB_PAYLOAD_ENV = "ALOOK_WINDOWS_JOB_PAYLOAD";
+const WINDOWS_JOB_RUNNER_ENV = "ALOOK_WINDOWS_JOB_RUNNER";
+const WINDOWS_JOB_STDIN_PIPE_ENV = "ALOOK_WINDOWS_JOB_STDIN_PIPE";
+
+// The tracked Windows child is a PowerShell supervisor that owns a kill-on-close
+// Job Object. It creates the inner Node process suspended, gives it the
+// supervisor's raw output handles, assigns it to the job, and only then
+// resumes it. Every descendant inherits the job, so the kernel retains tree
+// authority after a `.cmd` shell or runtime root exits. Persistent protocol
+// stdin uses a dedicated named pipe: PowerShell must not own that pipe because
+// its host can block while probing stdin before it runs the encoded bootstrap.
+const WINDOWS_JOB_RUNNER = "const{spawn}=require('node:child_process');const{connect}=require('node:net');const p=JSON.parse(Buffer.from(process.env.ALOOK_WINDOWS_JOB_PAYLOAD,'base64').toString('utf8'));const pipe=process.env.ALOOK_WINDOWS_JOB_STDIN_PIPE;delete process.env.ALOOK_WINDOWS_JOB_NODE;delete process.env.ALOOK_WINDOWS_JOB_PAYLOAD;delete process.env.ALOOK_WINDOWS_JOB_RUNNER;delete process.env.ALOOK_WINDOWS_JOB_STDIN_PIPE;const run=stdin=>{const c=spawn(p.command,p.args,{cwd:p.cwd,env:process.env,shell:p.shell,stdio:[stdin,'inherit','inherit'],windowsHide:true});c.once('spawn',()=>{if(stdin!=='ignore')stdin.unref()});c.once('error',e=>{console.error(e);process.exitCode=1});c.once('exit',(code,signal)=>{process.exitCode=signal?1:(code??1)})};if(pipe){const input=connect(pipe);input.once('connect',()=>run(input));input.once('error',e=>{console.error(e);process.exitCode=1})}else run('ignore')";
+
+const WINDOWS_JOB_BOOTSTRAP = String.raw`
+$ErrorActionPreference = "Stop"
+Add-Type -TypeDefinition @"
+using System;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading;
+
+public static class AlookAgentJob {
+ [StructLayout(LayoutKind.Sequential)]
+ private struct BasicLimits {
+ public long PerProcessUserTimeLimit;
+ public long PerJobUserTimeLimit;
+ public uint LimitFlags;
+ public UIntPtr MinimumWorkingSetSize;
+ public UIntPtr MaximumWorkingSetSize;
+ public uint ActiveProcessLimit;
+ public UIntPtr Affinity;
+ public uint PriorityClass;
+ public uint SchedulingClass;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct IoCounters {
+ public ulong ReadOperationCount;
+ public ulong WriteOperationCount;
+ public ulong OtherOperationCount;
+ public ulong ReadTransferCount;
+ public ulong WriteTransferCount;
+ public ulong OtherTransferCount;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ExtendedLimits {
+ public BasicLimits BasicLimitInformation;
+ public IoCounters IoInfo;
+ public UIntPtr ProcessMemoryLimit;
+ public UIntPtr JobMemoryLimit;
+ public UIntPtr PeakProcessMemoryUsed;
+ public UIntPtr PeakJobMemoryUsed;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct BasicAccountingInformation {
+ public long TotalUserTime;
+ public long TotalKernelTime;
+ public long ThisPeriodTotalUserTime;
+ public long ThisPeriodTotalKernelTime;
+ public uint TotalPageFaultCount;
+ public uint TotalProcesses;
+ public uint ActiveProcesses;
+ public uint TotalTerminatedProcesses;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct StartupInfo {
+ public uint Size;
+ public IntPtr Reserved;
+ public IntPtr Desktop;
+ public IntPtr Title;
+ public uint X;
+ public uint Y;
+ public uint XSize;
+ public uint YSize;
+ public uint XCountChars;
+ public uint YCountChars;
+ public uint FillAttribute;
+ public uint Flags;
+ public ushort ShowWindow;
+ public ushort Reserved2Size;
+ public IntPtr Reserved2;
+ public IntPtr StdInput;
+ public IntPtr StdOutput;
+ public IntPtr StdError;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ProcessInformation {
+ public IntPtr Process;
+ public IntPtr Thread;
+ public uint ProcessId;
+ public uint ThreadId;
+ }
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern IntPtr CreateJobObject(IntPtr attributes, string name);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool SetInformationJobObject(
+ IntPtr job,
+ int informationClass,
+ ref ExtendedLimits information,
+ uint informationLength
+ );
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool TerminateJobObject(IntPtr job, uint exitCode);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool QueryInformationJobObject(
+ IntPtr job,
+ int informationClass,
+ ref BasicAccountingInformation information,
+ uint informationLength,
+ IntPtr returnLength
+ );
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern bool CreateProcessW(
+ string applicationName,
+ StringBuilder commandLine,
+ IntPtr processAttributes,
+ IntPtr threadAttributes,
+ bool inheritHandles,
+ uint creationFlags,
+ IntPtr environment,
+ string currentDirectory,
+ ref StartupInfo startupInfo,
+ out ProcessInformation processInformation
+ );
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern IntPtr GetStdHandle(int standardHandle);
+
+ [DllImport("kernel32.dll")]
+ private static extern IntPtr GetCurrentProcess();
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool DuplicateHandle(
+ IntPtr sourceProcess,
+ IntPtr sourceHandle,
+ IntPtr targetProcess,
+ out IntPtr targetHandle,
+ uint desiredAccess,
+ bool inheritHandle,
+ uint options
+ );
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern uint ResumeThread(IntPtr thread);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool TerminateProcess(IntPtr process, uint exitCode);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool CloseHandle(IntPtr handle);
+
+ private static IntPtr CreateKillOnCloseJob() {
+ const uint KillOnJobClose = 0x00002000;
+ const int ExtendedLimitInformation = 9;
+ IntPtr job = CreateJobObject(IntPtr.Zero, null);
+ if (job == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateJobObject failed");
+ var limits = new ExtendedLimits();
+ limits.BasicLimitInformation.LimitFlags = KillOnJobClose;
+ if (!SetInformationJobObject(job, ExtendedLimitInformation, ref limits, (uint)Marshal.SizeOf(limits))) {
+ int error = Marshal.GetLastWin32Error();
+ CloseHandle(job);
+ throw new Win32Exception(error, "SetInformationJobObject failed");
+ }
+ return job;
+ }
+
+ private static string QuoteArgument(string value) {
+ if (value.Length == 0) return "\"\"";
+ if (value.IndexOfAny(new[] { ' ', '\t', '\n', '\v', '"' }) < 0) return value;
+ var quoted = new StringBuilder("\"");
+ int backslashes = 0;
+ foreach (char character in value) {
+ if (character == '\\') {
+ backslashes++;
+ } else if (character == '"') {
+ quoted.Append('\\', backslashes * 2 + 1);
+ quoted.Append('"');
+ backslashes = 0;
+ } else {
+ quoted.Append('\\', backslashes);
+ quoted.Append(character);
+ backslashes = 0;
+ }
+ }
+ quoted.Append('\\', backslashes * 2);
+ quoted.Append('"');
+ return quoted.ToString();
+ }
+
+ private static IntPtr DuplicateStandardHandle(int standardHandle) {
+ const uint DuplicateSameAccess = 0x00000002;
+ IntPtr source = GetStdHandle(standardHandle);
+ if (source == IntPtr.Zero || source == new IntPtr(-1))
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetStdHandle failed");
+ IntPtr current = GetCurrentProcess();
+ IntPtr duplicate;
+ if (!DuplicateHandle(
+ current,
+ source,
+ current,
+ out duplicate,
+ 0,
+ true,
+ DuplicateSameAccess
+ )) throw new Win32Exception(Marshal.GetLastWin32Error(), "DuplicateHandle failed");
+ return duplicate;
+ }
+
+ private static void TerminateAndDrainJob(IntPtr job) {
+ const int BasicAccounting = 1;
+ if (!TerminateJobObject(job, 1))
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "TerminateJobObject failed");
+ DateTime deadline = DateTime.UtcNow.AddSeconds(5);
+ while (true) {
+ var accounting = new BasicAccountingInformation();
+ if (!QueryInformationJobObject(
+ job,
+ BasicAccounting,
+ ref accounting,
+ (uint)Marshal.SizeOf(accounting),
+ IntPtr.Zero
+ )) throw new Win32Exception(Marshal.GetLastWin32Error(), "QueryInformationJobObject failed");
+ if (accounting.ActiveProcesses == 0) return;
+ if (DateTime.UtcNow >= deadline)
+ throw new TimeoutException("Windows process job did not drain within 5000ms");
+ Thread.Sleep(10);
+ }
+ }
+
+ public static int RunNode(string nodePath, string runner) {
+ const uint CreateSuspended = 0x00000004;
+ const uint StartfUseStdHandles = 0x00000100;
+ const uint Infinite = 0xffffffff;
+ const uint WaitFailed = 0xffffffff;
+ IntPtr stdInput = DuplicateStandardHandle(-10);
+ IntPtr stdOutput = IntPtr.Zero;
+ IntPtr stdError = IntPtr.Zero;
+ IntPtr job = IntPtr.Zero;
+ var startup = new StartupInfo();
+ startup.Size = (uint)Marshal.SizeOf(startup);
+ startup.Flags = StartfUseStdHandles;
+ var commandLine = new StringBuilder(
+ QuoteArgument(nodePath) + " -e " + QuoteArgument(runner)
+ );
+ ProcessInformation child;
+ try {
+ stdOutput = DuplicateStandardHandle(-11);
+ stdError = DuplicateStandardHandle(-12);
+ startup.StdInput = stdInput;
+ startup.StdOutput = stdOutput;
+ startup.StdError = stdError;
+ job = CreateKillOnCloseJob();
+ if (!CreateProcessW(
+ nodePath,
+ commandLine,
+ IntPtr.Zero,
+ IntPtr.Zero,
+ true,
+ CreateSuspended,
+ IntPtr.Zero,
+ null,
+ ref startup,
+ out child
+ )) throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateProcessW failed");
+ bool assigned = false;
+ try {
+ if (!AssignProcessToJobObject(job, child.Process))
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "AssignProcessToJobObject failed");
+ assigned = true;
+ if (ResumeThread(child.Thread) == uint.MaxValue)
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "ResumeThread failed");
+ if (WaitForSingleObject(child.Process, Infinite) == WaitFailed)
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "WaitForSingleObject failed");
+ uint exitCode;
+ if (!GetExitCodeProcess(child.Process, out exitCode))
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetExitCodeProcess failed");
+ if (!CloseHandle(child.Thread))
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "CloseHandle child thread failed");
+ child.Thread = IntPtr.Zero;
+ if (!CloseHandle(child.Process))
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "CloseHandle child process failed");
+ child.Process = IntPtr.Zero;
+ TerminateAndDrainJob(job);
+ return unchecked((int)exitCode);
+ } catch {
+ if (!assigned && child.Process != IntPtr.Zero) TerminateProcess(child.Process, 1);
+ throw;
+ } finally {
+ if (child.Thread != IntPtr.Zero) CloseHandle(child.Thread);
+ if (child.Process != IntPtr.Zero) CloseHandle(child.Process);
+ }
+ } finally {
+ if (job != IntPtr.Zero) CloseHandle(job);
+ if (stdError != IntPtr.Zero) CloseHandle(stdError);
+ if (stdOutput != IntPtr.Zero) CloseHandle(stdOutput);
+ CloseHandle(stdInput);
+ }
+ }
+}
+"@
+$exitCode = [AlookAgentJob]::RunNode($env:ALOOK_WINDOWS_JOB_NODE, $env:ALOOK_WINDOWS_JOB_RUNNER)
+exit $exitCode
+`;
+
+const WINDOWS_JOB_ENCODED_COMMAND = Buffer.from(WINDOWS_JOB_BOOTSTRAP, "utf16le").toString("base64");
+
+interface AgentSpawnOptions {
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ /** Run through a shell — needed on Windows for `.cmd`/`.bat` shims. */
+ shell?: boolean;
+ /**
+ * stdin disposition. Default `"pipe"` for persistent stdio transports. A
+ * one-shot adapter that proves it never reads stdin may opt into `"ignore"`.
+ * stdout/stderr stay piped regardless for protocol output and diagnostics.
+ */
+ stdin?: "pipe" | "ignore";
+}
+
+/**
+ * The only sanctioned way to spawn an agent CLI child process. Always pipes
+ * stdio and (on POSIX) spawns `detached` so the child becomes its own
+ * process-group leader — required for `killProcessTree`'s group signal to
+ * actually reach it (and its grandchildren) instead of silently no-oping.
+ * See the module doc comment above for why this must be the single spawn
+ * entry point rather than each driver calling `child_process.spawn` itself.
+ */
+export function spawnAgentProcess(command: string, args: string[], opts: AgentSpawnOptions): ChildProcess {
+ if (!isPosix) {
+ const stdin = opts.stdin ?? "pipe";
+ const stdinProxy = stdin === "pipe" ? new PassThrough() : undefined;
+ const stdinPipe = stdinProxy
+ ? `\\\\.\\pipe\\alook-agent-${process.pid}-${randomUUID()}`
+ : undefined;
+ let stdinSocket: Socket | undefined;
+ const stdinServer = stdinProxy
+ ? createServer((socket) => {
+ stdinSocket = socket;
+ stdinServer?.close();
+ socket.once("close", () => {
+ if (stdinSocket === socket) stdinSocket = undefined;
+ });
+ socket.once("error", () => stdinProxy.destroy());
+ stdinProxy.pipe(socket);
+ })
+ : undefined;
+ stdinProxy?.once("close", () => {
+ if (!stdinProxy.writableFinished) stdinSocket?.destroy();
+ });
+ stdinServer?.once("error", () => stdinProxy?.destroy());
+ if (stdinPipe) stdinServer?.listen(stdinPipe);
+ const env: NodeJS.ProcessEnv = {
+ ...opts.env,
+ [WINDOWS_JOB_NODE_ENV]: process.execPath,
+ [WINDOWS_JOB_PAYLOAD_ENV]: Buffer.from(JSON.stringify({ command, args, cwd: opts.cwd, shell: opts.shell ?? false })).toString("base64"),
+ [WINDOWS_JOB_RUNNER_ENV]: WINDOWS_JOB_RUNNER,
+ ...(stdinPipe ? { [WINDOWS_JOB_STDIN_PIPE_ENV]: stdinPipe } : {}),
+ };
+ let proc: ChildProcess;
+ try {
+ proc = spawn("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", WINDOWS_JOB_ENCODED_COMMAND], {
+ cwd: opts.cwd,
+ // PowerShell receives NUL for stdin so its host cannot consume or
+ // block the persistent protocol pipe before running the bootstrap.
+ stdio: ["ignore", "pipe", "pipe"],
+ env,
+ windowsHide: true,
+ });
+ } catch (error) {
+ stdinServer?.close();
+ stdinProxy?.destroy();
+ throw error;
+ }
+ if (stdinProxy) Object.defineProperty(proc, "stdin", { value: stdinProxy });
+ const closeStdinBridge = () => {
+ if (stdinServer?.listening) stdinServer.close();
+ stdinSocket?.destroy();
+ stdinProxy?.destroy();
+ };
+ proc.once("error", closeStdinBridge);
+ proc.once("exit", closeStdinBridge);
+ return proc;
+ }
+ return spawn(command, args, {
+ cwd: opts.cwd,
+ // stdout/stderr always piped (we read stream-json/JSON-RPC); stdin defaults
+ // to pipe for persistent transports. See AgentSpawnOptions.stdin.
+ stdio: [opts.stdin ?? "pipe", "pipe", "pipe"],
+ env: opts.env,
+ shell: opts.shell ?? false,
+ detached: isPosix,
+ });
+}
+
+export function isAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ return (e as NodeJS.ErrnoException)?.code === "EPERM";
+ }
+}
+
+function isProcessGroupAlive(pid: number): boolean {
+ if (!isPosix) return false;
+ try {
+ process.kill(-pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException)?.code === "EPERM";
+ }
+}
+
+interface PosixTreeTargets {
+ readonly pids: readonly number[];
+ readonly processGroups: readonly number[];
+}
+
+/** Capture one exact-root subtree before any signal can break its PPID links. */
+function capturePosixTreeTargets(rootPid: number, rootOwnsProcessGroup: boolean): PosixTreeTargets {
+ const fallback = (): PosixTreeTargets => ({
+ pids: [rootPid],
+ processGroups: rootOwnsProcessGroup ? [rootPid] : [],
+ });
+ let output: string;
+ try {
+ output = execFileSync("ps", ["-axo", "pid=,ppid=,pgid="], {
+ encoding: "utf8",
+ timeout: POSIX_TREE_CAPTURE_TIMEOUT_MS,
+ maxBuffer: POSIX_TREE_CAPTURE_MAX_BUFFER,
+ });
+ } catch {
+ return fallback();
+ }
+
+ const processGroupsByPid = new Map<number, number>();
+ const children = new Map<number, number[]>();
+ for (const line of output.split("\n")) {
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)$/);
+ if (!match) continue;
+ const pid = Number(match[1]);
+ const ppid = Number(match[2]);
+ const pgid = Number(match[3]);
+ if (!Number.isSafeInteger(pid) || pid < 1 || !Number.isSafeInteger(ppid) || !Number.isSafeInteger(pgid)) {
+ continue;
+ }
+ processGroupsByPid.set(pid, pgid);
+ const siblings = children.get(ppid);
+ if (siblings) siblings.push(pid);
+ else children.set(ppid, [pid]);
+ }
+
+ const pids = new Set<number>([rootPid]);
+ const pending = [rootPid];
+ for (let index = 0; index < pending.length; index += 1) {
+ const parent = pending[index]!;
+ for (const child of children.get(parent) ?? []) {
+ if (pids.has(child)) continue;
+ pids.add(child);
+ pending.push(child);
+ }
+ }
+
+ // Signal a captured PGID only when its group leader is itself in the exact
+ // root subtree. Every captured PID is also signalled directly, preserving
+ // authority without ever broadening termination to an unrelated group.
+ const processGroups = new Set<number>();
+ if (rootOwnsProcessGroup) processGroups.add(rootPid);
+ for (const targetPid of pids) {
+ const pgid = processGroupsByPid.get(targetPid);
+ if (pgid && pids.has(pgid)) processGroups.add(pgid);
+ }
+ return { pids: [...pids], processGroups: [...processGroups] };
+}
+
+function posixTargetsAreAlive(targets: PosixTreeTargets): boolean {
+ return targets.processGroups.some(isProcessGroupAlive) || targets.pids.some(isAlive);
+}
+
+/** Best-effort group signals followed by direct signals to every captured PID. */
+function signalPosixTargets(targets: PosixTreeTargets, signal: NodeJS.Signals): void {
+ for (const pgid of targets.processGroups) {
+ try {
+ process.kill(-pgid, signal);
+ } catch {
+ // An already-dead group is safe to ignore. Direct PID signals below are
+ // still required because group-signal failure is not proof of PID exit.
+ }
+ }
+ for (const pid of targets.pids) {
+ try {
+ process.kill(pid, signal);
+ } catch {
+ // already dead
+ }
+ }
+}
+
+/** Stop the live Windows job supervisor and await its forced tree walk. */
+function taskkillTree(pid: number): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const killer = spawn("taskkill.exe", ["/pid", String(pid), "/t", "/f"], {
+ stdio: "ignore",
+ windowsHide: true,
+ });
+ let settled = false;
+ const settle = (result: "resolve" | "reject", error?: Error) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (result === "resolve") resolve();
+ else reject(error);
+ };
+ const timer = setTimeout(() => {
+ killer.kill();
+ settle("reject", new Error(`Windows process-tree termination timed out after ${TASKKILL_WAIT_MS}ms`));
+ }, TASKKILL_WAIT_MS);
+ timer.unref?.();
+ killer.once("error", (error) => {
+ settle("reject", new Error(`failed to launch Windows process-tree termination: ${error.message}`));
+ });
+ killer.once("close", (code, signal) => {
+ if (code === 0) {
+ settle("resolve");
+ return;
+ }
+ settle(
+ "reject",
+ new Error(`Windows process-tree termination failed (exit=${String(code)}, signal=${String(signal)})`),
+ );
+ });
+ });
+}
+
+async function killWindowsProcessTree(pid: number): Promise<void> {
+ if (!isAlive(pid)) return;
+ // A single /T /F call snapshots and terminates the complete tree while the
+ // wrapper pid is still alive. Killing the wrapper first would orphan the
+ // actual runtime and make a later tree walk unable to discover it. Windows
+ // has no safe recursive graceful-signal primitive, so start this immediately;
+ // the controller separately owns the public force deadline.
+ await taskkillTree(pid);
+ await waitForProcessExit(pid, FORCE_EXIT_WAIT_MS);
+ if (isAlive(pid)) throw new Error(`Windows process tree ${pid} remained alive after taskkill completed`);
+}
+
+async function waitForProcessExit(pid: number, timeoutMs: number): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (isAlive(pid) && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
+ }
+}
+
+/**
+ * Terminate `pid` and its descendants: POSIX process-group signals with force
+ * escalation after `graceMs`, or immediate Windows job-supervisor teardown.
+ * A dead Windows supervisor has already closed its kill-on-close job.
+ */
+export async function killProcessTree(
+ pid: number,
+ opts?: { graceMs?: number },
+): Promise<void> {
+ if (!pid || pid < 1) return;
+ if (!isPosix) {
+ if (!isAlive(pid)) return;
+ await killWindowsProcessTree(pid);
+ return;
+ }
+
+ const rootOwnsProcessGroup = isProcessGroupAlive(pid);
+ if (!rootOwnsProcessGroup && !isAlive(pid)) return;
+
+ // Capture descendants before TERM can make the root exit and reparent an
+ // escaped MCP subgroup. The snapshot remains the sole termination authority
+ // through force escalation; no later global process-table scan is used.
+ const targets = capturePosixTreeTargets(pid, rootOwnsProcessGroup);
+ const targetIsAlive = () => posixTargetsAreAlive(targets);
+
+ const graceMs = opts?.graceMs ?? DEFAULT_GRACE_MS;
+ signalPosixTargets(targets, "SIGTERM");
+
+ const deadline = Date.now() + graceMs;
+ while (Date.now() < deadline) {
+ if (!targetIsAlive()) return;
+ await new Promise((r) => setTimeout(r, POLL_MS));
+ }
+
+ if (targetIsAlive()) {
+ signalPosixTargets(targets, "SIGKILL");
+ const forceDeadline = Date.now() + FORCE_EXIT_WAIT_MS;
+ while (targetIsAlive() && Date.now() < forceDeadline) {
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
+ }
+ if (targetIsAlive()) throw new Error(`POSIX process tree ${pid} remained alive after SIGKILL`);
+ }
+}
diff --git a/src/daemon/agent-driver/src/internal/killTree.windows-errors.test.ts b/src/daemon/agent-driver/src/internal/killTree.windows-errors.test.ts
new file mode 100644
index 000000000..77de4388f
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/killTree.windows-errors.test.ts
@@ -0,0 +1,94 @@
+import { EventEmitter } from "node:events";
+import type { ChildProcess } from "node:child_process";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+function fakeChild(): ChildProcess & { kill: ReturnType<typeof vi.fn> } {
+ return Object.assign(new EventEmitter(), {
+ kill: vi.fn(() => true),
+ }) as unknown as ChildProcess & { kill: ReturnType<typeof vi.fn> };
+}
+
+async function importWithSpawn(spawn: ReturnType<typeof vi.fn>) {
+ vi.resetModules();
+ vi.doMock("child_process", async () => ({
+ ...await vi.importActual<typeof import("child_process")>("child_process"),
+ spawn,
+ }));
+ return import("./killTree.js");
+}
+
+afterEach(() => {
+ vi.doUnmock("child_process");
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe.skipIf(process.platform !== "win32")("Windows process-tree error handling", () => {
+ it("cleans up and rethrows when the PowerShell supervisor cannot spawn", async () => {
+ const spawn = vi.fn(() => { throw new Error("powershell unavailable"); });
+ const { spawnAgentProcess } = await importWithSpawn(spawn);
+
+ expect(() => spawnAgentProcess("agent.cmd", [], {
+ cwd: process.cwd(),
+ env: process.env,
+ stdin: "ignore",
+ })).toThrow("powershell unavailable");
+ });
+
+ it("surfaces taskkill launch and nonzero-exit failures", async () => {
+ vi.spyOn(process, "kill").mockImplementation(() => true);
+
+ const launchFailure = fakeChild();
+ let spawn = vi.fn(() => launchFailure);
+ let module = await importWithSpawn(spawn);
+ const launchStopping = module.killProcessTree(4_242);
+ launchFailure.emit("error", new Error("taskkill unavailable"));
+ await expect(launchStopping).rejects.toThrow("failed to launch Windows process-tree termination");
+
+ const exitFailure = fakeChild();
+ spawn = vi.fn(() => exitFailure);
+ module = await importWithSpawn(spawn);
+ const exitStopping = module.killProcessTree(4_242);
+ exitFailure.emit("close", 5, null);
+ await expect(exitStopping).rejects.toThrow("exit=5");
+ });
+
+ it("times out taskkill and kills the stuck helper", async () => {
+ vi.useFakeTimers();
+ vi.spyOn(process, "kill").mockImplementation(() => true);
+ const killer = fakeChild();
+ const { killProcessTree } = await importWithSpawn(vi.fn(() => killer));
+
+ const stopping = killProcessTree(4_242);
+ const rejected = expect(stopping).rejects.toThrow("termination timed out");
+ await vi.advanceTimersByTimeAsync(2_000);
+ await rejected;
+ expect(killer.kill).toHaveBeenCalledOnce();
+ });
+
+ it("waits for delayed process exit and rejects a tree that remains alive", async () => {
+ vi.useFakeTimers();
+ let checks = 0;
+ vi.spyOn(process, "kill").mockImplementation(() => {
+ checks += 1;
+ if (checks <= 3) return true;
+ throw Object.assign(new Error("not found"), { code: "ESRCH" });
+ });
+ let killer = fakeChild();
+ let module = await importWithSpawn(vi.fn(() => killer));
+ const delayedExit = module.killProcessTree(4_242);
+ killer.emit("close", 0, null);
+ await vi.advanceTimersByTimeAsync(100);
+ await expect(delayedExit).resolves.toBeUndefined();
+
+ vi.restoreAllMocks();
+ vi.spyOn(process, "kill").mockImplementation(() => true);
+ killer = fakeChild();
+ module = await importWithSpawn(vi.fn(() => killer));
+ const stuckTree = module.killProcessTree(4_242);
+ killer.emit("close", 0, null);
+ const rejected = expect(stuckTree).rejects.toThrow("remained alive after taskkill completed");
+ await vi.advanceTimersByTimeAsync(2_100);
+ await rejected;
+ });
+});
diff --git a/src/daemon/src/drivers/probe.test.ts b/src/daemon/agent-driver/src/internal/probe.test.ts
similarity index 57%
rename from src/daemon/src/drivers/probe.test.ts
rename to src/daemon/agent-driver/src/internal/probe.test.ts
index 2f8212363..d296cc817 100644
--- a/src/daemon/src/drivers/probe.test.ts
+++ b/src/daemon/agent-driver/src/internal/probe.test.ts
@@ -1,12 +1,15 @@
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { describe, it, expect, vi } from "vitest";
import { execFileSync } from "child_process";
-import { resolveSpawnSpec, probeCommandVersion } from "./probe";
+import { resolveClaudeCommand, resolveSpawnSpec, probeCliRuntime, probeCommandVersion } from "./probe.js";
vi.mock("child_process", () => ({ execFileSync: vi.fn() }));
/**
- * `resolveSpawnSpec` is what makes Cursor/Copilot/Antigravity/Kimi/OpenCode
- * (and Codex/Gemini) spawnable on Windows when the CLI resolves to a
+ * `resolveSpawnSpec` is what makes Cursor/OpenCode/Codex spawnable on Windows
+ * when the CLI resolves to a
* `.cmd`/`.bat` shim, which `child_process.spawn` can only exec through a
* shell. See plans/other-drivers-audit-fixes.md finding #2.
*/
@@ -27,23 +30,23 @@ describe("resolveSpawnSpec", () => {
});
it("sets shell: true on win32 when the resolved binary is a .bat shim", () => {
- const spec = resolveSpawnSpec("kimi", [], undefined, { which: () => "C:\\tools\\kimi.bat" }, "win32");
+ const spec = resolveSpawnSpec("opencode", [], undefined, { which: () => "C:\\tools\\opencode.bat" }, "win32");
expect(spec.shell).toBe(true);
});
it("does not set shell when the resolved binary is a native .exe on win32", () => {
- const spec = resolveSpawnSpec("copilot", [], undefined, { which: () => "C:\\tools\\copilot.exe" }, "win32");
+ const spec = resolveSpawnSpec("codex", [], undefined, { which: () => "C:\\tools\\codex.exe" }, "win32");
expect(spec.shell).toBe(false);
});
it("never sets shell on POSIX, even for a path that looks like a shim", () => {
- const spec = resolveSpawnSpec("agy", [], undefined, { which: () => "/usr/local/bin/agy.cmd" }, "darwin");
+ const spec = resolveSpawnSpec("opencode", [], undefined, { which: () => "/usr/local/bin/opencode.cmd" }, "darwin");
expect(spec.shell).toBe(false);
});
it("falls back to the bare command name when PATH resolution fails, without a shell on POSIX", () => {
- const spec = resolveSpawnSpec("opencode", ["run"], undefined, { which: () => null }, "linux");
- expect(spec).toEqual({ command: "opencode", args: ["run"], shell: false });
+ const spec = resolveSpawnSpec("opencode", ["serve"], undefined, { which: () => null }, "linux");
+ expect(spec).toEqual({ command: "opencode", args: ["serve"], shell: false });
});
it("honors an absolute-path override without re-resolving via PATH", () => {
@@ -54,10 +57,10 @@ describe("resolveSpawnSpec", () => {
});
it("resolves a bare-name override via PATH (so a user can point at a differently-named binary)", () => {
- const which = vi.fn(() => "/opt/kimi-custom/bin/kimi-alt");
- const spec = resolveSpawnSpec("kimi", [], "kimi-alt", { which }, "linux");
- expect(spec.command).toBe("/opt/kimi-custom/bin/kimi-alt");
- expect(which).toHaveBeenCalledWith("kimi-alt");
+ const which = vi.fn(() => "/opt/opencode-custom/bin/opencode-alt");
+ const spec = resolveSpawnSpec("opencode", [], "opencode-alt", { which }, "linux");
+ expect(spec.command).toBe("/opt/opencode-custom/bin/opencode-alt");
+ expect(which).toHaveBeenCalledWith("opencode-alt");
});
it("treats empty or whitespace-only override as absent (falls back to command)", () => {
@@ -68,6 +71,28 @@ describe("resolveSpawnSpec", () => {
});
});
+describe("resolveClaudeCommand", () => {
+ it("uses the macOS per-user app fallback when PATH has no Claude binary", () => {
+ const homeDir = mkdtempSync(join(tmpdir(), "claude-probe-home-"));
+ const platform = vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
+ try {
+ const executable = join(
+ homeDir,
+ "Applications/Claude Code URL Handler.app/Contents/MacOS/claude",
+ );
+ mkdirSync(join(executable, ".."), { recursive: true });
+ writeFileSync(executable, "");
+ expect(resolveClaudeCommand({
+ homeDir,
+ which: () => null,
+ })).toBe(executable);
+ } finally {
+ platform.mockRestore();
+ rmSync(homeDir, { recursive: true, force: true });
+ }
+ });
+});
+
/**
* Regression tests: `probeCommandVersion` — used by every non-Pi driver's
* `probe()` via `probeCliRuntime`/`probeClaude` — must agree with
@@ -94,49 +119,48 @@ describe("probeCommandVersion — Windows shim shell parity with resolveSpawnSpe
it("runs .bat shims through a shell on win32", () => {
vi.mocked(execFileSync).mockReturnValue("1.2.3\n");
- probeCommandVersion("C:\\tools\\kimi.bat", [], {}, "win32");
+ probeCommandVersion("C:\\tools\\opencode.bat", [], {}, "win32");
- expect(execFileSync).toHaveBeenCalledWith("C:\\tools\\kimi.bat", ["--version"], expect.objectContaining({ shell: true }));
+ expect(execFileSync).toHaveBeenCalledWith("C:\\tools\\opencode.bat", ["--version"], expect.objectContaining({ shell: true }));
});
it("does not use a shell for a native .exe on win32", () => {
vi.mocked(execFileSync).mockReturnValue("1.2.3\n");
- probeCommandVersion("C:\\tools\\copilot.exe", [], {}, "win32");
+ probeCommandVersion("C:\\tools\\codex.exe", [], {}, "win32");
- expect(execFileSync).toHaveBeenCalledWith("C:\\tools\\copilot.exe", ["--version"], expect.objectContaining({ shell: false }));
+ expect(execFileSync).toHaveBeenCalledWith("C:\\tools\\codex.exe", ["--version"], expect.objectContaining({ shell: false }));
});
it("never uses a shell on POSIX, even for a path that looks like a shim", () => {
vi.mocked(execFileSync).mockReturnValue("1.2.3\n");
- probeCommandVersion("/usr/local/bin/agy.cmd", [], {}, "darwin");
+ probeCommandVersion("/usr/local/bin/opencode.cmd", [], {}, "darwin");
- expect(execFileSync).toHaveBeenCalledWith("/usr/local/bin/agy.cmd", ["--version"], expect.objectContaining({ shell: false }));
+ expect(execFileSync).toHaveBeenCalledWith("/usr/local/bin/opencode.cmd", ["--version"], expect.objectContaining({ shell: false }));
});
});
/**
- * Version-shape validation + non-interactive spawn — the fix for the GitHub
- * Copilot shim that prints `Install GitHub Copilot CLI? ['y/N']` and exits 0.
- * The shim's prompt has no version token, so it must be rejected as
+ * Version-shape validation + non-interactive spawn. An installation prompt has
+ * no version token, so it must be rejected as
* `invalid_version_output` rather than surfacing as a bogus "version". These
* assert on the RETURNED result (the older tests only assert call args), so the
* validation is actually covered.
*/
describe("probeCommandVersion — version validation + non-interactive spawn", () => {
- it("rejects the Copilot install prompt (exit 0, no version token)", () => {
- vi.mocked(execFileSync).mockReturnValue("Install GitHub Copilot CLI? ['y/N'] ");
+ it("rejects an interactive install prompt (exit 0, no version token)", () => {
+ vi.mocked(execFileSync).mockReturnValue("Install runtime CLI? ['y/N'] ");
- const result = probeCommandVersion("copilot", [], {}, "darwin");
+ const result = probeCommandVersion("runtime-cli", [], {}, "darwin");
expect(result).toEqual({ ok: false, error: "invalid_version_output" });
});
it("rejects a non-version first line", () => {
- vi.mocked(execFileSync).mockReturnValue("Cannot find GitHub Copilot CLI\n");
+ vi.mocked(execFileSync).mockReturnValue("Cannot find runtime CLI\n");
- expect(probeCommandVersion("copilot", [], {}, "darwin")).toEqual({
+ expect(probeCommandVersion("runtime-cli", [], {}, "darwin")).toEqual({
ok: false,
error: "invalid_version_output",
});
@@ -145,7 +169,7 @@ describe("probeCommandVersion — version validation + non-interactive spawn", (
it("returns empty_version_output for blank output", () => {
vi.mocked(execFileSync).mockReturnValue("\n");
- expect(probeCommandVersion("copilot", [], {}, "darwin")).toEqual({
+ expect(probeCommandVersion("runtime-cli", [], {}, "darwin")).toEqual({
ok: false,
error: "empty_version_output",
});
@@ -166,10 +190,10 @@ describe("probeCommandVersion — version validation + non-interactive spawn", (
it("spawns non-interactively: empty stdin + CI env, stdout still piped", () => {
vi.mocked(execFileSync).mockReturnValue("1.2.3\n");
- probeCommandVersion("gemini", [], {}, "darwin");
+ probeCommandVersion("opencode", [], {}, "darwin");
expect(execFileSync).toHaveBeenCalledWith(
- "gemini",
+ "opencode",
["--version"],
expect.objectContaining({
input: "",
@@ -179,3 +203,21 @@ describe("probeCommandVersion — version validation + non-interactive spawn", (
);
});
});
+
+describe("probeCliRuntime command override", () => {
+ it("probes the explicit command without resolving the default binary", () => {
+ vi.mocked(execFileSync).mockReturnValue("custom v6.0.0\n");
+ const which = vi.fn(() => "/default/runtime");
+
+ expect(probeCliRuntime("default-runtime", { which }, "/custom/runtime")).toEqual({
+ status: "healthy",
+ version: "custom v6.0.0",
+ });
+ expect(which).not.toHaveBeenCalled();
+ expect(execFileSync).toHaveBeenCalledWith(
+ "/custom/runtime",
+ ["--version"],
+ expect.any(Object),
+ );
+ });
+});
diff --git a/src/daemon/src/drivers/probe.ts b/src/daemon/agent-driver/src/internal/probe.ts
similarity index 92%
rename from src/daemon/src/drivers/probe.ts
rename to src/daemon/agent-driver/src/internal/probe.ts
index 6150e3103..5182f520d 100644
--- a/src/daemon/src/drivers/probe.ts
+++ b/src/daemon/agent-driver/src/internal/probe.ts
@@ -5,7 +5,7 @@
import { execFileSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
-import type { ProbeResult } from "../types.js";
+import type { ProbeResult } from "./adapter.js";
/**
* Wall-clock cap for every `--version`/`where`/`which` probe. Kept short: a
@@ -41,14 +41,14 @@ export function resolveCommandOnPath(command: string, deps: ProbeDeps = {}): str
}
}
-export function firstExistingPath(candidates: string[]): string | null {
+function firstExistingPath(candidates: string[]): string | null {
for (const c of candidates) {
if (c && fs.existsSync(c)) return c;
}
return null;
}
-export type VersionProbeResult =
+type VersionProbeResult =
| { ok: true; version: string }
| { ok: false; error: string };
@@ -56,10 +56,9 @@ export type VersionProbeResult =
* A `--version` line must look like a version to be accepted: it has to contain
* a digit-dotted token (e.g. `1.2.3`, `v0.4`, `2024.1`). This is the
* load-bearing defense against a CLI whose `--version` doesn't print a version
- * but instead an interactive prompt or error. Confirmed case: the VS Code
- * GitHub Copilot shim resolves as `copilot` on PATH, exits 0, and prints
- * `Install GitHub Copilot CLI? ['y/N']` to stdout — no version token, so it's
- * rejected here rather than surfacing as a bogus "version" on the Runtimes
+ * but instead an interactive prompt or error. A shim can resolve on PATH, exit
+ * 0, and print an installation prompt with no version token; it is rejected
+ * here rather than surfacing as a bogus "version" on the Runtimes
* page. The non-interactive spawn options below can't catch it (the shim exits
* 0 even with stdin closed), so this regex is what draws the line.
*/
@@ -130,11 +129,11 @@ export function probeCommandVersion(
}
}
-export function resolveHomePath(relativePath: string, deps: ProbeDeps = {}): string {
+function resolveHomePath(relativePath: string, deps: ProbeDeps = {}): string {
return path.join(deps.homeDir || process.env.HOME || ".", relativePath);
}
-export interface SpawnSpec {
+interface SpawnSpec {
command: string;
args: string[];
/** Run through a shell — needed on Windows for `.cmd`/`.bat` shims. */
@@ -197,8 +196,9 @@ export function probeClaude(deps: ProbeDeps = {}): ProbeResult {
* rather than living inline so a future change to probe semantics is one edit,
* not eight.
*/
-export function probeCliRuntime(binary: string, deps: ProbeDeps = {}): ProbeResult {
- const command = resolveCommandOnPath(binary, deps);
+export function probeCliRuntime(binary: string, deps: ProbeDeps = {}, override?: string): ProbeResult {
+ const explicit = override?.trim();
+ const command = explicit || resolveCommandOnPath(binary, deps);
if (!command) return { status: "unhealthy", lastError: "not_on_path" };
const r = probeCommandVersion(command, [], deps);
if (!r.ok) return { status: "unhealthy", lastError: r.error };
diff --git a/src/daemon/agent-driver/src/internal/spawnAuthorityLint.test.ts b/src/daemon/agent-driver/src/internal/spawnAuthorityLint.test.ts
new file mode 100644
index 000000000..c8bae5330
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/spawnAuthorityLint.test.ts
@@ -0,0 +1,24 @@
+import { ESLint } from "eslint";
+import { fileURLToPath } from "node:url";
+import { resolve } from "node:path";
+import { describe, expect, it } from "vitest";
+
+const packageRoot = fileURLToPath(new URL("../../", import.meta.url));
+const adapterProbe = resolve(packageRoot, "src/adapters/__gate__.ts");
+
+describe("adapter process-spawn authority lint", () => {
+ it.each([
+ ["named import", 'import { spawn } from "node:child_process"; void spawn;'],
+ ["namespace import", 'import * as cp from "node:child_process"; void cp.spawn;'],
+ ["default import", 'import cp from "child_process"; void cp.spawn;'],
+ ["dynamic import", 'import("node:child_process").then((cp) => cp.spawn);'],
+ ])("rejects the %s bypass", async (_label, source) => {
+ const eslint = new ESLint({ cwd: packageRoot });
+ const [result] = await eslint.lintText(source, { filePath: adapterProbe });
+
+ expect(result?.errorCount).toBeGreaterThan(0);
+ expect(result?.messages.some((message) =>
+ message.ruleId === "no-restricted-imports" || message.ruleId === "no-restricted-syntax",
+ )).toBe(true);
+ });
+});
diff --git a/src/daemon/src/drivers/spawnEnv.test.ts b/src/daemon/agent-driver/src/internal/spawnEnv.test.ts
similarity index 98%
rename from src/daemon/src/drivers/spawnEnv.test.ts
rename to src/daemon/agent-driver/src/internal/spawnEnv.test.ts
index 1be988f35..178b77d49 100644
--- a/src/daemon/src/drivers/spawnEnv.test.ts
+++ b/src/daemon/agent-driver/src/internal/spawnEnv.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { mergeEnvLayers, platformEnv, runtimeContextEnv, describeProvenance, type EnvLayer } from "./spawnEnv";
+import { mergeEnvLayers, platformEnv, runtimeContextEnv, describeProvenance, type EnvLayer } from "./spawnEnv.js";
describe("mergeEnvLayers", () => {
it("applies non-sensitive layers in ascending precedence (higher wins)", () => {
diff --git a/src/daemon/src/drivers/spawnEnv.ts b/src/daemon/agent-driver/src/internal/spawnEnv.ts
similarity index 98%
rename from src/daemon/src/drivers/spawnEnv.ts
rename to src/daemon/agent-driver/src/internal/spawnEnv.ts
index 86dcff4a8..d9c31b905 100644
--- a/src/daemon/src/drivers/spawnEnv.ts
+++ b/src/daemon/agent-driver/src/internal/spawnEnv.ts
@@ -22,7 +22,7 @@ export interface EnvLayer {
sensitive?: boolean;
}
-export interface MergedEnv {
+interface MergedEnv {
env: NodeJS.ProcessEnv;
/** key → name of the layer that supplied the final value (for debug). */
provenance: Record<string, string>;
@@ -68,7 +68,7 @@ export function describeProvenance(layers: EnvLayer[], provenance: Record<string
* so changing the prefix or adding a key is type-checked instead of relying on
* scattered `${E}_XXX` string concatenation.
*/
-export interface PlatformEnvFields {
+interface PlatformEnvFields {
stateHome: string;
agentId: string;
cliName: string;
diff --git a/src/daemon/src/drivers/utils.test.ts b/src/daemon/agent-driver/src/internal/utils.test.ts
similarity index 51%
rename from src/daemon/src/drivers/utils.test.ts
rename to src/daemon/agent-driver/src/internal/utils.test.ts
index 0f6437484..239c758c0 100644
--- a/src/daemon/src/drivers/utils.test.ts
+++ b/src/daemon/agent-driver/src/internal/utils.test.ts
@@ -1,6 +1,5 @@
-import { describe, it, expect, vi } from "vitest";
-import { EventEmitter } from "events";
-import { jsonRpcRequest, tryParseJsonLine, writeToStdinAndDetach } from "./utils";
+import { describe, it, expect } from "vitest";
+import { jsonRpcRequest, tryParseJsonLine } from "./utils.js";
describe("jsonRpcRequest", () => {
it("produces a valid JSON-RPC 2.0 envelope with the given method and params", () => {
@@ -36,25 +35,3 @@ describe("tryParseJsonLine", () => {
expect(tryParseJsonLine("")).toBeNull();
});
});
-
-describe("writeToStdinAndDetach", () => {
- it("defers the write to a microtask and closes stdin exactly once after", async () => {
- const stdin = { write: vi.fn(), end: vi.fn() };
- const proc = Object.assign(new EventEmitter(), { stdin });
- writeToStdinAndDetach(proc as never, "hello");
-
- // Not written yet — microtask hasn't run.
- expect(stdin.write).not.toHaveBeenCalled();
- expect(stdin.end).not.toHaveBeenCalled();
-
- await Promise.resolve();
-
- expect(stdin.write).toHaveBeenCalledTimes(1);
- expect(stdin.write).toHaveBeenCalledWith("hello");
- expect(stdin.end).toHaveBeenCalledTimes(1);
- // write is called before end within the same microtask flush.
- const writeOrder = stdin.write.mock.invocationCallOrder[0];
- const endOrder = stdin.end.mock.invocationCallOrder[0];
- expect(writeOrder).toBeLessThan(endOrder);
- });
-});
diff --git a/src/daemon/src/drivers/utils.ts b/src/daemon/agent-driver/src/internal/utils.ts
similarity index 50%
rename from src/daemon/src/drivers/utils.ts
rename to src/daemon/agent-driver/src/internal/utils.ts
index 7d821bae3..42caf8d04 100644
--- a/src/daemon/src/drivers/utils.ts
+++ b/src/daemon/agent-driver/src/internal/utils.ts
@@ -2,30 +2,12 @@
* Small helpers shared across driver files. Each kills a duplication pattern
* that had multiple drivers copy-pasting the same 3-4 lines.
*/
-import type { ChildProcess } from "child_process";
import { randomUUID } from "crypto";
-/**
- * Write `payload` (already includes any trailing newline) to a child's stdin
- * on the next microtask, then close stdin. Used by drivers whose runtime is
- * one-shot: they spawn, deliver the prompt, and the runtime exits when
- * stdin closes.
- *
- * `queueMicrotask` mirrors codex's original pattern — it lets the caller
- * finish attaching stdout/stderr listeners before the write is scheduled, so
- * the child can never emit its first line into a listener-less pipe.
- */
-export function writeToStdinAndDetach(proc: ChildProcess, payload: string): void {
- queueMicrotask(() => {
- proc.stdin?.write(payload);
- proc.stdin?.end();
- });
-}
-
/**
* Build a JSON-RPC 2.0 request string (no trailing newline — the caller
- * appends one when writing to stdin). Both Codex and Kimi speak JSON-RPC over
- * stdio and every request they send follows this exact shape; centralize the
+ * appends one when writing to stdin). Codex uses this envelope for every
+ * request it sends; centralize the
* envelope so `id` defaulting and `jsonrpc` version live in one place.
*/
export function jsonRpcRequest(method: string, params: unknown, id?: string | number): string {
diff --git a/src/daemon/agent-driver/src/pack.test.ts b/src/daemon/agent-driver/src/pack.test.ts
new file mode 100644
index 000000000..72c61fba0
--- /dev/null
+++ b/src/daemon/agent-driver/src/pack.test.ts
@@ -0,0 +1,200 @@
+import { execFile } from "node:child_process";
+import {
+ chmodSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+
+const execFileAsync = promisify(execFile);
+const packageRoot = fileURLToPath(new URL("../", import.meta.url));
+const repositoryRoot = fileURLToPath(new URL("../../../../", import.meta.url));
+const tempRoots: string[] = [];
+
+afterEach(() => {
+ if (process.env.KEEP_AGENT_DRIVER_PACK_TEMP !== "1") {
+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });
+ }
+});
+
+function packageVersion(root: string): string {
+ return (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version: string }).version;
+}
+
+describe("packed @alook/agent-driver", () => {
+ it("shares the daemon version and installs with only its documented exports", { timeout: 120_000 }, async () => {
+ expect(packageVersion(packageRoot)).toBe(packageVersion(join(repositoryRoot, "src/daemon")));
+
+ const root = mkdtempSync(join(tmpdir(), "alook-agent-driver-pack-"));
+ const fixture = join(root, "consumer");
+ tempRoots.push(root);
+ mkdirSync(fixture, { recursive: true });
+ writeFileSync(join(root, "package.json"), '{"type":"module"}\n');
+ await execFileAsync("pnpm", ["pack", "--pack-destination", root], {
+ cwd: packageRoot,
+ maxBuffer: 10 * 1024 * 1024,
+ shell: process.platform === "win32",
+ });
+ const tarballName = readdirSync(root).find((name) => name.endsWith(".tgz"));
+ if (!tarballName) throw new Error("agent-driver pack did not produce a tarball");
+ const tarball = join(root, tarballName);
+
+ await execFileAsync("npm", ["install", "--ignore-scripts", "--no-audit", "--no-fund", tarball], {
+ cwd: root,
+ maxBuffer: 10 * 1024 * 1024,
+ shell: process.platform === "win32",
+ });
+ writeFileSync(join(root, "usage.ts"), `
+import { createAgentDriverSdk } from "@alook/agent-driver";
+
+const sdk = createAgentDriverSdk();
+const opened = await sdk.open({
+ backend: "codex",
+ launch: {
+ workingDirectory: ".",
+ instructions: { format: "markdown", content: "Be concise." },
+ launchId: "launch-example",
+ },
+ config: { model: { kind: "default" }, mode: "default" },
+});
+if (!opened.ok) throw new Error(opened.error.message);
+const session = opened.session;
+const observedText: string[] = [];
+const eventsDone = (async () => {
+ for await (const event of session.events) {
+ if (event.type === "text_delta") observedText.push(event.text);
+ }
+})();
+const receipt = await session.start({ id: "command-example", kind: "user", text: "Explain this repository." });
+if (receipt.status === "rejected") throw new Error(receipt.reason);
+await session.stop({ reason: "owner_request", forceAfterMs: 5_000 });
+const result = await session.closed;
+await eventsDone;
+void { result, observedText };
+`);
+ writeFileSync(join(root, "tsconfig.json"), JSON.stringify({
+ compilerOptions: {
+ target: "ES2022",
+ module: "NodeNext",
+ moduleResolution: "NodeNext",
+ strict: true,
+ noEmit: true,
+ skipLibCheck: false,
+ },
+ include: ["usage.ts"],
+ }));
+ const tsc = join(repositoryRoot, "node_modules", "typescript", "bin", "tsc");
+ await execFileAsync(process.execPath, [tsc, "-p", join(root, "tsconfig.json")], { cwd: root });
+
+ writeFileSync(join(root, "fake-cursor.mjs"), `
+import { createInterface } from "node:readline";
+const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
+for await (const line of createInterface({ input: process.stdin })) {
+ const message = JSON.parse(line);
+ if (message.method === "initialize") {
+ send({
+ jsonrpc: "2.0",
+ id: message.id,
+ result: {
+ protocolVersion: 1,
+ agentCapabilities: { loadSession: true },
+ authMethods: [{ id: "cursor_login", name: "Cursor Login" }],
+ },
+ });
+ } else if (message.method === "authenticate") {
+ send({ jsonrpc: "2.0", id: message.id, result: {} });
+ } else if (message.method === "session/new") {
+ send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "packed-session", configOptions: [] } });
+ } else if (message.method === "session/prompt") {
+ send({
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "packed-session",
+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "packed-ok" } },
+ },
+ });
+ send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } });
+ }
+}
+`);
+ const executable = process.platform === "win32"
+ ? join(root, "fake-cursor.cmd")
+ : join(root, "fake-cursor");
+ if (process.platform === "win32") {
+ writeFileSync(executable, "@node \"%~dp0\\fake-cursor.mjs\" %*\r\n");
+ } else {
+ writeFileSync(executable, `#!/usr/bin/env node\nawait import(${JSON.stringify(join(root, "fake-cursor.mjs"))});\n`);
+ chmodSync(executable, 0o755);
+ }
+ writeFileSync(join(root, "runtime.mjs"), `
+import { createBuiltinAgentDriverSdk } from "@alook/agent-driver/host";
+import { createFakeAgentDriverHost } from "@alook/agent-driver/testing";
+const sdk = createBuiltinAgentDriverSdk({ host: createFakeAgentDriverHost({
+ environmentLayers: {
+ base: process.env,
+ hostStatic: {}, identityProtected: {}, platformProtected: {},
+ runtimeProtected: {}, networkProtected: {}, credentialSensitive: {},
+ },
+}) });
+const opened = await sdk.open({
+ backend: "cursor",
+ launch: { workingDirectory: ${JSON.stringify(fixture)}, instructions: { format: "markdown", content: "Packed." }, launchId: "packed-launch" },
+ config: { model: { kind: "default" }, command: ${JSON.stringify(executable)} },
+});
+if (!opened.ok) throw new Error(opened.error.message);
+const events = [];
+const done = (async () => {
+ for await (const event of opened.session.events) {
+ events.push(event);
+ if (event.type === "turn_completed") return;
+ }
+})();
+const receipt = await opened.session.start({ id: "packed-command", kind: "user", text: "run" });
+if (receipt.status !== "accepted") throw new Error(JSON.stringify(receipt));
+await done;
+await opened.session.stop({ reason: "owner_request", forceAfterMs: 1_000 });
+await opened.session.closed;
+if (!events.some((event) => event.type === "text_delta" && event.text === "packed-ok")) throw new Error("missing packed text event: " + JSON.stringify(events));
+try {
+ await import("@alook/agent-driver/internal/adapter");
+ throw new Error("private subpath unexpectedly exported");
+} catch (error) {
+ if (error?.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw error;
+}
+`);
+ await execFileAsync(process.execPath, [join(root, "runtime.mjs")], { cwd: root });
+
+ const declarationFiles = readdirSync(join(root, "node_modules/@alook/agent-driver/dist"), { recursive: true })
+ .filter((name): name is string => typeof name === "string" && name.endsWith(".d.ts"));
+ const declarations = declarationFiles
+ .map((name) => readFileSync(join(root, "node_modules/@alook/agent-driver/dist", name), "utf8"))
+ .join("\n");
+ expect(declarations).not.toContain("@alook/daemon");
+ expect(declarations).not.toContain("src/daemon/src");
+ const installedDist = join(root, "node_modules/@alook/agent-driver/dist");
+ const rootDeclaration = readFileSync(join(installedDist, "index.d.ts"), "utf8");
+ const testingDeclaration = readFileSync(join(installedDist, "testing/index.d.ts"), "utf8");
+ const hostDeclaration = readFileSync(join(installedDist, "host.d.ts"), "utf8");
+ for (const privateName of [
+ "BackendAdapter",
+ "BackendExecution",
+ "SpawnedProcess",
+ "VendorSessionHandle",
+ "AgentBackendRegistration",
+ "createAgentDriverRegistry",
+ ]) {
+ expect(rootDeclaration).not.toContain(privateName);
+ expect(testingDeclaration).not.toContain(privateName);
+ expect(hostDeclaration).not.toContain(privateName);
+ }
+ });
+});
diff --git a/src/daemon/agent-driver/src/public-contract.ts b/src/daemon/agent-driver/src/public-contract.ts
new file mode 100644
index 000000000..bce89bb72
--- /dev/null
+++ b/src/daemon/agent-driver/src/public-contract.ts
@@ -0,0 +1,13 @@
+/** Consumer contract: logical SDK/session/event/result vocabulary only. */
+export type {
+ JsonPrimitive, JsonValue, JsonObject, BuiltinBackendId, ReasoningEffort, ModelSelection, DefaultProvider,
+ ClaudeProvider, PiProvider, BaseBackendConfig, ClaudeConfig, CodexConfig, ModelBackendConfig, CursorConfig,
+ OpenCodeConfig, PiConfig, BackendCapabilities, ClaudeCapabilities, CodexCapabilities, CursorCapabilities,
+ OpenCodeCapabilities, PiCapabilities, BackendExtensionSpec, BackendTypeSpec, BuiltinBackendSpecs, BackendId,
+ FixedCapabilities, ConfigOf, CapabilitiesOf, ExtensionsOf, ExtraEventOf, AgentInstructions, AgentLaunchContext, AgentMessage,
+ AgentDriverError, OpenSessionResult, DeliveryReceipt, InterruptResult, StopInput, StopReceipt, HostCleanupResult,
+ AgentSessionResult, AgentTurnResult, TokenUsage, CoreAgentEventPayload, AgentEventEnvelope, AgentEvent,
+ AgentSessionSnapshot, AgentEventStream, ExtensionNames, ExtensionInput, ExtensionOutput, ExtensionResult,
+ AgentSession, ProbeInput, BackendProbe, OpenSessionInput,
+ AgentDriverSdk,
+} from "./contract.js";
diff --git a/src/daemon/agent-driver/src/public-sdk.ts b/src/daemon/agent-driver/src/public-sdk.ts
new file mode 100644
index 000000000..96a135bae
--- /dev/null
+++ b/src/daemon/agent-driver/src/public-sdk.ts
@@ -0,0 +1,12 @@
+import type { AgentDriverSdk, BuiltinBackendSpecs } from "./contract.js";
+import { createAgentDriverSdk as createBuiltinSdk } from "./sdk.js";
+
+export interface PublicAgentDriverSdkOptions {
+ readonly hostReleaseTimeoutMs?: number;
+}
+
+export function createAgentDriverSdk(
+ options: PublicAgentDriverSdkOptions = {},
+): AgentDriverSdk<BuiltinBackendSpecs> {
+ return createBuiltinSdk(options);
+}
diff --git a/src/daemon/agent-driver/src/registry.test.ts b/src/daemon/agent-driver/src/registry.test.ts
new file mode 100644
index 000000000..876fa114b
--- /dev/null
+++ b/src/daemon/agent-driver/src/registry.test.ts
@@ -0,0 +1,158 @@
+import { describe, it, expect } from "vitest";
+import {
+ assertAdapterCompatibility, BUILTIN_BACKEND_IDS, capabilitiesFor, createAgentDriverRegistry,
+ createBuiltinAgentDriverRegistry,
+} from "./registry.js";
+import type { BackendCapabilities, BuiltinBackendId } from "./contract.js";
+import { ADAPTER_AUTHOR_CONTRACT_VERSION } from "./adapter-author.js";
+
+/**
+ * Every driver declares which `RuntimeConfig` fields it actually consumes,
+ * per the plan's capability matrix. This test pins that declaration so a
+ * silent drift (e.g. someone adds `reasoningEffort` to a driver's `buildArgs`
+ * without updating `capabilities`) trips CI.
+ */
+const EXPECTED: Record<BuiltinBackendId, BackendCapabilities> = {
+ claude: { modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: true, disallowedTools: true, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },
+ codex: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: true, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },
+ cursor: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "next_turn_queue", interrupt: true },
+ opencode: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
+ pi: { modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: false, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },
+};
+
+describe("driver.capabilities", () => {
+ it.each(BUILTIN_BACKEND_IDS)("%s declares the expected capability record", (id) => {
+ expect(capabilitiesFor(id)).toEqual(EXPECTED[id]);
+ });
+
+ it("pins the orthogonal built-in execution matrix and adapter-author version", () => {
+ expect(ADAPTER_AUTHOR_CONTRACT_VERSION).toBe(1);
+ const registry = createBuiltinAgentDriverRegistry();
+ const expected = {
+ claude: {
+ lifetime: "session",
+ transport: { kind: "stdio_stream", protocol: "claude.stream-json.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "vendor_message",
+ },
+ codex: {
+ lifetime: "session",
+ transport: { kind: "stdio_rpc", protocol: "codex.app-server.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ },
+ cursor: {
+ lifetime: "session",
+ transport: { kind: "stdio_rpc", protocol: "cursor.acp.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ },
+ opencode: {
+ lifetime: "session",
+ transport: { kind: "http_sse", protocol: "opencode.v2.service.1.17.20" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ },
+ pi: {
+ lifetime: "session",
+ transport: { kind: "in_process_sdk", protocol: "pi_sdk" },
+ wakeStart: "immediate",
+ terminalOwnership: "prompt_invocation",
+ },
+ } as const;
+ for (const id of BUILTIN_BACKEND_IDS) {
+ const registration = registry.get(id);
+ expect(registration.contractVersion).toBe(1);
+ expect(registration.createAdapter().execution).toEqual(expected[id]);
+ }
+ });
+});
+
+describe("adapter registration runtime boundary", () => {
+ it("rejects malformed registrations and duplicate ids at construction", () => {
+ expect(() => createAgentDriverRegistry([null] as never)).toThrow("Invalid agent backend registration");
+ expect(() => createAgentDriverRegistry([{
+ id: "",
+ capabilities: {},
+ createAdapter: () => ({}),
+ }] as never)).toThrow("non-empty id");
+ const registration = {
+ id: "sixth",
+ contractVersion: 1 as const,
+ capabilities: EXPECTED.claude,
+ createAdapter: () => ({}),
+ };
+ expect(() => createAgentDriverRegistry([registration, registration] as never)).toThrow("Duplicate agent backend registration");
+ });
+
+ it("accepts the public suggestion_only model-selection capability for extension adapters", () => {
+ const registration = {
+ id: "sixth",
+ contractVersion: 1 as const,
+ capabilities: { ...EXPECTED.claude, modelSelection: "suggestion_only" },
+ createAdapter: () => ({}),
+ };
+ expect(createAgentDriverRegistry([registration] as never).backendIds).toEqual(["sixth"]);
+ });
+
+ it("rejects each malformed registration capability and adapter shape at runtime", () => {
+ const valid = {
+ id: "sixth",
+ contractVersion: 1 as const,
+ capabilities: EXPECTED.claude,
+ createAdapter: () => new (class {
+ id = "sixth";
+ instructionDelivery = { kind: "native" } as const;
+ execution = {
+ lifetime: "session",
+ transport: { kind: "stdio_stream", protocol: "sixth.test.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "vendor_message",
+ } as const;
+ currentSessionId = null;
+ probe() { return { status: "healthy" as const }; }
+ normalizeLine() { return []; }
+ encodeMessage() { return ""; }
+ async openLane() { throw new Error("not opened by registration tests"); }
+ async spawn() { return { process: {} }; }
+ })(),
+ };
+ expect(() => createAgentDriverRegistry([{ ...valid, capabilities: null }] as never)).toThrow("requires capabilities");
+ expect(() => createAgentDriverRegistry([{ ...valid, capabilities: { ...EXPECTED.claude, resume: "bad" } }] as never)).toThrow("invalid capability resume");
+ expect(() => createAgentDriverRegistry([{ ...valid, capabilities: { ...EXPECTED.claude, interrupt: "yes" } }] as never)).toThrow("invalid capability interrupt");
+ expect(() => createAgentDriverRegistry([{ ...valid, createAdapter: null }] as never)).toThrow("requires createAdapter");
+ });
+
+ it("fails closed for missing, old, and unknown adapter-author contract versions", () => {
+ const valid = {
+ id: "sixth",
+ contractVersion: 1,
+ capabilities: EXPECTED.claude,
+ createAdapter: () => ({}),
+ };
+ for (const contractVersion of [undefined, 0, 2]) {
+ expect(() => createAgentDriverRegistry([{ ...valid, contractVersion }] as never))
+ .toThrow("unsupported adapter-author contract version");
+ }
+ });
+
+ it("rejects next-turn delivery adapters that declare a per-turn execution", () => {
+ const adapter = {
+ id: "sixth",
+ instructionDelivery: { kind: "native" },
+ execution: {
+ lifetime: "turn",
+ transport: { kind: "one_shot_cli", protocol: "sixth.test.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "lane_generation",
+ },
+ probe() {},
+ openLane() {},
+ };
+ expect(() => assertAdapterCompatibility(
+ "sixth",
+ { ...EXPECTED.claude, sessionLifetime: "per_turn" },
+ adapter,
+ )).toThrow("delivery conflicts with its execution lifetime");
+ });
+});
diff --git a/src/daemon/agent-driver/src/registry.ts b/src/daemon/agent-driver/src/registry.ts
new file mode 100644
index 000000000..fb10dc8fe
--- /dev/null
+++ b/src/daemon/agent-driver/src/registry.ts
@@ -0,0 +1,206 @@
+import type {
+ BackendCapabilities,
+ BackendId,
+ BuiltinBackendId,
+ BuiltinBackendSpecs,
+ CapabilitiesOf,
+ ConfigOf,
+} from "./contract.js";
+import { ClaudeDriver } from "./adapters/claude/index.js";
+import { CodexDriver } from "./adapters/codex/index.js";
+import { CursorDriver } from "./adapters/cursor/index.js";
+import { OpenCodeDriver } from "./adapters/opencode/index.js";
+import { PiDriver } from "./adapters/pi/index.js";
+import type { BackendAdapter } from "./internal/adapter.js";
+
+export interface AgentBackendRegistration<Specs, Id extends BackendId<Specs>> {
+ readonly id: Id;
+ readonly contractVersion: 1;
+ readonly capabilities: CapabilitiesOf<Specs, Id>;
+ createAdapter(): BackendAdapter<Id, ConfigOf<Specs, Id>>;
+}
+
+export type AgentBackendRegistrationOf<Specs> = {
+ [Id in BackendId<Specs>]: AgentBackendRegistration<Specs, Id>;
+}[BackendId<Specs>];
+
+export interface AgentDriverRegistry<Specs> {
+ readonly backendIds: readonly BackendId<Specs>[];
+ get<Id extends BackendId<Specs>>(id: Id): AgentBackendRegistration<Specs, Id>;
+}
+
+export function createAgentDriverRegistry<Specs>(
+ registrations: readonly AgentBackendRegistrationOf<Specs>[],
+): AgentDriverRegistry<Specs> {
+ const entries = new Map<string, AgentBackendRegistrationOf<Specs>>();
+ for (const registration of registrations) {
+ assertRegistrationShape(registration);
+ if (entries.has(registration.id)) throw new Error(`Duplicate agent backend registration: ${registration.id}`);
+ entries.set(registration.id, Object.freeze({ ...registration }));
+ }
+ const backendIds = Object.freeze([...entries.keys()]) as readonly BackendId<Specs>[];
+ return Object.freeze({
+ backendIds,
+ get<Id extends BackendId<Specs>>(id: Id): AgentBackendRegistration<Specs, Id> {
+ const registration = entries.get(id);
+ if (!registration) throw new Error(`Unknown agent backend: ${id}`);
+ return registration as AgentBackendRegistration<Specs, Id>;
+ },
+ });
+}
+
+export function assertRegistrationShape(registration: unknown): void {
+ if (!registration || typeof registration !== "object") throw new Error("Invalid agent backend registration");
+ const candidate = registration as Record<string, unknown>;
+ if (typeof candidate.id !== "string" || candidate.id.length === 0) {
+ throw new Error("Agent backend registration requires a non-empty id");
+ }
+ if (candidate.contractVersion !== 1) {
+ throw new Error(`Agent backend registration ${candidate.id} has an unsupported adapter-author contract version`);
+ }
+ if (!candidate.capabilities || typeof candidate.capabilities !== "object") {
+ throw new Error(`Agent backend registration ${candidate.id} requires capabilities`);
+ }
+ const capabilities = candidate.capabilities as Record<string, unknown>;
+ const enumFields = {
+ modelSelection: ["launchable", "suggestion_only", "unsupported"],
+ resume: ["by_id", "none"],
+ sessionLifetime: ["persistent", "per_turn"],
+ midTurnDelivery: ["safe_boundary_queue", "steer", "next_turn_queue"],
+ } as const;
+ for (const [field, allowed] of Object.entries(enumFields)) {
+ if (!allowed.includes(String(capabilities[field]) as never)) {
+ throw new Error(`Agent backend registration ${candidate.id} has invalid capability ${field}`);
+ }
+ }
+ for (const field of [
+ "providerConfiguration",
+ "reasoningEffort",
+ "fastMode",
+ "disallowedTools",
+ "commandOverride",
+ "interrupt",
+ ] as const) {
+ if (typeof capabilities[field] !== "boolean") {
+ throw new Error(`Agent backend registration ${candidate.id} has invalid capability ${field}`);
+ }
+ }
+ if (typeof candidate.createAdapter !== "function") {
+ throw new Error(`Agent backend registration ${candidate.id} requires createAdapter()`);
+ }
+}
+
+export function assertAdapterCompatibility(
+ registrationId: string,
+ registeredCapabilities: unknown,
+ adapter: unknown,
+): asserts adapter is BackendAdapter<string, unknown> {
+ if (!adapter || typeof adapter !== "object") throw new Error(`Adapter ${registrationId} factory returned no adapter`);
+ const candidate = adapter as Record<string, unknown>;
+ if (candidate.id !== registrationId) {
+ throw new Error(`Adapter identity mismatch for registration ${registrationId}`);
+ }
+ for (const method of ["probe", "openLane"] as const) {
+ if (typeof candidate[method] !== "function") throw new Error(`Adapter ${registrationId} is missing ${method}()`);
+ }
+ const instruction = candidate.instructionDelivery as Record<string, unknown> | undefined;
+ if (!instruction || (instruction.kind !== "native" && instruction.kind !== "workspace_file")) {
+ throw new Error(`Adapter ${registrationId} has an invalid instructionDelivery declaration`);
+ }
+ if (
+ instruction.kind === "workspace_file"
+ && (
+ typeof instruction.canonical !== "string"
+ || instruction.canonical.length === 0
+ || !Array.isArray(instruction.aliases)
+ || !instruction.aliases.every((alias) => typeof alias === "string")
+ )
+ ) {
+ throw new Error(`Adapter ${registrationId} has an invalid workspace_file instruction declaration`);
+ }
+ const execution = candidate.execution as Record<string, unknown> | undefined;
+ if (
+ !execution
+ || (execution.lifetime !== "session" && execution.lifetime !== "turn")
+ || (execution.wakeStart !== "immediate" && execution.wakeStart !== "deferred")
+ || !["transport_request", "vendor_message", "prompt_invocation", "lane_generation"]
+ .includes(String(execution.terminalOwnership))
+ ) {
+ throw new Error(`Adapter ${registrationId} has an invalid execution declaration`);
+ }
+ const transport = execution.transport as Record<string, unknown> | undefined;
+ if (
+ !transport
+ || typeof transport.kind !== "string"
+ || transport.kind.trim().length === 0
+ || typeof transport.protocol !== "string"
+ || transport.protocol.trim().length === 0
+ || (
+ transport.metadata !== undefined
+ && (
+ !transport.metadata
+ || typeof transport.metadata !== "object"
+ || Array.isArray(transport.metadata)
+ )
+ )
+ ) {
+ throw new Error(`Adapter ${registrationId} has an invalid transport declaration`);
+ }
+ const capabilities = registeredCapabilities as Record<string, unknown> | undefined;
+ const declaredLifetime = capabilities?.sessionLifetime === "persistent" ? "session" : "turn";
+ if (execution.lifetime !== declaredLifetime) {
+ throw new Error(`Adapter ${registrationId} lifetime conflicts with its registered capabilities`);
+ }
+ if (
+ capabilities?.midTurnDelivery !== "next_turn_queue"
+ && execution.lifetime !== "session"
+ ) {
+ throw new Error(`Adapter ${registrationId} delivery conflicts with its execution lifetime`);
+ }
+ if (execution.wakeStart === "deferred" && execution.lifetime !== "turn") {
+ throw new Error(`Adapter ${registrationId} has an invalid deferred wake declaration`);
+ }
+}
+
+export const BUILTIN_BACKEND_IDS = ["claude", "codex", "cursor", "opencode", "pi"] as const;
+
+const capabilities = {
+ claude: {
+ modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: true,
+ disallowedTools: true, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true,
+ },
+ codex: {
+ modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: true,
+ disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true,
+ },
+ cursor: {
+ modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false,
+ disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "next_turn_queue", interrupt: true,
+ },
+ opencode: {
+ modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false,
+ disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,
+ },
+ pi: {
+ modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: false,
+ disallowedTools: false, commandOverride: false, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,
+ },
+} as const satisfies Record<BuiltinBackendId, BackendCapabilities>;
+
+export function createBuiltinAgentDriverRegistry(): AgentDriverRegistry<BuiltinBackendSpecs> {
+ return createAgentDriverRegistry<BuiltinBackendSpecs>([
+ { id: "claude", contractVersion: 1, capabilities: capabilities.claude, createAdapter: () => new ClaudeDriver() },
+ { id: "codex", contractVersion: 1, capabilities: capabilities.codex, createAdapter: () => new CodexDriver() },
+ { id: "cursor", contractVersion: 1, capabilities: capabilities.cursor, createAdapter: () => new CursorDriver() },
+ { id: "opencode", contractVersion: 1, capabilities: capabilities.opencode, createAdapter: () => new OpenCodeDriver() },
+ { id: "pi", contractVersion: 1, capabilities: capabilities.pi, createAdapter: () => new PiDriver() },
+ ]);
+}
+
+const builtinRegistry = createBuiltinAgentDriverRegistry();
+
+export function capabilitiesFor<Id extends BuiltinBackendId>(
+ backend: Id,
+): CapabilitiesOf<BuiltinBackendSpecs, Id> {
+ return builtinRegistry.get(backend).capabilities;
+}
diff --git a/src/daemon/agent-driver/src/sdk.test.ts b/src/daemon/agent-driver/src/sdk.test.ts
new file mode 100644
index 000000000..54085dae1
--- /dev/null
+++ b/src/daemon/agent-driver/src/sdk.test.ts
@@ -0,0 +1,478 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type {
+ AgentDriverError,
+ BackendTypeSpec,
+ BuiltinBackendSpecs,
+} from "./index.js";
+import type { BackendAdapter } from "./adapter-author.js";
+import type { AgentDriverHost } from "./host.js";
+import { ClaudeDriver } from "./adapters/claude/index.js";
+import { createFakeAgentDriverHost } from "./testing/fake-host.js";
+import { createAgentDriverSdk, createAgentDriverSdkWithRegistry } from "./sdk.js";
+import { createAgentDriverRegistry, type AgentDriverRegistry } from "./registry.js";
+import { createAgentDriverSdk as createPublicAgentDriverSdk } from "./public-sdk.js";
+
+const claudeInput = {
+ backend: "claude" as const,
+ launch: {
+ workingDirectory: process.cwd(),
+ instructions: { format: "markdown" as const, content: "" },
+ launchId: "launch-1",
+ },
+ config: {
+ model: { kind: "default" as const },
+ provider: { kind: "default" as const },
+ mode: "default" as const,
+ },
+};
+
+const claudeCapabilities = {
+ modelSelection: "launchable",
+ providerConfiguration: true,
+ reasoningEffort: true,
+ fastMode: true,
+ disallowedTools: true,
+ commandOverride: true,
+ resume: "by_id",
+ sessionLifetime: "persistent",
+ midTurnDelivery: "safe_boundary_queue",
+ interrupt: true,
+} as const;
+
+afterEach(() => vi.restoreAllMocks());
+
+function sdkTestLane(receipt = "fresh-receipt") {
+ return {
+ currentSessionId: "fresh-session",
+ start: vi.fn(async () => ({ ok: true as const, acceptedAs: "prompt" as const, receipt })),
+ send: vi.fn(async () => ({ ok: true as const, acceptedAs: "prompt" as const, receipt })),
+ interrupt: vi.fn(async () => false),
+ stop: vi.fn(async () => {}),
+ on: vi.fn(),
+ };
+}
+
+describe("createAgentDriverSdk", () => {
+ it("exposes the built-ins with default options", () => {
+ expect(createAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "opencode", "pi"]);
+ });
+
+ it("maps healthy, unhealthy, and thrown adapter probes", async () => {
+ const sdk = createAgentDriverSdk();
+ const probe = vi.spyOn(ClaudeDriver.prototype, "probe");
+ probe.mockResolvedValueOnce({ status: "healthy", version: "1.2.3" });
+ await expect(sdk.probe({ backend: "claude", command: "claude-test" })).resolves.toMatchObject({
+ status: "healthy",
+ version: "1.2.3",
+ });
+
+ probe.mockResolvedValueOnce({ status: "unhealthy", lastError: "not_found" });
+ await expect(sdk.probe({ backend: "claude" })).resolves.toMatchObject({
+ status: "unhealthy",
+ error: { code: "not_found" },
+ });
+
+ probe.mockRejectedValueOnce(new Error("probe exploded"));
+ await expect(sdk.probe({ backend: "claude" })).resolves.toMatchObject({
+ status: "unhealthy",
+ error: { code: "probe_threw", message: "Backend claude probe failed" },
+ });
+ });
+
+ it.each(["claude", "codex", "cursor", "opencode"] as const)(
+ "forwards an explicit command override through the real %s probe",
+ async (backend) => {
+ await expect(createAgentDriverSdk().probe({ backend, command: process.execPath })).resolves.toMatchObject({
+ status: "healthy",
+ });
+ },
+ );
+
+ it("public SDK factory delegates to the built-in logical SDK", () => {
+ expect(createPublicAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "opencode", "pi"]);
+ });
+
+ it("returns host preparation failures without constructing a session", async () => {
+ const error: AgentDriverError = {
+ category: "configuration",
+ code: "prepare_failed",
+ message: "cannot prepare",
+ retryable: false,
+ };
+ const host = {
+ prepareExecution: vi.fn(async () => ({ ok: false as const, error })),
+ onRawOutput: vi.fn(),
+ now: () => 1,
+ createId: () => "id",
+ } satisfies AgentDriverHost;
+ await expect(createAgentDriverSdk({ host }).open(claudeInput)).resolves.toEqual({ ok: false, error });
+ });
+
+ it("opens a logical session using the prepared host resource", async () => {
+ const host = createFakeAgentDriverHost();
+ const opened = await createAgentDriverSdk({ host, hostReleaseTimeoutMs: 25 }).open(claudeInput);
+ expect(opened.ok).toBe(true);
+ if (!opened.ok) throw new Error("expected a session");
+ expect(opened.capabilities.midTurnDelivery).toBe("safe_boundary_queue");
+ expect(opened.session.snapshot()).toMatchObject({ state: "new", queuedCommands: [] });
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 1 });
+ expect(host.releases).toHaveLength(1);
+ });
+
+ it("creates a fresh workspace before public instruction materialization and lane open", async () => {
+ const base = mkdtempSync(join(tmpdir(), "agent-driver-fresh-workspace-"));
+ const workingDirectory = join(base, "nested", "agent");
+ const host = createFakeAgentDriverHost();
+ const adapter = new ClaudeDriver();
+ vi.spyOn(adapter, "beginTurn").mockReturnValue("fresh-receipt");
+ const lane = sdkTestLane();
+ const openLane = vi.spyOn(adapter, "openLane").mockImplementation(async (ctx) => {
+ expect(ctx.workingDirectory).toBe(workingDirectory);
+ expect(readFileSync(join(workingDirectory, "AGENTS.md"), "utf8")).toBe("Fresh instructions.");
+ expect(readFileSync(join(workingDirectory, "CLAUDE.md"), "utf8")).toBe("Fresh instructions.");
+ return lane;
+ });
+ const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
+ id: "claude",
+ contractVersion: 1,
+ capabilities: claudeCapabilities,
+ createAdapter: () => adapter,
+ }]);
+
+ try {
+ const opened = await createAgentDriverSdkWithRegistry({ registry, host }).open({
+ ...claudeInput,
+ launch: {
+ ...claudeInput.launch,
+ workingDirectory,
+ instructions: { format: "markdown", content: "Fresh instructions." },
+ },
+ });
+ expect(opened.ok).toBe(true);
+ if (!opened.ok) throw new Error("expected a session");
+ await expect(opened.session.start({ id: "fresh", kind: "user", text: "hello" }))
+ .resolves.toMatchObject({ status: "accepted" });
+ expect(openLane).toHaveBeenCalledTimes(1);
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 1 });
+ expect(lane.stop).toHaveBeenCalledTimes(1);
+ expect(host.releases).toHaveLength(1);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ it("creates a fresh workspace for empty instructions before lane open", async () => {
+ const base = mkdtempSync(join(tmpdir(), "agent-driver-empty-workspace-"));
+ const workingDirectory = join(base, "nested", "agent");
+ const host = createFakeAgentDriverHost();
+ const adapter = new ClaudeDriver();
+ vi.spyOn(adapter, "beginTurn").mockReturnValue("fresh-receipt");
+ const lane = sdkTestLane();
+ const openLane = vi.spyOn(adapter, "openLane").mockImplementation(async () => {
+ expect(existsSync(workingDirectory)).toBe(true);
+ return lane;
+ });
+ const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
+ id: "claude",
+ contractVersion: 1,
+ capabilities: claudeCapabilities,
+ createAdapter: () => adapter,
+ }]);
+
+ try {
+ const opened = await createAgentDriverSdkWithRegistry({ registry, host }).open({
+ ...claudeInput,
+ launch: { ...claudeInput.launch, workingDirectory },
+ });
+ expect(opened.ok).toBe(true);
+ if (!opened.ok) throw new Error("expected a session");
+ await expect(opened.session.start({ id: "fresh-empty", kind: "user", text: "hello" }))
+ .resolves.toMatchObject({ status: "accepted" });
+ expect(openLane).toHaveBeenCalledTimes(1);
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 1 });
+ expect(host.releases).toHaveLength(1);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ it("preserves existing workspace content while materializing instructions", async () => {
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-existing-workspace-"));
+ const marker = join(workingDirectory, "keep.txt");
+ writeFileSync(marker, "keep me");
+ const host = createFakeAgentDriverHost();
+ const adapter = new ClaudeDriver();
+ vi.spyOn(adapter, "beginTurn").mockReturnValue("fresh-receipt");
+ const lane = sdkTestLane();
+ vi.spyOn(adapter, "openLane").mockResolvedValue(lane);
+ const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
+ id: "claude",
+ contractVersion: 1,
+ capabilities: claudeCapabilities,
+ createAdapter: () => adapter,
+ }]);
+
+ try {
+ const opened = await createAgentDriverSdkWithRegistry({ registry, host }).open({
+ ...claudeInput,
+ launch: {
+ ...claudeInput.launch,
+ workingDirectory,
+ instructions: { format: "markdown", content: "Existing workspace instructions." },
+ },
+ });
+ expect(opened.ok).toBe(true);
+ if (!opened.ok) throw new Error("expected a session");
+ await expect(opened.session.start({ id: "existing", kind: "user", text: "hello" }))
+ .resolves.toMatchObject({ status: "accepted" });
+ expect(readFileSync(marker, "utf8")).toBe("keep me");
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 1 });
+ expect(host.releases).toHaveLength(1);
+ } finally {
+ rmSync(workingDirectory, { recursive: true, force: true });
+ }
+ });
+
+ it("fails closed before physical lane open when the workspace path is not a directory", async () => {
+ const base = mkdtempSync(join(tmpdir(), "agent-driver-invalid-workspace-"));
+ const workingDirectory = join(base, "not-a-directory");
+ writeFileSync(workingDirectory, "occupied");
+ const host = createFakeAgentDriverHost();
+ const adapter = new ClaudeDriver();
+ const openLane = vi.spyOn(adapter, "openLane").mockResolvedValue(sdkTestLane());
+ const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
+ id: "claude",
+ contractVersion: 1,
+ capabilities: claudeCapabilities,
+ createAdapter: () => adapter,
+ }]);
+
+ try {
+ const opened = await createAgentDriverSdkWithRegistry({ registry, host }).open({
+ ...claudeInput,
+ launch: {
+ ...claudeInput.launch,
+ workingDirectory,
+ instructions: { format: "markdown", content: "Cannot be written." },
+ },
+ });
+ expect(opened.ok).toBe(true);
+ if (!opened.ok) throw new Error("expected a session");
+ const eventTypes = (async () => {
+ const types: string[] = [];
+ for await (const event of opened.session.events) types.push(event.type);
+ return types;
+ })();
+ await expect(opened.session.start({ id: "blocked", kind: "user", text: "hello" }))
+ .resolves.toMatchObject({ status: "rejected", reason: "runtime_unavailable" });
+ await expect(opened.session.closed).resolves.toMatchObject({ outcome: "failed_to_start" });
+ expect(await eventTypes).not.toContain("session_started");
+ expect(openLane).not.toHaveBeenCalled();
+ expect(opened.session.snapshot().diagnostics.metrics.physicalOpenCount).toBe(0);
+ expect(host.releases).toHaveLength(1);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ it("opens a sixth backend through only its public adapter registration", async () => {
+ const capabilities = {
+ modelSelection: "unsupported",
+ providerConfiguration: false,
+ reasoningEffort: false,
+ fastMode: false,
+ disallowedTools: false,
+ commandOverride: false,
+ resume: "none",
+ sessionLifetime: "per_turn",
+ midTurnDelivery: "next_turn_queue",
+ interrupt: false,
+ } as const;
+ interface SixthSpecs {
+ readonly sixth: BackendTypeSpec<
+ { readonly flavor: string },
+ typeof capabilities,
+ Record<never, never>,
+ never
+ >;
+ }
+ const adapter: BackendAdapter<"sixth", { readonly flavor: string }> = {
+ id: "sixth",
+ instructionDelivery: { kind: "native" },
+ execution: {
+ lifetime: "turn",
+ transport: { kind: "one_shot_cli", protocol: "sixth.test.v1" },
+ wakeStart: "deferred",
+ terminalOwnership: "lane_generation",
+ },
+ probe: vi.fn(() => ({ status: "healthy" as const, version: "6.0.0" })),
+ openLane: vi.fn(async () => { throw new Error("not started by this test"); }),
+ };
+ const registry = createAgentDriverRegistry<SixthSpecs>([{
+ id: "sixth",
+ contractVersion: 1,
+ capabilities,
+ createAdapter: () => adapter,
+ }]);
+ const sdk = createAgentDriverSdkWithRegistry({ registry, host: createFakeAgentDriverHost() });
+
+ expect(sdk.backendIds).toEqual(["sixth"]);
+ await expect(sdk.probe({ backend: "sixth" })).resolves.toMatchObject({
+ status: "healthy",
+ version: "6.0.0",
+ capabilities,
+ });
+ const opened = await sdk.open({
+ backend: "sixth",
+ launch: {
+ workingDirectory: process.cwd(),
+ instructions: { format: "markdown", content: "native instructions" },
+ launchId: "sixth-launch",
+ },
+ config: { flavor: "vanilla" },
+ });
+ expect(opened.ok).toBe(true);
+ if (!opened.ok) return;
+ expect(opened.session.backend).toBe("sixth");
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 1 });
+ });
+
+ it("fails adapter identity validation before host preparation", async () => {
+ const host = createFakeAgentDriverHost();
+ const prepare = vi.spyOn(host, "prepareExecution");
+ const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
+ id: "claude",
+ contractVersion: 1,
+ capabilities: claudeCapabilities,
+ createAdapter: () => {
+ const adapter = new ClaudeDriver();
+ Object.defineProperty(adapter, "id", { value: "codex" });
+ return adapter;
+ },
+ }]);
+ const sdk = createAgentDriverSdkWithRegistry({ registry, host });
+
+ await expect(sdk.probe({ backend: "claude" })).resolves.toMatchObject({
+ status: "unhealthy",
+ error: { code: "adapter_contract_invalid", retryable: false },
+ });
+ await expect(sdk.open(claudeInput)).resolves.toMatchObject({
+ ok: false,
+ error: { code: "adapter_contract_invalid", retryable: false },
+ });
+ expect(prepare).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["missing", undefined],
+ ["old", 0],
+ ["unknown", 2],
+ ] as const)("fails a %s contract version from an untrusted custom registry before side effects", async (_name, version) => {
+ const host = createFakeAgentDriverHost();
+ const prepare = vi.spyOn(host, "prepareExecution");
+ const createAdapter = vi.fn(() => new ClaudeDriver());
+ const registry = {
+ backendIds: ["claude"],
+ get: () => ({
+ id: "claude",
+ contractVersion: version,
+ capabilities: claudeCapabilities,
+ createAdapter,
+ }),
+ } as unknown as AgentDriverRegistry<BuiltinBackendSpecs>;
+ const sdk = createAgentDriverSdkWithRegistry({ registry, host });
+
+ await expect(sdk.probe({ backend: "claude" })).resolves.toMatchObject({
+ status: "unhealthy",
+ error: { code: "adapter_contract_invalid", retryable: false },
+ });
+ await expect(sdk.open(claudeInput)).resolves.toMatchObject({
+ ok: false,
+ error: { code: "adapter_contract_invalid", retryable: false },
+ });
+ expect(createAdapter).not.toHaveBeenCalled();
+ expect(prepare).not.toHaveBeenCalled();
+ });
+
+ it("accepts an opaque third-party transport kind without protocol-name branching", async () => {
+ const adapter = new ClaudeDriver();
+ Object.defineProperty(adapter, "execution", {
+ configurable: true,
+ value: {
+ lifetime: "session",
+ transport: {
+ kind: "websocket_multiplex",
+ protocol: "third-party.example.v7",
+ metadata: { framing: "binary" },
+ },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ },
+ });
+ vi.spyOn(adapter, "probe").mockReturnValue({ status: "healthy", version: "7.0.0" });
+ const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
+ id: "claude",
+ contractVersion: 1,
+ capabilities: claudeCapabilities,
+ createAdapter: () => adapter,
+ }]);
+
+ await expect(createAgentDriverSdkWithRegistry({ registry }).probe({ backend: "claude" }))
+ .resolves.toMatchObject({ status: "healthy", version: "7.0.0" });
+ });
+
+ it.each([
+ ["missing probe", { probe: undefined }],
+ ["invalid instruction kind", { instructionDelivery: { kind: "raw" } }],
+ ["incomplete execution", { execution: {
+ lifetime: "session", transport: { kind: "stdio_stream", protocol: "claude.test.v1" }, wakeStart: "unknown",
+ terminalOwnership: "vendor_message",
+ } }],
+ ["invalid execution kind", { execution: { lifetime: "raw" } }],
+ ["invalid transport", { execution: {
+ lifetime: "session", transport: { kind: "stdio_stream", protocol: "" }, wakeStart: "immediate",
+ terminalOwnership: "vendor_message",
+ } }],
+ ["lifetime mismatch", { execution: {
+ lifetime: "turn", transport: { kind: "one_shot_cli", protocol: "claude.test.v1" }, wakeStart: "immediate",
+ terminalOwnership: "lane_generation",
+ } }],
+ ["deferred persistent wake", { execution: {
+ lifetime: "session", transport: { kind: "stdio_stream", protocol: "claude.test.v1" }, wakeStart: "deferred",
+ terminalOwnership: "vendor_message",
+ } }],
+ ["invalid workspace instruction", {
+ instructionDelivery: { kind: "workspace_file", canonical: "", aliases: [1] },
+ }],
+ ["missing lane factory", { openLane: undefined }],
+ ] as const)("fails %s adapter shape validation before host preparation", async (_name, override) => {
+ const host = createFakeAgentDriverHost();
+ const prepare = vi.spyOn(host, "prepareExecution");
+ const valid = new ClaudeDriver();
+ const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
+ id: "claude",
+ contractVersion: 1,
+ capabilities: claudeCapabilities,
+ createAdapter: () => {
+ for (const [key, value] of Object.entries(override)) {
+ Object.defineProperty(valid, key, { configurable: true, value });
+ }
+ return valid as never;
+ },
+ }]);
+ const sdk = createAgentDriverSdkWithRegistry({ registry, host });
+
+ await expect(sdk.probe({ backend: "claude" })).resolves.toMatchObject({
+ status: "unhealthy",
+ error: { code: "adapter_contract_invalid", retryable: false },
+ });
+ await expect(sdk.open(claudeInput)).resolves.toMatchObject({
+ ok: false,
+ error: { code: "adapter_contract_invalid", retryable: false },
+ });
+ expect(prepare).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/daemon/agent-driver/src/sdk.ts b/src/daemon/agent-driver/src/sdk.ts
new file mode 100644
index 000000000..ca568f0ba
--- /dev/null
+++ b/src/daemon/agent-driver/src/sdk.ts
@@ -0,0 +1,123 @@
+import type {
+ AgentDriverSdk,
+ BackendId,
+ BackendProbe,
+ BuiltinBackendSpecs,
+ CapabilitiesOf,
+ CreateAgentDriverSdkOptions,
+ OpenSessionInput,
+ OpenSessionResult,
+ ProbeInput,
+} from "./contract.js";
+import { createDefaultAgentDriverHost } from "./host/default-host.js";
+import {
+ assertAdapterCompatibility,
+ assertRegistrationShape,
+ createBuiltinAgentDriverRegistry,
+ type AgentDriverRegistry,
+} from "./registry.js";
+import { LogicalAgentSession } from "./controller/logical-session.js";
+import { scrubDriverError, stableErrorCode } from "./internal/errors.js";
+
+export function createAgentDriverSdk(
+ options: CreateAgentDriverSdkOptions = {},
+): AgentDriverSdk<BuiltinBackendSpecs> {
+ return createAgentDriverSdkWithRegistry({ ...options, registry: createBuiltinAgentDriverRegistry() });
+}
+
+export function createAgentDriverSdkWithRegistry<Specs>(
+ options: CreateAgentDriverSdkOptions & { readonly registry: AgentDriverRegistry<Specs> },
+): AgentDriverSdk<Specs> {
+ const host = options.host ?? createDefaultAgentDriverHost();
+ const hostReleaseTimeoutMs = options.hostReleaseTimeoutMs ?? 5_000;
+ const registry = options.registry;
+ return {
+ backendIds: registry.backendIds,
+ async probe<Id extends BackendId<Specs>>(
+ input: ProbeInput<Specs, Id>,
+ ): Promise<BackendProbe<CapabilitiesOf<Specs, Id>>> {
+ const registration = registry.get(input.backend);
+ const capabilities = registration.capabilities;
+ try {
+ assertRegistrationShape(registration);
+ const adapter = registration.createAdapter();
+ assertAdapterCompatibility(String(registration.id), registration.capabilities, adapter);
+ const command = (capabilities as { readonly commandOverride: boolean }).commandOverride
+ ? input.command
+ : undefined;
+ const result = await adapter.probe(command);
+ if (result.status === "healthy") return { status: "healthy", version: result.version, capabilities };
+ return {
+ status: "unhealthy",
+ error: {
+ category: "runtime_unavailable",
+ code: stableErrorCode(result.lastError, "probe_failed"),
+ message: `Backend ${input.backend} is unavailable`,
+ retryable: true,
+ },
+ capabilities,
+ };
+ } catch (error) {
+ const contractInvalid = error instanceof Error && (
+ error.message.startsWith("Adapter ")
+ || error.message.startsWith("Agent backend registration ")
+ );
+ return {
+ status: "unhealthy",
+ error: {
+ category: contractInvalid ? "internal" : "runtime_unavailable",
+ code: contractInvalid ? "adapter_contract_invalid" : "probe_threw",
+ message: contractInvalid
+ ? `Backend ${input.backend} adapter contract is invalid`
+ : `Backend ${input.backend} probe failed`,
+ retryable: !contractInvalid,
+ },
+ capabilities,
+ };
+ }
+ },
+ async open<Id extends BackendId<Specs>>(
+ input: OpenSessionInput<Specs, Id>,
+ ): Promise<OpenSessionResult<Specs, Id>> {
+ const registration = registry.get(input.backend);
+ let adapter;
+ try {
+ assertRegistrationShape(registration);
+ adapter = registration.createAdapter();
+ assertAdapterCompatibility(String(registration.id), registration.capabilities, adapter);
+ } catch {
+ return {
+ ok: false,
+ error: {
+ category: "internal",
+ code: "adapter_contract_invalid",
+ message: `Backend ${input.backend} adapter contract is invalid`,
+ retryable: false,
+ },
+ };
+ }
+ const prepared = await host.prepareExecution({
+ backend: input.backend,
+ launchId: input.launch.launchId,
+ workingDirectory: input.launch.workingDirectory,
+ });
+ if (!prepared.ok) return { ok: false, error: scrubDriverError(prepared.error) };
+ const session = new LogicalAgentSession<Specs, Id>(
+ input.backend,
+ input.config,
+ {
+ workingDirectory: input.launch.workingDirectory,
+ instructions: input.launch.instructions.content,
+ resumeSessionId: input.launch.resumeSessionId,
+ launchId: input.launch.launchId,
+ },
+ adapter,
+ registration.capabilities,
+ host,
+ prepared.resource,
+ hostReleaseTimeoutMs,
+ );
+ return { ok: true, session, capabilities: registration.capabilities };
+ },
+ };
+}
diff --git a/src/daemon/agent-driver/src/testing/adapter-fixture.ts b/src/daemon/agent-driver/src/testing/adapter-fixture.ts
new file mode 100644
index 000000000..890e896e2
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/adapter-fixture.ts
@@ -0,0 +1,38 @@
+import type { BuiltinBackendId, PreparedExecutionResource } from "../contract.js";
+import type { AdapterLaunchContext } from "../internal/adapter.js";
+
+export function fakePrepared(
+ overrides: Partial<PreparedExecutionResource["environmentLayers"]> = {},
+): PreparedExecutionResource {
+ return {
+ environmentLayers: {
+ base: {},
+ hostStatic: {},
+ identityProtected: {},
+ platformProtected: {},
+ runtimeProtected: {},
+ networkProtected: {},
+ credentialSensitive: {},
+ ...overrides,
+ },
+ release: async () => {},
+ };
+}
+
+export function fakeLaunchContext(
+ backend: BuiltinBackendId,
+ workingDirectory: string,
+ overrides: Partial<AdapterLaunchContext> = {},
+): AdapterLaunchContext {
+ return {
+ backend,
+ agentId: "agent_1",
+ launchId: "launch_1",
+ workingDirectory,
+ standingPrompt: "",
+ prompt: "",
+ prepared: fakePrepared(),
+ config: {},
+ ...overrides,
+ };
+}
diff --git a/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts
new file mode 100644
index 000000000..87843d9aa
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from "vitest";
+import type { AdapterEvent } from "../internal/adapter.js";
+import { createBuiltinAgentDriverRegistry } from "../registry.js";
+import { mapPiSdkEvent } from "../adapters/pi/index.js";
+import { runAgentBackendAdapterConformance } from "./conformance.js";
+
+const line = (value: unknown): string => JSON.stringify(value);
+
+describe("builtin adapter protocol conformance", () => {
+ const registry = createBuiltinAgentDriverRegistry();
+
+ it("locks the exact built-in lifetime, transport, delivery, and terminal-owner matrix", () => {
+ const expected = {
+ claude: ["session", "stdio_stream", "claude.stream-json.v1", "safe_boundary_queue", "vendor_message"],
+ codex: ["session", "stdio_rpc", "codex.app-server.v1", "safe_boundary_queue", "transport_request"],
+ cursor: ["session", "stdio_rpc", "cursor.acp.v1", "next_turn_queue", "transport_request"],
+ opencode: ["session", "http_sse", "opencode.v2.service.1.17.20", "steer", "transport_request"],
+ pi: ["session", "in_process_sdk", "pi_sdk", "steer", "prompt_invocation"],
+ } as const;
+ const actual = Object.fromEntries(registry.backendIds.map((backend) => {
+ const registration = registry.get(backend);
+ const execution = registration.createAdapter().execution;
+ return [backend, [
+ execution.lifetime,
+ execution.transport.kind,
+ execution.transport.protocol,
+ registration.capabilities.midTurnDelivery,
+ execution.terminalOwnership,
+ ]];
+ }));
+ expect(actual).toEqual(expected);
+ });
+
+ it("runs the real Claude adapter through the shared normalized-event contract", () => {
+ const events = runAgentBackendAdapterConformance(registry.get("claude"), {
+ exercise(adapter) {
+ const receipt = adapter.beginTurn?.();
+ const rootUuid = receipt?.slice("claude:".length);
+ return [
+ ...adapter.normalizeLine(line({ type: "system", subtype: "init", session_id: "claude-root" })),
+ ...adapter.normalizeLine(line({
+ type: "user",
+ isReplay: true,
+ uuid: rootUuid,
+ message: { role: "user", content: [{ type: "text", text: "prompt" }] },
+ })),
+ ...adapter.normalizeLine(line({ type: "assistant", message: { content: [
+ { type: "thinking", thinking: "plan" },
+ { type: "tool_use", name: "Read", input: { path: "x" } },
+ ] } })),
+ ...adapter.normalizeLine(line({ type: "user", message: { content: [{ type: "tool_result" }] } })),
+ ...adapter.normalizeLine(line({ type: "assistant", message: { content: [{ type: "text", text: "done" }] } })),
+ ...adapter.normalizeLine(line({
+ type: "result",
+ subtype: "success",
+ session_id: "claude-root",
+ user_message_uuid: rootUuid,
+ })),
+ ];
+ },
+ expectedEventKinds: ["session_init", "thinking", "tool_call", "tool_output", "text", "turn_end"],
+ });
+ expect(events.at(-1)).toMatchObject({ kind: "turn_end", sessionId: "claude-root", turnOwner: expect.stringMatching(/^claude:/) });
+ });
+
+ it("runs the real Codex adapter and rejects child completion/output in the shared contract", () => {
+ const events = runAgentBackendAdapterConformance(registry.get("codex"), {
+ exercise(adapter) {
+ const rootThread = "codex-root";
+ const rootTurn = "root-turn";
+ return [
+ ...adapter.normalizeLine(line({ jsonrpc: "2.0", id: 2, result: { thread: { id: rootThread } } })),
+ ...adapter.normalizeLine(line({ jsonrpc: "2.0", method: "turn/started", params: { threadId: rootThread, turn: { id: rootTurn, status: "inProgress" } } })),
+ ...adapter.normalizeLine(line({ jsonrpc: "2.0", method: "turn/completed", params: { threadId: "child-thread", turn: { id: "child-turn", status: "completed" } } })),
+ ...adapter.normalizeLine(line({ jsonrpc: "2.0", method: "item/agentMessage/delta", params: { threadId: "child-thread", delta: "must not leak" } })),
+ ...adapter.normalizeLine(line({ jsonrpc: "2.0", method: "item/started", params: { threadId: rootThread, turnId: rootTurn, item: { type: "commandExecution" } } })),
+ ...adapter.normalizeLine(line({ jsonrpc: "2.0", method: "item/completed", params: { threadId: rootThread, turnId: rootTurn, item: { type: "commandExecution" } } })),
+ ...adapter.normalizeLine(line({ jsonrpc: "2.0", method: "turn/completed", params: { threadId: rootThread, turn: { id: rootTurn, status: "completed" } } })),
+ ];
+ },
+ expectedEventKinds: ["session_init", "turn_owner", "thinking", "tool_call", "tool_output", "turn_end"],
+ });
+ expect(JSON.stringify(events)).not.toContain("must not leak");
+ });
+
+ it("declares the real Cursor adapter as a lane-owned persistent ACP transport", () => {
+ const adapter = registry.get("cursor").createAdapter();
+ expect(adapter.execution).toEqual({
+ lifetime: "session",
+ transport: { kind: "stdio_rpc", protocol: "cursor.acp.v1" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ });
+ expect("normalizeLine" in adapter).toBe(false);
+ });
+
+ it("declares the real OpenCode adapter as a lane-owned persistent v2 service", () => {
+ const adapter = registry.get("opencode").createAdapter();
+ expect(adapter.execution).toEqual({
+ lifetime: "session",
+ transport: { kind: "http_sse", protocol: "opencode.v2.service.1.17.20" },
+ wakeStart: "immediate",
+ terminalOwnership: "transport_request",
+ });
+ expect("normalizeLine" in adapter).toBe(false);
+ });
+
+ it("runs the real Pi adapter registration and SDK mapper through the shared normalized-event contract", () => {
+ runAgentBackendAdapterConformance(registry.get("pi"), {
+ exercise(adapter) {
+ expect(adapter.execution).toEqual({
+ lifetime: "session",
+ transport: { kind: "in_process_sdk", protocol: "pi_sdk" },
+ wakeStart: "immediate",
+ terminalOwnership: "prompt_invocation",
+ });
+ const state = { sawTextDelta: false };
+ const vendorEvents = [
+ { type: "message_update", delta: { type: "thinking_delta", delta: "plan" } },
+ { type: "tool_execution_start", toolName: "read", args: {} },
+ { type: "tool_execution_end", toolName: "read" },
+ { type: "message_update", delta: { type: "text_delta", delta: "done" } },
+ { type: "agent_end" },
+ ];
+ return vendorEvents.flatMap((event) => mapPiSdkEvent(event, "pi-root", state)) as AdapterEvent[];
+ },
+ expectedEventKinds: ["thinking", "tool_call", "tool_output", "text"],
+ terminalSource: "transport_invocation",
+ });
+ });
+});
diff --git a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts
new file mode 100644
index 000000000..ddfdf6ab1
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts
@@ -0,0 +1,1350 @@
+import { EventEmitter } from "node:events";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { PassThrough } from "node:stream";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type {
+ AgentEvent,
+ BuiltinBackendId,
+ BuiltinBackendSpecs,
+ ConfigOf,
+} from "../contract.js";
+import type {
+ AdapterEvent,
+ AdapterLaunchContext,
+ LaneAdmission,
+ LaneInterruptInput,
+ LaneSendInput,
+ LaneStartInput,
+ LaneStopInput,
+ RuntimeLane,
+ RuntimeLaneEventMap,
+ SpawnedProcessHandle,
+ VendorSessionHandle,
+} from "../internal/adapter.js";
+import { ClaudeDriver } from "../adapters/claude/index.js";
+import { CodexDriver } from "../adapters/codex/index.js";
+import { CursorDriver } from "../adapters/cursor/index.js";
+import { CursorAcpLane } from "../adapters/cursor/acp-lane.js";
+import { OpenCodeDriver } from "../adapters/opencode/index.js";
+import { PiDriver } from "../adapters/pi/index.js";
+import { ProcessLane } from "../controller/process-host.js";
+import { SdkLane } from "../controller/sdk-host.js";
+import { createFakeAgentDriverHost } from "./fake-host.js";
+import { capabilitiesFor, createAgentDriverRegistry, createBuiltinAgentDriverRegistry } from "../registry.js";
+import { createAgentDriverSdkWithRegistry } from "../sdk.js";
+
+const configs: { [Id in BuiltinBackendId]: ConfigOf<BuiltinBackendSpecs, Id> } = {
+ claude: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default" },
+ codex: { model: { kind: "default" }, mode: "default" },
+ cursor: { model: { kind: "default" } },
+ opencode: { model: { kind: "default" } },
+ pi: { model: { kind: "default" }, provider: { kind: "default" } },
+};
+
+type HarnessProcess = SpawnedProcessHandle & {
+ stdout: PassThrough;
+ stderr: PassThrough;
+ stdin: PassThrough;
+ finish(code?: number | null, signal?: NodeJS.Signals | null): void;
+};
+
+interface VendorHarness {
+ readonly contexts: AdapterLaunchContext[];
+ readonly processes: HarnessProcess[];
+ readonly lanes: SdkLane[];
+ readonly openCodeLanes: HarnessRuntimeLane[];
+ readonly handles: Array<VendorSessionHandle & { isStreaming: boolean }>;
+ readonly claudeInputUuids: readonly string[];
+ readonly stdinMessages: readonly Record<string, unknown>[];
+ sessionReady(turn: number): void;
+ completeTurn(turn: number): void;
+ duplicateTurn(turn: number, overrides?: Record<string, unknown>): void;
+ completeTurnWithTail(turn: number, tail: readonly unknown[], sameChunk: boolean): void;
+ emitProvider(event: unknown): void;
+ replayClaudeInput(index: number): void;
+ resultForClaudeInput(index: number, overrides?: Record<string, unknown>): void;
+}
+
+class HarnessRuntimeLane implements RuntimeLane {
+ private readonly events = new EventEmitter();
+ currentSessionId: string | null = "opencode-resumed";
+ rootReceipt: string | undefined;
+
+ on<K extends keyof RuntimeLaneEventMap>(event: K, listener: (value: RuntimeLaneEventMap[K]) => void): void {
+ this.events.on(event, listener);
+ }
+
+ start(input: LaneStartInput): Promise<LaneAdmission> {
+ this.rootReceipt = input.terminalOwner ?? "msg_opencode_root";
+ return Promise.resolve({ ok: true, acceptedAs: "prompt", receipt: this.rootReceipt });
+ }
+
+ send(input: LaneSendInput): Promise<LaneAdmission> {
+ if (input.mode === "idle") this.rootReceipt = input.terminalOwner ?? "msg_opencode_idle";
+ return Promise.resolve({
+ ok: true,
+ acceptedAs: input.mode === "busy" ? "steer" : "prompt",
+ receipt: input.mode === "busy" ? "msg_opencode_steer" : this.rootReceipt!,
+ });
+ }
+
+ interrupt(_input: LaneInterruptInput): Promise<boolean> {
+ return Promise.resolve(true);
+ }
+
+ stop(_input: LaneStopInput): Promise<void> {
+ return Promise.resolve();
+ }
+
+ emit(event: AdapterEvent): void {
+ this.events.emit("runtime_event", event);
+ }
+
+ reportUnexpectedExit(code = 17, signal: string | null = null): void {
+ this.events.emit("exit", { code, signal, reason: "runtime_exit" } satisfies RuntimeLaneEventMap["exit"]);
+ }
+}
+
+const workingDirectories: string[] = [];
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const directory of workingDirectories.splice(0)) rmSync(directory, { recursive: true, force: true });
+});
+
+function fakeProcess(): HarnessProcess {
+ const proc = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ stdin: new PassThrough(),
+ pid: undefined,
+ exitCode: null as number | null,
+ signalCode: null as NodeJS.Signals | null,
+ kill: vi.fn(() => true),
+ finish(code: number | null = 0, signal: NodeJS.Signals | null = null) {
+ proc.exitCode = code;
+ proc.signalCode = signal;
+ proc.emit("exit", code, signal);
+ },
+ });
+ return proc as unknown as HarnessProcess;
+}
+
+function installVendorHarness(backend: BuiltinBackendId): VendorHarness {
+ const contexts: AdapterLaunchContext[] = [];
+ const processes: HarnessProcess[] = [];
+ const lanes: SdkLane[] = [];
+ const openCodeLanes: HarnessRuntimeLane[] = [];
+ const handles: Array<VendorSessionHandle & { isStreaming: boolean }> = [];
+ const piPromptResolutions: Array<() => void> = [];
+ const claudeTurnUuids: string[] = [];
+ const claudeInputUuids: string[] = [];
+ const stdinMessages: Record<string, unknown>[] = [];
+ let claudeAckCursor = 0;
+ if (backend === "pi") {
+ vi.spyOn(PiDriver.prototype, "openLane").mockImplementation(async (ctx) => {
+ contexts.push(ctx);
+ const handle = {
+ isStreaming: false,
+ prompt: vi.fn(() => new Promise<void>((resolve) => { piPromptResolutions.push(resolve); })),
+ steer: vi.fn(async () => {}),
+ abort: vi.fn(async () => {}),
+ dispose: vi.fn(async () => {}),
+ };
+ handles.push(handle);
+ const lane = new SdkLane(handle, "pi-resumed", { terminalOnPromptSettled: true });
+ lanes.push(lane);
+ return lane;
+ });
+ } else if (backend === "opencode") {
+ vi.spyOn(OpenCodeDriver.prototype, "openLane").mockImplementation(async (ctx) => {
+ contexts.push(ctx);
+ const lane = new HarnessRuntimeLane();
+ openCodeLanes.push(lane);
+ return lane;
+ });
+ } else {
+ const classes = { claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver };
+ if (backend === "claude") {
+ const beginTurn = ClaudeDriver.prototype.beginTurn;
+ vi.spyOn(ClaudeDriver.prototype, "beginTurn").mockImplementation(function (this: ClaudeDriver) {
+ const receipt = beginTurn.call(this);
+ const uuid = receipt.slice("claude:".length);
+ claudeTurnUuids.push(uuid);
+ claudeInputUuids.push(uuid);
+ return receipt;
+ });
+ const encodeMessage = ClaudeDriver.prototype.encodeMessage;
+ vi.spyOn(ClaudeDriver.prototype, "encodeMessage").mockImplementation(function (
+ this: ClaudeDriver,
+ text,
+ sessionId,
+ opts,
+ ) {
+ const encoded = encodeMessage.call(this, text, sessionId, opts);
+ if (opts?.mode === "busy") claudeInputUuids.push(JSON.parse(encoded).uuid);
+ return encoded;
+ });
+ }
+ vi.spyOn(classes[backend].prototype, "spawn").mockImplementation(async (ctx) => {
+ contexts.push(ctx as AdapterLaunchContext);
+ const process = fakeProcess();
+ let stdinBuffer = "";
+ process.stdin.on("data", (chunk) => {
+ stdinBuffer += chunk.toString();
+ const lines = stdinBuffer.split("\n");
+ stdinBuffer = lines.pop() ?? "";
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ const message = JSON.parse(line) as Record<string, unknown>;
+ stdinMessages.push(message);
+ if (backend !== "cursor") continue;
+ const respond = (result: unknown) => process.stdout.write(`${JSON.stringify({
+ jsonrpc: "2.0",
+ id: message.id,
+ result,
+ })}\n`);
+ if (message.method === "initialize") {
+ respond({
+ protocolVersion: 1,
+ agentCapabilities: { loadSession: true },
+ authMethods: [{ id: "cursor_login", name: "Cursor Login" }],
+ });
+ } else if (message.method === "authenticate") {
+ respond({});
+ } else if (message.method === "session/load") {
+ const params = message.params as { sessionId?: string } | undefined;
+ respond({ sessionId: params?.sessionId ?? "cursor-resumed", configOptions: [] });
+ } else if (message.method === "session/new") {
+ respond({ sessionId: "cursor-resumed", configOptions: [] });
+ }
+ }
+ });
+ processes.push(process);
+ return { process };
+ });
+ }
+
+ const write = (value: unknown, index = processes.length - 1) => {
+ processes[index]!.stdout.write(`${JSON.stringify(value)}\n`);
+ };
+ const acknowledgeClaudeInputs = () => {
+ for (const uuid of claudeInputUuids.slice(claudeAckCursor)) {
+ write({
+ type: "user",
+ isReplay: true,
+ uuid,
+ session_id: "claude-resumed",
+ message: { role: "user", content: [{ type: "text", text: "ack" }] },
+ });
+ }
+ claudeAckCursor = claudeInputUuids.length;
+ };
+ const claudeTerminal = (turn: number, overrides: Record<string, unknown> = {}) => ({
+ type: "result",
+ subtype: "success",
+ session_id: "claude-resumed",
+ user_message_uuid: claudeTurnUuids[turn - 1],
+ duration_ms: turn,
+ ...overrides,
+ });
+ return {
+ contexts,
+ processes,
+ lanes,
+ openCodeLanes,
+ handles,
+ claudeInputUuids,
+ stdinMessages,
+ sessionReady(turn) {
+ switch (backend) {
+ case "claude":
+ write({ type: "system", subtype: "init", session_id: "claude-resumed" });
+ break;
+ case "codex":
+ if (turn === 1) write({ jsonrpc: "2.0", id: 2, result: { thread: { id: "codex-resumed" } } });
+ write({ jsonrpc: "2.0", method: "turn/started", params: {
+ threadId: "codex-resumed", turn: { id: `codex-turn-${turn}`, status: "inProgress" },
+ } });
+ break;
+ case "cursor":
+ break;
+ case "opencode":
+ openCodeLanes[0]!.emit({ kind: "thinking", text: `turn-${turn}` });
+ break;
+ case "pi":
+ handles[0]!.isStreaming = true;
+ lanes[0]!.emitEvents([{ kind: "thinking", text: `turn-${turn}` }]);
+ break;
+ }
+ },
+ completeTurn(turn) {
+ switch (backend) {
+ case "claude":
+ acknowledgeClaudeInputs();
+ write(claudeTerminal(turn));
+ break;
+ case "codex":
+ write({ jsonrpc: "2.0", method: "turn/completed", params: {
+ threadId: "codex-resumed", turn: { id: `codex-turn-${turn}`, status: "completed" },
+ } });
+ break;
+ case "cursor":
+ {
+ const prompts = stdinMessages.filter((message) => message.method === "session/prompt");
+ const prompt = prompts[turn - 1]!;
+ write({ jsonrpc: "2.0", id: prompt.id, result: { stopReason: "end_turn" } });
+ }
+ break;
+ case "opencode":
+ openCodeLanes[0]!.emit({
+ kind: "turn_end",
+ sessionId: "opencode-resumed",
+ turnOwner: openCodeLanes[0]!.rootReceipt,
+ });
+ break;
+ case "pi":
+ handles[0]!.isStreaming = false;
+ piPromptResolutions[turn - 1]!();
+ break;
+ }
+ },
+ duplicateTurn(turn, overrides = {}) {
+ switch (backend) {
+ case "claude":
+ write(claudeTerminal(turn, overrides));
+ break;
+ case "codex":
+ write({ jsonrpc: "2.0", method: "turn/completed", params: {
+ threadId: "codex-resumed", turn: { id: `codex-turn-${turn}`, status: "completed" },
+ } });
+ break;
+ case "cursor": {
+ const prompts = stdinMessages.filter((message) => message.method === "session/prompt");
+ const prompt = prompts[turn - 1]!;
+ write({ jsonrpc: "2.0", id: prompt.id, result: { stopReason: "end_turn", ...overrides } });
+ break;
+ }
+ case "opencode":
+ openCodeLanes[0]!.emit({
+ kind: "turn_end",
+ sessionId: "opencode-resumed",
+ turnOwner: openCodeLanes[0]!.rootReceipt,
+ });
+ break;
+ case "pi":
+ throw new Error("pi terminals are owned by prompt promise settlement, not vendor event payloads");
+ }
+ },
+ completeTurnWithTail(turn, tail, sameChunk) {
+ if (backend !== "claude") throw new Error("terminal tail fixture is Claude-specific");
+ acknowledgeClaudeInputs();
+ const events = [claudeTerminal(turn), ...tail];
+ if (sameChunk) {
+ processes[0]!.stdout.write(`${events.map((event) => JSON.stringify(event)).join("\n")}\n`);
+ } else {
+ for (const event of events) write(event, 0);
+ }
+ },
+ emitProvider(event) {
+ write(event);
+ },
+ replayClaudeInput(index) {
+ if (backend !== "claude") throw new Error("replay acknowledgements are Claude-specific");
+ const uuid = claudeInputUuids[index];
+ if (!uuid) throw new Error(`missing Claude input UUID at index ${index}`);
+ write({
+ type: "user",
+ isReplay: true,
+ uuid,
+ session_id: "claude-resumed",
+ message: { role: "user", content: [{ type: "text", text: "ack" }] },
+ });
+ },
+ resultForClaudeInput(index, overrides = {}) {
+ if (backend !== "claude") throw new Error("input-owned results are Claude-specific");
+ const uuid = claudeInputUuids[index];
+ if (!uuid) throw new Error(`missing Claude input UUID at index ${index}`);
+ write({
+ type: "result",
+ subtype: "success",
+ session_id: "claude-resumed",
+ user_message_uuid: uuid,
+ ...overrides,
+ });
+ },
+ };
+}
+
+async function settle(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+async function settlePromptAdmission<T>(
+ backend: BuiltinBackendId,
+ harness: VendorHarness,
+ turn: number,
+ pending: Promise<T>,
+): Promise<T> {
+ if (backend === "codex") {
+ await vi.waitFor(() => expect(harness.processes).toHaveLength(1));
+ harness.sessionReady(turn);
+ }
+ return pending;
+}
+
+async function runPublicSessionLifecycle(backend: BuiltinBackendId): Promise<void> {
+ const harness = installVendorHarness(backend);
+ const host = createFakeAgentDriverHost({
+ environmentLayers: {
+ base: { CONFORMANCE_BASE: backend },
+ hostStatic: {}, identityProtected: {}, platformProtected: {}, runtimeProtected: {},
+ networkProtected: {}, credentialSensitive: { CONFORMANCE_SECRET: "injected" },
+ },
+ });
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry(), hostReleaseTimeoutMs: 50 });
+ const workingDirectory = mkdtempSync(join(tmpdir(), `agent-driver-${backend}-`));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs[backend] as never,
+ launch: {
+ workingDirectory,
+ instructions: { format: "markdown", content: "Conformance instructions" },
+ resumeSessionId: `${backend}-resume-input`,
+ launchId: `${backend}-public-conformance`,
+ },
+ });
+ expect(opened.ok).toBe(true);
+ if (!opened.ok) return;
+ const session = opened.session;
+ const events: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ const collecting = (async () => { for await (const event of session.events) events.push(event as never); })();
+
+ expect(await session.send({ id: "early", kind: "user", text: "early" })).toMatchObject({ status: "rejected", reason: "not_started" });
+ const first = session.start({ id: "first", kind: "user", text: "first" });
+ expect(await settlePromptAdmission(backend, harness, 1, first)).toMatchObject({ status: "accepted" });
+ if (backend !== "codex") harness.sessionReady(1);
+ await settle();
+ expect(harness.contexts[0]!.config.sessionId).toBe(`${backend}-resume-input`);
+ expect(harness.contexts[0]!.prepared.environmentLayers).toMatchObject({
+ base: { CONFORMANCE_BASE: backend },
+ credentialSensitive: { CONFORMANCE_SECRET: "injected" },
+ });
+
+ const busy = await session.send({ id: "busy", kind: "user", text: "busy" });
+ expect(busy.status).toBe(backend === "pi" || backend === "opencode" ? "accepted" : "queued");
+ const interrupted = await session.interrupt({ requestId: "interrupt-1", reason: "conformance" });
+ expect(interrupted.status).toBe("accepted");
+ harness.completeTurn(1);
+ await settle();
+
+ if (backend === "cursor") {
+ await vi.waitFor(() => {
+ expect(harness.stdinMessages.filter((message) => message.method === "session/prompt")).toHaveLength(2);
+ });
+ harness.completeTurn(2);
+ await settle();
+ const reuse = session.send({ id: "reuse", kind: "user", text: "reuse" });
+ expect(await settlePromptAdmission(backend, harness, 3, reuse)).toMatchObject({ status: "accepted" });
+ harness.sessionReady(3);
+ await settle();
+ harness.completeTurn(3);
+ } else if (backend === "pi" || backend === "claude" || backend === "codex" || backend === "opencode") {
+ const reuse = session.send({ id: "reuse", kind: "user", text: "reuse" });
+ expect(await settlePromptAdmission(backend, harness, 2, reuse)).toMatchObject({ status: "accepted" });
+ if (backend === "pi") harness.handles[0]!.isStreaming = true;
+ }
+ if (backend !== "cursor") {
+ if (backend !== "codex") harness.sessionReady(2);
+ await settle();
+ harness.completeTurn(2);
+ await settle();
+ }
+
+ const stopping = session.stop({ reason: "shutdown", forceAfterMs: 25 });
+ if (backend === "claude") harness.processes[0]!.finish();
+ expect(await stopping).toMatchObject({ status: "accepted" });
+ const closed = await session.closed;
+ await collecting;
+ expect(closed.outcome).toBe("stopped");
+ expect(host.releases).toHaveLength(1);
+ expect(events.at(-1)?.type).toBe("session_closed");
+ expect(events.filter((event) => event.type === "turn_completed").map((event) => event.type === "turn_completed" && event.result.outcome)).toContain("interrupted");
+ expect(events.filter((event) => event.type === "command_accepted" && event.commandId === "busy")).toHaveLength(1);
+}
+
+async function openRegisteredHarness(backend: BuiltinBackendId, label: string) {
+ const harness = installVendorHarness(backend);
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry(), hostReleaseTimeoutMs: 50 });
+ const workingDirectory = mkdtempSync(join(tmpdir(), `agent-driver-${label}-${backend}-`));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs[backend] as never,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: `${label}-${backend}` },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event as never); })();
+ return { session: opened.session, harness, host, events, collecting };
+}
+
+async function stopRegisteredHarness(
+ backend: BuiltinBackendId,
+ fixture: Awaited<ReturnType<typeof openRegisteredHarness>>,
+): Promise<void> {
+ const stopping = fixture.session.stop({ reason: "shutdown", forceAfterMs: 25 });
+ if (backend === "claude") fixture.harness.processes[0]?.finish();
+ await stopping;
+ await fixture.session.closed;
+ await fixture.collecting;
+}
+
+function emitStaleTerminal(backend: BuiltinBackendId, harness: VendorHarness): void {
+ if (backend === "opencode") {
+ harness.openCodeLanes[0]!.emit({
+ kind: "turn_end",
+ sessionId: "opencode-resumed",
+ turnOwner: "msg_opencode_root",
+ });
+ return;
+ }
+ if (backend === "pi") {
+ harness.lanes[0]!.emitEvents([{ kind: "turn_end", sessionId: "pi-resumed", turnOwner: "pi-stale" }]);
+ return;
+ }
+ harness.duplicateTurn(1);
+}
+
+describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(
+ "%s shared persistent stress conformance",
+ (backend) => {
+ it("runs ten sequential public turns through one physical open", async () => {
+ const fixture = await openRegisteredHarness(backend, "shared-ten-turn");
+ for (let turn = 1; turn <= 10; turn += 1) {
+ const pending = turn === 1
+ ? fixture.session.start({ id: `turn-${turn}`, kind: "user", text: `turn ${turn}` })
+ : fixture.session.send({ id: `turn-${turn}`, kind: "user", text: `turn ${turn}` });
+ expect(await settlePromptAdmission(backend, fixture.harness, turn, pending)).toMatchObject({ status: "accepted" });
+ if (backend !== "codex") fixture.harness.sessionReady(turn);
+ fixture.harness.completeTurn(turn);
+ await vi.waitFor(() => expect(fixture.session.snapshot().activeTurn).toBeUndefined());
+ }
+ expect(fixture.session.snapshot().diagnostics.metrics).toMatchObject({
+ physicalOpenCount: 1,
+ turnCount: 10,
+ commandAdmissionCount: 10,
+ });
+ await vi.waitFor(() => expect(fixture.events.filter((event) => event.type === "turn_completed")).toHaveLength(10));
+ await stopRegisteredHarness(backend, fixture);
+ });
+
+ it("settles a ten-command busy/terminal/idle burst exactly once in FIFO order", async () => {
+ const fixture = await openRegisteredHarness(backend, "shared-high-frequency");
+ const ids = Array.from({ length: 10 }, (_, index) => `command-${index}`);
+ const first = fixture.session.start({ id: ids[0]!, kind: "user", text: ids[0]! });
+ await settlePromptAdmission(backend, fixture.harness, 1, first);
+ if (backend !== "codex") fixture.harness.sessionReady(1);
+
+ const busy = ids.slice(1, 6).map((id) => fixture.session.send({ id, kind: "user", text: id }));
+ await Promise.all(busy);
+ fixture.harness.completeTurn(1);
+ await settle();
+
+ const idleBurst = ids.slice(6).map((id) => fixture.session.send({ id, kind: "user", text: id }));
+ if (backend === "codex") {
+ await vi.waitFor(() => expect(fixture.session.snapshot().diagnostics.deliveryPhase).toBe("admission_wait"));
+ fixture.harness.sessionReady(2);
+ }
+ await Promise.all(idleBurst);
+ if (backend !== "codex" && backend !== "cursor") fixture.harness.sessionReady(2);
+ let turn = 2;
+ let staleTerminalEmitted = false;
+ let completedTurnId: string | undefined;
+ while (
+ fixture.session.snapshot().diagnostics.metrics.commandAdmissionCount < ids.length
+ || fixture.session.snapshot().activeTurn
+ ) {
+ await vi.waitFor(() => {
+ const activeTurnId = fixture.session.snapshot().activeTurn?.turnId;
+ expect(activeTurnId).toBeDefined();
+ expect(activeTurnId).not.toBe(completedTurnId);
+ });
+ if (backend === "codex" && fixture.session.snapshot().diagnostics.deliveryPhase === "admission_wait") {
+ fixture.harness.sessionReady(turn);
+ await vi.waitFor(() => expect(fixture.session.snapshot().diagnostics.deliveryPhase).not.toBe("admission_wait"));
+ }
+ if (!staleTerminalEmitted) {
+ emitStaleTerminal(backend, fixture.harness);
+ staleTerminalEmitted = true;
+ await settle();
+ expect(fixture.session.snapshot().activeTurn).toBeDefined();
+ }
+ completedTurnId = fixture.session.snapshot().activeTurn!.turnId;
+ fixture.harness.completeTurn(turn);
+ turn += 1;
+ if (turn > 11) throw new Error(`${backend} did not drain the ten-command FIFO`);
+ await settle();
+ }
+ await vi.waitFor(() => {
+ expect(fixture.events.filter((event) => event.type === "command_accepted" || event.type === "command_failed"))
+ .toHaveLength(ids.length);
+ });
+
+ const finalEvents = fixture.events.filter((event) => event.type === "command_accepted" || event.type === "command_failed");
+ expect(finalEvents.map((event) => event.commandId)).toEqual(ids);
+ for (const id of ids) expect(finalEvents.filter((event) => event.commandId === id)).toHaveLength(1);
+ expect(fixture.session.snapshot().diagnostics.metrics).toMatchObject({
+ physicalOpenCount: 1,
+ commandAdmissionCount: 10,
+ });
+ await stopRegisteredHarness(backend, fixture);
+ });
+ },
+);
+
+describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(
+ "%s registered public-session lifecycle conformance",
+ (backend) => {
+ it("runs resume, busy admission, interrupt reuse, environment, release, and requested stop through sdk.open", async () => {
+ await runPublicSessionLifecycle(backend);
+ });
+
+ it("settles a stop racing an in-flight registered-adapter open without late acceptance", async () => {
+ const harness = installVendorHarness(backend);
+ let releaseOpen!: () => void;
+ const openGate = new Promise<void>((resolve) => { releaseOpen = resolve; });
+ const laneOwned = backend === "pi" || backend === "opencode";
+ const method = laneOwned ? "openLane" : "spawn";
+ const prototype = backend === "pi"
+ ? PiDriver.prototype
+ : backend === "opencode"
+ ? OpenCodeDriver.prototype
+ : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, opencode: OpenCodeDriver } as const)[backend].prototype;
+ const existing = (prototype as unknown as Record<string, ReturnType<typeof vi.fn>>)[method]!;
+ existing.mockImplementationOnce(async (...args: unknown[]) => {
+ await openGate;
+ if (backend === "pi") return harness.lanes[0] ?? new SdkLane({
+ isStreaming: false,
+ prompt: async () => {}, steer: async () => {}, abort: async () => {}, dispose: async () => {},
+ }, "late-pi");
+ if (backend === "opencode") return harness.openCodeLanes[0] ?? new HarnessRuntimeLane();
+ const process = fakeProcess();
+ harness.processes.push(process);
+ return { process };
+ });
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry(), hostReleaseTimeoutMs: 20 });
+ const workingDirectory = mkdtempSync(join(tmpdir(), `agent-driver-race-${backend}-`));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs[backend] as never,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: `race-${backend}` },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: string[] = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event.type); })();
+ const settlementOrder: string[] = [];
+ void opened.session.closed.then(() => { settlementOrder.push("session_closed"); });
+ const starting = opened.session.start({ id: "racing", kind: "user", text: "racing" });
+ void starting.then(() => { settlementOrder.push("start_resolved"); });
+ const stopping = opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ releaseOpen();
+ expect(await starting).toMatchObject({ status: "rejected" });
+ expect(await stopping).toMatchObject({ status: "accepted" });
+ await opened.session.closed;
+ await starting;
+ await collecting;
+ expect(settlementOrder.indexOf("session_closed")).toBeLessThan(settlementOrder.indexOf("start_resolved"));
+ expect(events.filter((type) => type === "command_failed")).toHaveLength(1);
+ expect(events).not.toContain("command_accepted");
+ expect(events.at(-1)).toBe("session_closed");
+ expect(host.releases).toHaveLength(1);
+ });
+
+ it("scrubs and releases a registered-adapter failed start", async () => {
+ installVendorHarness(backend);
+ const laneOwned = backend === "pi" || backend === "opencode";
+ const method = laneOwned ? "openLane" : "spawn";
+ const prototype = backend === "pi"
+ ? PiDriver.prototype
+ : backend === "opencode"
+ ? OpenCodeDriver.prototype
+ : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver } as const)[backend].prototype;
+ (prototype as unknown as Record<string, ReturnType<typeof vi.fn>>)[method]!.mockRejectedValueOnce(
+ new Error("apiKey=supersecret failed at /Users/Alice Smith/private key.json"),
+ );
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), `agent-driver-failed-${backend}-`));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs[backend] as never,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: `failed-${backend}` },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event as never); })();
+ expect(await opened.session.start({ id: "failed", kind: "user", text: "failed" })).toMatchObject({ status: "rejected" });
+ const closed = await opened.session.closed;
+ await collecting;
+ expect(closed.outcome).toBe("failed_to_start");
+ expect(JSON.stringify({ closed, events })).not.toMatch(/supersecret|Alice Smith|private key/);
+ expect(host.releases).toHaveLength(1);
+ expect(host.releases[0]?.reason).toBe("failed_start");
+ });
+
+ it("settles stop before start through the public session and releases exactly once", async () => {
+ installVendorHarness(backend);
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), `agent-driver-prestart-${backend}-`));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs[backend] as never,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: `prestart-${backend}` },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ expect(await opened.session.stop({ reason: "shutdown", forceAfterMs: 10 })).toMatchObject({ status: "accepted" });
+ expect((await opened.session.closed).outcome).toBe("stopped");
+ expect(host.releases).toHaveLength(1);
+ expect(await opened.session.start({ id: "late", kind: "user", text: "late" })).toMatchObject({ status: "rejected", reason: "closed" });
+ });
+
+ it("settles a physical stop rejection as forced and still releases exactly once", async () => {
+ const harness = installVendorHarness(backend);
+ const laneStop = backend === "pi"
+ ? vi.spyOn(SdkLane.prototype, "stop")
+ : backend === "cursor"
+ ? vi.spyOn(CursorAcpLane.prototype, "stop")
+ : backend === "opencode"
+ ? vi.spyOn(HarnessRuntimeLane.prototype, "stop")
+ : vi.spyOn(ProcessLane.prototype, "stop");
+ laneStop.mockRejectedValueOnce(new Error("dispose rejected at /Users/Alice/private"));
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), `agent-driver-reject-stop-${backend}-`));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs[backend] as never,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: `reject-stop-${backend}` },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ await settlePromptAdmission(
+ backend,
+ harness,
+ 1,
+ opened.session.start({ id: "reject-stop", kind: "user", text: "start" }),
+ );
+ const receipt = await opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ expect(receipt.status).toBe("failed");
+ expect(JSON.stringify(receipt)).not.toContain("/Users/Alice");
+ expect((await opened.session.closed).outcome).toBe("forced");
+ expect(host.releases).toHaveLength(1);
+ });
+
+ it("forces a bounded stop and releases the registered adapter when its physical lane hangs", async () => {
+ const harness = installVendorHarness(backend);
+ const laneStop = backend === "pi"
+ ? vi.spyOn(SdkLane.prototype, "stop")
+ : backend === "cursor"
+ ? vi.spyOn(CursorAcpLane.prototype, "stop")
+ : backend === "opencode"
+ ? vi.spyOn(HarnessRuntimeLane.prototype, "stop")
+ : vi.spyOn(ProcessLane.prototype, "stop");
+ laneStop.mockImplementationOnce(() => new Promise<void>(() => {}));
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), `agent-driver-force-${backend}-`));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs[backend] as never,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: `force-${backend}` },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ await settlePromptAdmission(
+ backend,
+ harness,
+ 1,
+ opened.session.start({ id: "force", kind: "user", text: "force" }),
+ );
+ expect(await opened.session.stop({ reason: "stalled", forceAfterMs: 1 })).toMatchObject({ status: "accepted" });
+ const closed = await opened.session.closed;
+ expect(closed.outcome).toBe("forced");
+ expect(host.releases).toHaveLength(1);
+ expect(host.releases[0]?.reason).toBe("requested_stop");
+ });
+
+ it("closes as crashed on an unexpected registered-backend physical exit and releases exactly once", async () => {
+ const harness = installVendorHarness(backend);
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), `agent-driver-crash-${backend}-`));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs[backend] as never,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: `crash-${backend}` },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: string[] = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event.type); })();
+ expect(await settlePromptAdmission(
+ backend,
+ harness,
+ 1,
+ opened.session.start({ id: "crash", kind: "user", text: "crash" }),
+ )).toMatchObject({ status: "accepted" });
+ if (backend === "pi") harness.lanes[0]!.reportUnexpectedExit();
+ else if (backend === "opencode") harness.openCodeLanes[0]!.reportUnexpectedExit();
+ else harness.processes[0]!.finish(17, null);
+ expect((await opened.session.closed).outcome).toBe("crashed");
+ await collecting;
+ expect(events).toContain("session_failed");
+ expect(events.at(-1)).toBe("session_closed");
+ expect(host.releases).toHaveLength(1);
+ expect(host.releases[0]?.reason).toBe("crash");
+ });
+ },
+);
+
+describe("pi registered public-session lifecycle conformance", () => {
+ it("completes a clean SDK dispose before the force timer without waiting for its deadline", async () => {
+ vi.useFakeTimers();
+ try {
+ const harness = installVendorHarness("pi");
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-clean-dispose-pi-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend: "pi",
+ config: configs.pi,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: "clean-dispose-pi" },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ await opened.session.start({ id: "clean-dispose", kind: "user", text: "clean" });
+ harness.handles[0]!.isStreaming = false;
+ await vi.advanceTimersByTimeAsync(25);
+ const stopped = opened.session.stop({ reason: "shutdown", forceAfterMs: 60_000 });
+ expect(await stopped).toMatchObject({ status: "accepted" });
+ expect((await opened.session.closed).outcome).toBe("stopped");
+ expect(harness.handles[0]!.dispose).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("codex persistent terminal ownership", () => {
+ it("keeps turn B active when turn A's terminal is duplicated after B starts", async () => {
+ const backend = "codex" as const;
+ const harness = installVendorHarness(backend);
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), `agent-driver-terminal-owner-${backend}-`));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs[backend] as never,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: `terminal-owner-${backend}` },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event as never); })();
+
+ const firstPending = opened.session.start({ id: "first", kind: "user", text: "first" });
+ const first = await settlePromptAdmission(backend, harness, 1, firstPending);
+ expect(first.status).toBe("accepted");
+ harness.completeTurn(1);
+ await settle();
+ const secondPending = opened.session.send({ id: "second", kind: "user", text: "second" });
+ const second = await settlePromptAdmission(backend, harness, 2, secondPending);
+ expect(second.status).toBe("accepted");
+ await settle();
+ harness.duplicateTurn(1);
+ await settle();
+ expect(opened.session.snapshot().activeTurn?.turnId).toBe(second.status === "accepted" ? second.turnId : "unreachable");
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1);
+ harness.completeTurn(2);
+ await settle();
+ expect(opened.session.snapshot().activeTurn).toBeUndefined();
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2);
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await collecting;
+ });
+});
+
+describe("cursor persistent ACP ownership", () => {
+ it("keeps a queued second root off the wire and fences a late first response by JSON-RPC id", async () => {
+ const harness = installVendorHarness("cursor");
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-terminal-owner-cursor-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend: "cursor",
+ config: configs.cursor,
+ launch: {
+ workingDirectory,
+ instructions: { format: "markdown", content: "" },
+ launchId: "terminal-owner-cursor",
+ },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, "cursor">> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();
+
+ expect(await opened.session.start({ id: "first", kind: "user", text: "same" }))
+ .toMatchObject({ status: "accepted" });
+ expect(harness.stdinMessages.filter((message) => message.method === "session/prompt")).toHaveLength(1);
+ expect(await opened.session.send({ id: "second", kind: "user", text: "same" }))
+ .toEqual({ status: "queued", reason: "runtime_busy", commandId: "second" });
+ expect(harness.stdinMessages.filter((message) => message.method === "session/prompt")).toHaveLength(1);
+
+ harness.completeTurn(1);
+ await vi.waitFor(() => {
+ expect(harness.stdinMessages.filter((message) => message.method === "session/prompt")).toHaveLength(2);
+ });
+ const secondTurnId = opened.session.snapshot().activeTurn?.turnId;
+ harness.duplicateTurn(1);
+ await settle();
+ expect(opened.session.snapshot().activeTurn?.turnId).toBe(secondTurnId);
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1);
+
+ harness.completeTurn(2);
+ await vi.waitFor(() => expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2));
+ expect(harness.processes).toHaveLength(1);
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await collecting;
+ });
+
+ it("keeps ten sequential public root turns on one process and one ACP session", async () => {
+ const harness = installVendorHarness("cursor");
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-ten-turn-cursor-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend: "cursor",
+ config: configs.cursor,
+ launch: {
+ workingDirectory,
+ instructions: { format: "markdown", content: "" },
+ launchId: "ten-turn-cursor",
+ },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, "cursor">> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();
+
+ for (let turn = 1; turn <= 10; turn += 1) {
+ const receipt = turn === 1
+ ? await opened.session.start({ id: `cursor-${turn}`, kind: "user", text: "same" })
+ : await opened.session.send({ id: `cursor-${turn}`, kind: "user", text: "same" });
+ expect(receipt.status).toBe("accepted");
+ harness.completeTurn(turn);
+ await vi.waitFor(() => {
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(turn);
+ });
+ }
+ expect(harness.processes).toHaveLength(1);
+ expect(harness.contexts).toHaveLength(1);
+ expect(harness.stdinMessages.filter((message) => message.method === "session/new")).toHaveLength(1);
+ expect(harness.stdinMessages.filter((message) => message.method === "session/prompt")).toHaveLength(10);
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await collecting;
+ });
+});
+
+describe("claude persistent transport ownership", () => {
+ it("accepts identical legitimate terminals while a late prior-turn duplicate stays fenced on one process", async () => {
+ const backend = "claude" as const;
+ const harness = installVendorHarness(backend);
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-terminal-owner-claude-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend,
+ config: configs.claude,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: "terminal-owner-claude" },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, "claude">> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();
+
+ const first = await opened.session.start({ id: "first", kind: "user", text: "same" });
+ expect(first.status).toBe("accepted");
+ harness.sessionReady(1);
+ harness.completeTurn(1);
+ await settle();
+ const second = await opened.session.send({ id: "second", kind: "user", text: "same" });
+ expect(second.status).toBe("accepted");
+ expect(harness.processes).toHaveLength(1);
+ harness.sessionReady(2);
+
+ for (let index = 0; index < 128; index += 1) {
+ harness.duplicateTurn(1);
+ }
+ await settle();
+ expect(opened.session.snapshot().activeTurn?.turnId).toBe(second.status === "accepted" ? second.turnId : "unreachable");
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1);
+
+ harness.completeTurn(2);
+ await settle();
+ expect(opened.session.snapshot().activeTurn).toBeUndefined();
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2);
+ expect(harness.contexts).toHaveLength(1);
+ const stopping = opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ harness.processes[0]!.finish();
+ await stopping;
+ await collecting;
+ });
+
+ it("drops stale errored-result side effects before they can poison the active turn", async () => {
+ const harness = installVendorHarness("claude");
+ const sdk = createAgentDriverSdkWithRegistry({
+ host: createFakeAgentDriverHost(),
+ registry: createBuiltinAgentDriverRegistry(),
+ });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-stale-error-claude-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend: "claude",
+ config: configs.claude,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: "stale-error-claude" },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, "claude">> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();
+
+ await opened.session.start({ id: "first", kind: "user", text: "first" });
+ harness.sessionReady(1);
+ harness.completeTurn(1);
+ await settle();
+ const second = await opened.session.send({ id: "second", kind: "user", text: "second" });
+ expect(second.status).toBe("accepted");
+ harness.sessionReady(2);
+ harness.duplicateTurn(1, {
+ is_error: true,
+ result: "stale failure",
+ usage: { input_tokens: 99, output_tokens: 99 },
+ });
+ await settle();
+ expect(opened.session.snapshot().activeTurn?.turnId).toBe(second.status === "accepted" ? second.turnId : "unreachable");
+ expect(events.filter((event) => event.type === "diagnostic")).toHaveLength(0);
+ expect(events.filter((event) => event.type === "token_usage")).toHaveLength(0);
+
+ harness.completeTurn(2);
+ await settle();
+ const completions = events.filter((event) => event.type === "turn_completed");
+ expect(completions).toHaveLength(2);
+ expect(completions.at(-1)).toMatchObject({ result: { outcome: "success" } });
+ const stopping = opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ harness.processes[0]!.finish();
+ await stopping;
+ await collecting;
+ });
+
+ it("fences a prior-turn stdout tail until the next root replay acknowledgement", async () => {
+ const harness = installVendorHarness("claude");
+ const sdk = createAgentDriverSdkWithRegistry({
+ host: createFakeAgentDriverHost(),
+ registry: createBuiltinAgentDriverRegistry(),
+ });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-cross-turn-tail-claude-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend: "claude",
+ config: configs.claude,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: "cross-turn-tail-claude" },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, "claude">> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();
+
+ await opened.session.start({ id: "first", kind: "user", text: "first" });
+ harness.sessionReady(1);
+ harness.completeTurn(1);
+ await settle();
+ expect(await opened.session.send({ id: "second", kind: "user", text: "second" }))
+ .toMatchObject({ status: "accepted" });
+
+ harness.emitProvider({ type: "assistant", message: { content: [{ type: "text", text: "LATE_A" }] } });
+ harness.emitProvider({
+ type: "assistant",
+ message: { content: [{ type: "tool_use", id: "late-tool", name: "LateTool", input: {} }] },
+ });
+ harness.emitProvider({ type: "system", subtype: "status", status: "late-progress" });
+ await settle();
+ expect(events.filter((event) => event.type === "text_delta")).toHaveLength(0);
+ expect(events.filter((event) => event.type === "tool_started")).toHaveLength(0);
+ expect(events.filter((event) => event.type === "internal_progress")).toHaveLength(0);
+
+ harness.sessionReady(2);
+ harness.replayClaudeInput(1);
+ harness.emitProvider({ type: "assistant", message: { content: [{ type: "text", text: "B_TEXT" }] } });
+ harness.emitProvider({
+ type: "assistant",
+ message: { content: [{ type: "tool_use", id: "b-tool", name: "CurrentTool", input: {} }] },
+ });
+ harness.emitProvider({
+ type: "user",
+ message: { content: [{ type: "tool_result", tool_use_id: "b-tool", content: "done" }] },
+ });
+ harness.resultForClaudeInput(1);
+ await vi.waitFor(() => {
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2);
+ });
+ expect(events.filter((event) => event.type === "text_delta")).toMatchObject([{ text: "B_TEXT" }]);
+ expect(events.filter((event) => event.type === "tool_started")).toMatchObject([{ name: "CurrentTool" }]);
+ expect(harness.processes).toHaveLength(1);
+
+ const stopping = opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ harness.processes[0]!.finish();
+ await stopping;
+ await collecting;
+ });
+
+ it.each([true, false] as const)(
+ "drops provider work after a final result (%s chunk) and starts B on the same process",
+ async (sameChunk) => {
+ const harness = installVendorHarness("claude");
+ const sdk = createAgentDriverSdkWithRegistry({
+ host: createFakeAgentDriverHost(),
+ registry: createBuiltinAgentDriverRegistry(),
+ });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-terminal-tail-claude-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend: "claude",
+ config: configs.claude,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: "terminal-tail-claude" },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, "claude">> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();
+
+ await opened.session.start({ id: "first", kind: "user", text: "first" });
+ harness.sessionReady(1);
+ harness.completeTurnWithTail(1, [
+ { type: "assistant", message: { content: [{ type: "text", text: "late text" }] } },
+ { type: "assistant", message: { content: [{ type: "tool_use", name: "LateTool", input: {} }] } },
+ { type: "system", subtype: "status", status: "late-progress" },
+ ], sameChunk);
+ await settle();
+ expect(opened.session.snapshot().activeTurn).toBeUndefined();
+ expect(events.filter((event) => event.type === "text_delta")).toHaveLength(0);
+ expect(events.filter((event) => event.type === "tool_started")).toHaveLength(0);
+ expect(events.filter((event) => event.type === "internal_progress")).toHaveLength(0);
+
+ const second = await opened.session.send({ id: "second", kind: "user", text: "second" });
+ expect(second.status).toBe("accepted");
+ expect(harness.processes).toHaveLength(1);
+ harness.sessionReady(2);
+ harness.completeTurn(2);
+ await settle();
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2);
+ const stopping = opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ harness.processes[0]!.finish();
+ await stopping;
+ await collecting;
+ },
+ );
+
+ it("delivers high-frequency FIFO steering inside one turn and one process across a follow-on provider segment", async () => {
+ const harness = installVendorHarness("claude");
+ const sdk = createAgentDriverSdkWithRegistry({
+ host: createFakeAgentDriverHost(),
+ registry: createBuiltinAgentDriverRegistry(),
+ });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-steering-claude-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend: "claude",
+ config: configs.claude,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: "steering-claude" },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, "claude">> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();
+
+ await opened.session.start({ id: "root", kind: "user", text: "root" });
+ harness.sessionReady(1);
+ harness.replayClaudeInput(0);
+ harness.emitProvider({
+ type: "assistant",
+ message: { content: [{ type: "tool_use", id: "tool-1", name: "Read", input: {} }] },
+ });
+ await settle();
+
+ const steering = Array.from({ length: 9 }, (_, index) => ({
+ id: `steer-${index + 1}`,
+ text: `steer-${index + 1}`,
+ }));
+ for (const message of steering) {
+ expect(await opened.session.send({ id: message.id, kind: "user", text: message.text }))
+ .toEqual({ status: "queued", reason: "unsafe_boundary", commandId: message.id });
+ }
+ expect(harness.stdinMessages).toHaveLength(0);
+
+ harness.emitProvider({
+ type: "user",
+ message: { content: [{ type: "tool_result", tool_use_id: "tool-1", content: "done" }] },
+ });
+ await vi.waitFor(() => expect(harness.stdinMessages).toHaveLength(9));
+ expect(harness.processes).toHaveLength(1);
+ expect(harness.stdinMessages.map((frame) => frame.priority)).toEqual(Array(9).fill("now"));
+ for (const [index, frame] of harness.stdinMessages.entries()) {
+ expect(frame).toMatchObject({
+ type: "user",
+ message: { role: "user", content: [{ type: "text", text: steering[index]!.text }] },
+ });
+ }
+ const wireUuids = harness.stdinMessages.map((frame) => frame.uuid);
+ expect(new Set(wireUuids).size).toBe(9);
+ expect(wireUuids).toEqual(harness.claudeInputUuids.slice(1));
+ await vi.waitFor(() => {
+ expect(opened.session.snapshot()).toMatchObject({
+ activeTurn: { commandIds: ["root", ...steering.map((message) => message.id)] },
+ queuedCommands: [],
+ });
+ });
+ await vi.waitFor(() => {
+ for (const message of steering) {
+ expect(events.filter((event) => event.type === "command_accepted" && event.commandId === message.id))
+ .toHaveLength(1);
+ }
+ });
+
+ harness.resultForClaudeInput(0);
+ await settle();
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(0);
+ expect(opened.session.snapshot().activeTurn).toBeDefined();
+
+ for (let index = 1; index <= steering.length; index += 1) harness.replayClaudeInput(index);
+ harness.resultForClaudeInput(1);
+ await settle();
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(0);
+ harness.resultForClaudeInput(steering.length);
+ await settle();
+ const completions = events.filter((event) => event.type === "turn_completed");
+ expect(completions).toHaveLength(1);
+ expect(completions[0]).toMatchObject({
+ commandIds: ["root", ...steering.map((message) => message.id)],
+ result: { outcome: "success" },
+ });
+ expect(harness.processes).toHaveLength(1);
+
+ const stopping = opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ harness.processes[0]!.finish();
+ await stopping;
+ await collecting;
+ });
+
+ it("keeps ten sequential turns on one stdin/stdout process", async () => {
+ const harness = installVendorHarness("claude");
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry({ host, registry: createBuiltinAgentDriverRegistry() });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-terminal-tail-claude-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend: "claude",
+ config: configs.claude,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: "terminal-tail-claude" },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, "claude">> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();
+ for (let turn = 1; turn <= 10; turn += 1) {
+ const receipt = turn === 1
+ ? await opened.session.start({ id: `message-${turn}`, kind: "user", text: `turn-${turn}` })
+ : await opened.session.send({ id: `message-${turn}`, kind: "user", text: `turn-${turn}` });
+ expect(receipt.status).toBe("accepted");
+ harness.sessionReady(turn);
+ harness.completeTurn(turn);
+ await settle();
+ }
+ expect(harness.processes).toHaveLength(1);
+ expect(harness.contexts).toHaveLength(1);
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(10);
+ const stopping = opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ harness.processes[0]!.finish();
+ await stopping;
+ await collecting;
+ });
+});
+
+it("Pi real adapter public chain owns identical turns by prompt invocation and ignores old completion duplicates", async () => {
+ let notify!: (event: unknown) => void;
+ const prompts: Array<{ resolve: () => void; promise: Promise<void> }> = [];
+ const vendor = {
+ prompt: vi.fn(() => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => { resolve = done; });
+ prompts.push({ resolve, promise });
+ return promise;
+ }),
+ steer: vi.fn(async () => {}),
+ abort: vi.fn(async () => {}),
+ dispose: vi.fn(async () => {}),
+ isStreaming: false,
+ subscribe(listener: (event: unknown) => void) { notify = listener; return () => {}; },
+ };
+ const adapter = new PiDriver(() => ({
+ buildSpawnEnv: async () => ({}),
+ createAgentSession: async () => ({ session: vendor, sessionId: "pi-terminal-owner" }),
+ } as never));
+ const registry = createAgentDriverRegistry<BuiltinBackendSpecs>([{
+ id: "pi",
+ contractVersion: 1,
+ capabilities: capabilitiesFor("pi"),
+ createAdapter: () => adapter,
+ }] as never);
+ const host = createFakeAgentDriverHost();
+ const sdk = createAgentDriverSdkWithRegistry<BuiltinBackendSpecs>({ host, registry });
+ const workingDirectory = mkdtempSync(join(tmpdir(), "agent-driver-terminal-owner-pi-"));
+ workingDirectories.push(workingDirectory);
+ const opened = await sdk.open({
+ backend: "pi",
+ config: configs.pi,
+ launch: { workingDirectory, instructions: { format: "markdown", content: "" }, launchId: "terminal-owner-pi" },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const events: Array<AgentEvent<BuiltinBackendSpecs, "pi">> = [];
+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();
+ await opened.session.start({ id: "first", kind: "user", text: "first" });
+ const firstTerminal = { type: "agent_end", messages: [] };
+ notify(firstTerminal);
+ prompts[0]!.resolve();
+ await prompts[0]!.promise;
+ await settle();
+ const second = await opened.session.send({ id: "second", kind: "user", text: "second" });
+ expect(second.status).toBe("accepted");
+ for (let index = 0; index < 128; index += 1) {
+ notify(firstTerminal);
+ prompts[0]!.resolve();
+ }
+ await settle();
+ expect(opened.session.snapshot().activeTurn?.turnId).toBe(second.status === "accepted" ? second.turnId : "unreachable");
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(1);
+ notify({ type: "agent_end", messages: [] });
+ prompts[1]!.resolve();
+ await prompts[1]!.promise;
+ await settle();
+ expect(opened.session.snapshot().activeTurn).toBeUndefined();
+ expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2);
+ await opened.session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await collecting;
+});
diff --git a/src/daemon/agent-driver/src/testing/conformance.ts b/src/daemon/agent-driver/src/testing/conformance.ts
new file mode 100644
index 000000000..e6a1c3d11
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/conformance.ts
@@ -0,0 +1,145 @@
+import type {
+ AgentSession,
+ AgentEvent,
+ BackendId,
+ DeliveryReceipt,
+ StopReceipt,
+} from "../contract.js";
+import type { BackendAdapter, AdapterEvent } from "../internal/adapter.js";
+import type { AgentBackendRegistration } from "../registry.js";
+
+type NormalizingBackendAdapter<Id extends string, Config> = BackendAdapter<Id, Config> & {
+ normalizeLine(line: string): AdapterEvent[];
+};
+
+export interface AgentDriverConformanceFixture<Specs, Id extends BackendId<Specs>> {
+ readonly session: AgentSession<Specs, Id>;
+ completeFirstTurn(): Promise<void>;
+}
+
+export interface AgentDriverConformanceResult {
+ readonly sendBeforeStart: DeliveryReceipt;
+ readonly firstStart: DeliveryReceipt;
+ readonly duplicateStart: DeliveryReceipt;
+ readonly conflictingDuplicate: DeliveryReceipt;
+ readonly secondStart: DeliveryReceipt;
+ readonly stop: StopReceipt;
+ readonly events: readonly { readonly type: string; readonly sequence: number }[];
+}
+
+interface AgentBackendAdapterConformanceFixture<Id extends string, Config> {
+ exercise(adapter: NormalizingBackendAdapter<Id, Config>): readonly AdapterEvent[];
+ readonly expectedEventKinds: readonly AdapterEvent["kind"][];
+ readonly terminalSource?: "normalized_event" | "transport_invocation";
+}
+
+/** Internal real-adapter contract runner; intentionally omitted from /testing. */
+export function runAgentBackendAdapterConformance<Specs, Id extends BackendId<Specs>>(
+ registration: AgentBackendRegistration<Specs, Id>,
+ fixture: AgentBackendAdapterConformanceFixture<Id, import("../contract.js").ConfigOf<Specs, Id>>,
+): readonly AdapterEvent[] {
+ const first = registration.createAdapter() as NormalizingBackendAdapter<
+ Id,
+ import("../contract.js").ConfigOf<Specs, Id>
+ >;
+ const second = registration.createAdapter();
+ assert(first !== second, "registry factory must return a fresh adapter instance");
+ assert(first.id === registration.id, "registration and adapter ids must match");
+ assert(
+ first.instructionDelivery.kind === "native" || first.instructionDelivery.kind === "workspace_file",
+ "adapter must declare an instruction-delivery strategy",
+ );
+ assert(
+ first.execution.lifetime === "session" || first.execution.lifetime === "turn",
+ "adapter must declare an execution strategy",
+ );
+ assert(typeof first.normalizeLine === "function", "built-in adapter must expose its internal event normalizer");
+
+ const events = fixture.exercise(first);
+ assert(
+ JSON.stringify(events.map((event) => event.kind)) === JSON.stringify(fixture.expectedEventKinds),
+ `normalized event order for ${registration.id} did not match the contract fixture`,
+ );
+ const terminalCount = events.filter((event) => event.kind === "turn_end").length;
+ if (fixture.terminalSource === "transport_invocation") {
+ assert(
+ first.execution.terminalOwnership === "prompt_invocation",
+ "transport-owned terminal requires prompt-invocation ownership",
+ );
+ assert(terminalCount === 0, "transport-owned terminal must not also come from an unowned vendor event payload");
+ } else {
+ assert(terminalCount === 1, "fixture must produce exactly one turn_end");
+ }
+ return events;
+}
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(`Agent-driver conformance failed: ${message}`);
+}
+
+/**
+ * Reusable black-box receipt/idempotency suite for repository adapter
+ * implementations.
+ * The fixture supplies only a public session and a deterministic way to finish
+ * its first turn; the suite does not reach into adapter internals.
+ */
+export async function runAgentDriverConformance<Specs, Id extends BackendId<Specs>>(
+ create: () => Promise<AgentDriverConformanceFixture<Specs, Id>> | AgentDriverConformanceFixture<Specs, Id>,
+): Promise<AgentDriverConformanceResult> {
+ const fixture = await create();
+ const { session } = fixture;
+ const observed: AgentEvent<Specs, Id>[] = [];
+ const collecting = (async () => {
+ for await (const event of session.events) observed.push(event);
+ })();
+ const sendBeforeStart = await session.send({ id: "conformance-early", kind: "user", text: "early" });
+ assert(sendBeforeStart.status === "rejected" && sendBeforeStart.reason === "not_started", "send before start must reject");
+
+ const firstPromise = session.start({ id: "conformance-first", kind: "user", text: "hello" });
+ const duplicatePromise = session.start({ id: "conformance-first", kind: "user", text: "hello" });
+ const [firstStart, duplicateStart] = await Promise.all([firstPromise, duplicatePromise]);
+ assert(JSON.stringify(firstStart) === JSON.stringify(duplicateStart), "byte-identical duplicate must replay its receipt");
+ assert(firstStart.status === "accepted" || firstStart.status === "queued", "first start must be admitted");
+
+ const conflictingDuplicate = await session.start({ id: "conformance-first", kind: "user", text: "different" });
+ assert(conflictingDuplicate.status === "rejected" && conflictingDuplicate.reason === "duplicate_conflict", "conflicting duplicate must reject");
+ const secondStart = await session.start({ id: "conformance-second", kind: "user", text: "second" });
+ assert(secondStart.status === "rejected" && secondStart.reason === "already_started", "second start must reject");
+
+ await fixture.completeFirstTurn();
+ const stop = await session.stop({ reason: "shutdown", forceAfterMs: 100 });
+ assert(stop.status === "accepted" || stop.status === "closed", "stop must settle truthfully");
+ await session.closed;
+ await collecting;
+
+ const coreObserved = observed as unknown as Array<{
+ readonly type: string;
+ readonly sequence: number;
+ readonly commandId?: string;
+ }>;
+ const firstCommandId = "conformance-first";
+ const commandOutcomes = coreObserved.filter((event) =>
+ ["command_accepted", "command_failed"].includes(event.type)
+ && event.commandId === firstCommandId);
+ assert(commandOutcomes.length === 1, "first command must have exactly one final admission outcome");
+ const acceptedIndex = coreObserved.findIndex((event) => event.type === "command_accepted" && event.commandId === firstCommandId);
+ const startedIndex = coreObserved.findIndex((event) => event.type === "turn_started");
+ const completedIndex = coreObserved.findIndex((event) => event.type === "turn_completed");
+ const closedIndex = coreObserved.findIndex((event) => event.type === "session_closed");
+ assert(acceptedIndex >= 0 && startedIndex > acceptedIndex, "command acceptance must precede turn_started");
+ assert(completedIndex > startedIndex, "turn_completed must follow turn_started");
+ assert(closedIndex > completedIndex && closedIndex === coreObserved.length - 1, "session_closed must be the final event");
+ for (let index = 0; index < coreObserved.length; index += 1) {
+ assert(coreObserved[index]!.sequence === index + 1, "event sequence must be contiguous and monotonic");
+ }
+
+ return {
+ sendBeforeStart,
+ firstStart,
+ duplicateStart,
+ conflictingDuplicate,
+ secondStart,
+ stop,
+ events: coreObserved,
+ };
+}
diff --git a/src/daemon/agent-driver/src/testing/fake-host.ts b/src/daemon/agent-driver/src/testing/fake-host.ts
new file mode 100644
index 000000000..05af9a88b
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/fake-host.ts
@@ -0,0 +1,39 @@
+import type {
+ AgentDriverHost,
+ PreparedExecutionResource,
+ RawOutputEvent,
+} from "../contract.js";
+
+export interface FakeAgentDriverHost extends AgentDriverHost {
+ readonly rawOutput: RawOutputEvent[];
+ readonly releases: Array<Parameters<PreparedExecutionResource["release"]>[0]>;
+}
+
+export function createFakeAgentDriverHost(
+ overrides: Partial<PreparedExecutionResource> = {},
+): FakeAgentDriverHost {
+ let id = 0;
+ const rawOutput: RawOutputEvent[] = [];
+ const releases: Array<Parameters<PreparedExecutionResource["release"]>[0]> = [];
+ const resource: PreparedExecutionResource = {
+ environmentLayers: {
+ base: {},
+ hostStatic: {},
+ identityProtected: {},
+ platformProtected: {},
+ runtimeProtected: {},
+ networkProtected: {},
+ credentialSensitive: {},
+ },
+ async release(input) { releases.push(input); },
+ ...overrides,
+ };
+ return {
+ rawOutput,
+ releases,
+ async prepareExecution() { return { ok: true, resource }; },
+ onRawOutput(event) { rawOutput.push(event); },
+ now: () => 1_700_000_000_000 + id,
+ createId: () => `fake-${++id}`,
+ };
+}
diff --git a/src/daemon/agent-driver/src/testing/index.ts b/src/daemon/agent-driver/src/testing/index.ts
new file mode 100644
index 000000000..122632a66
--- /dev/null
+++ b/src/daemon/agent-driver/src/testing/index.ts
@@ -0,0 +1,12 @@
+export type * from "../public-contract.js";
+export { createFakeAgentDriverHost } from "./fake-host.js";
+export type { FakeAgentDriverHost } from "./fake-host.js";
+export { runAgentDriverConformance } from "./conformance.js";
+export type {
+ AgentDriverConformanceFixture,
+ AgentDriverConformanceResult,
+} from "./conformance.js";
+export type {
+ AgentDriverHost, DefaultAgentDriverHostOptions, PrepareExecutionInput, PrepareExecutionResult,
+ PreparedExecutionResource, RawOutputEvent,
+} from "../contract.js";
diff --git a/src/daemon/agent-driver/tsconfig.build.json b/src/daemon/agent-driver/tsconfig.build.json
new file mode 100644
index 000000000..39f794c30
--- /dev/null
+++ b/src/daemon/agent-driver/tsconfig.build.json
@@ -0,0 +1,11 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "outDir": "dist",
+ "rootDir": "src"
+ },
+ "exclude": ["src/**/*.test.ts", "src/**/*.spec.ts"]
+}
diff --git a/src/daemon/agent-driver/tsconfig.json b/src/daemon/agent-driver/tsconfig.json
new file mode 100644
index 000000000..123acf993
--- /dev/null
+++ b/src/daemon/agent-driver/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "strict": true,
+ "skipLibCheck": true,
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+ "types": ["node", "vitest/globals"]
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/src/daemon/agent-driver/vitest.config.ts b/src/daemon/agent-driver/vitest.config.ts
new file mode 100644
index 000000000..b735c981d
--- /dev/null
+++ b/src/daemon/agent-driver/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["src/**/*.test.ts"],
+ testTimeout: 30_000,
+ },
+});
diff --git a/src/daemon/eslint.config.ts b/src/daemon/eslint.config.ts
index 0a0bbe8ca..488b41e7f 100644
--- a/src/daemon/eslint.config.ts
+++ b/src/daemon/eslint.config.ts
@@ -3,7 +3,7 @@ import tseslint from "typescript-eslint";
const eslintConfig = defineConfig([
...tseslint.configs.recommended,
- globalIgnores(["dist/**", "coverage/**"]),
+ globalIgnores(["dist/**", "coverage/**", "agent-driver/**"]),
{
files: ["src/drivers/**/*.ts", "src/cli/proxyServerApi.ts", "src/server/contract.ts", "src/server/wsControlServer.ts"],
rules: {
diff --git a/src/daemon/package.json b/src/daemon/package.json
index 3a5ab3a49..d6d350e9d 100644
--- a/src/daemon/package.json
+++ b/src/daemon/package.json
@@ -36,6 +36,7 @@
"access": "public"
},
"scripts": {
+ "prebuild": "pnpm -C agent-driver run build",
"build": "bun build src/index.ts --outdir dist --target node --format esm --external commander --external ws --external sharp && bun build src/cli/index.ts --outdir dist/cli --target node --format esm --external commander --external ws --external sharp && node scripts/prepare-dist.mjs",
"prepack": "pnpm run build",
"typecheck": "tsc --noEmit",
@@ -51,6 +52,7 @@
"ws": "^8.21.3"
},
"devDependencies": {
+ "@alook/agent-driver": "workspace:*",
"@alook/shared": "workspace:*",
"@types/node": "^20.0.0",
"@types/ws": "^8.18.1",
diff --git a/src/daemon/src/agent-driver-bundle.packed.test.ts b/src/daemon/src/agent-driver-bundle.packed.test.ts
new file mode 100644
index 000000000..436c57b21
--- /dev/null
+++ b/src/daemon/src/agent-driver-bundle.packed.test.ts
@@ -0,0 +1,65 @@
+import { execFile } from "node:child_process";
+import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+import { execPackageManagerSync } from "./test-package-manager.js";
+
+const execFileAsync = promisify(execFile);
+const packageRoot = fileURLToPath(new URL("../", import.meta.url));
+const tempRoots: string[] = [];
+
+afterEach(() => {
+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function javascriptFiles(root: string): string[] {
+ return readdirSync(root, { recursive: true })
+ .filter((name): name is string => typeof name === "string" && name.endsWith(".js"))
+ .map((name) => join(root, name));
+}
+
+describe("packed daemon agent-driver boundary", () => {
+ it("installs and imports without a runtime agent-driver dependency", { timeout: 120_000 }, async () => {
+ const root = mkdtempSync(join(tmpdir(), "alook-daemon-driver-bundle-"));
+ const installRoot = join(root, "consumer");
+ tempRoots.push(root);
+ writeFileSync(join(root, "package.json"), "{}\n");
+ execPackageManagerSync(
+ ["pack", "--pack-destination", root],
+ { cwd: packageRoot, maxBuffer: 20 * 1024 * 1024 },
+ );
+ const tarballName = readdirSync(root).find((name) => name.endsWith(".tgz"));
+ if (!tarballName) throw new Error("daemon pack did not produce a tarball");
+
+ await execFileAsync("npm", [
+ "install",
+ "--ignore-scripts",
+ "--no-audit",
+ "--no-fund",
+ "--prefix",
+ installRoot,
+ join(root, tarballName),
+ ], {
+ cwd: root,
+ maxBuffer: 20 * 1024 * 1024,
+ shell: process.platform === "win32",
+ });
+
+ const installedRoot = join(installRoot, "node_modules/@alook/daemon");
+ const manifest = JSON.parse(readFileSync(join(installedRoot, "package.json"), "utf8")) as {
+ dependencies?: Record<string, string>;
+ };
+ expect(manifest.dependencies).not.toHaveProperty("@alook/agent-driver");
+ for (const file of javascriptFiles(join(installedRoot, "dist"))) {
+ expect(readFileSync(file, "utf8"), file).not.toContain("@alook/agent-driver");
+ }
+ await execFileAsync(process.execPath, [
+ "--input-type=module",
+ "--eval",
+ "await import('@alook/daemon')",
+ ], { cwd: installRoot, maxBuffer: 10 * 1024 * 1024 });
+ });
+});
diff --git a/src/daemon/src/cli/daemonLifecycle.real.test.ts b/src/daemon/src/cli/daemonLifecycle.real.test.ts
index 548412996..3b17bd549 100644
--- a/src/daemon/src/cli/daemonLifecycle.real.test.ts
+++ b/src/daemon/src/cli/daemonLifecycle.real.test.ts
@@ -201,7 +201,7 @@ describe("daemon lifecycle real processes", () => {
await stop(baseDir);
await waitFor(() => !alive(owner.pid));
expect(fs.existsSync(pidfile(baseDir))).toBe(false);
- }, 60_000);
+ }, 120_000);
it("fails a fresh bare credential offline without creating a hash-derived machine directory", async () => {
const baseDir = makeEmptyBaseDir();
diff --git a/src/daemon/src/cli/daemonRunner.test.ts b/src/daemon/src/cli/daemonRunner.test.ts
index ee657ecb0..922210301 100644
--- a/src/daemon/src/cli/daemonRunner.test.ts
+++ b/src/daemon/src/cli/daemonRunner.test.ts
@@ -326,7 +326,7 @@ describe("daemon runner logger", () => {
resetting: false,
resettingSince: null,
stoppingSince: null,
- apmPhase: "idle",
+ deliveryPhase: "idle",
effects: [],
nowMs: eventTime,
timeIso: new Date(eventTime).toISOString(),
diff --git a/src/daemon/src/constants.test.ts b/src/daemon/src/constants.test.ts
index ab13895e4..4513ab5cf 100644
--- a/src/daemon/src/constants.test.ts
+++ b/src/daemon/src/constants.test.ts
@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";
import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
-import { SESSION_STOP_GRACE_MS } from "./runtime/killTree";
+import { SESSION_STOP_GRACE_MS } from "../agent-driver/src/internal/killTree.js";
/**
* Structural pins for extracted constants. We assert *magnitudes*, not
@@ -35,12 +35,12 @@ describe("magic-number extractions", () => {
expect(SESSION_STOP_GRACE_MS).toBeLessThan(Number(match![1]));
});
- it("PROBE_TIMEOUT_MS is set to 5000 in drivers/probe.ts", () => {
- expect(readSrc("drivers/probe.ts")).toMatch(/PROBE_TIMEOUT_MS\s*=\s*5000\b/);
+ it("PROBE_TIMEOUT_MS is set to 5000 in the driver package", () => {
+ expect(readSrc("../agent-driver/src/internal/probe.ts")).toMatch(/PROBE_TIMEOUT_MS\s*=\s*5000\b/);
});
- it("STDERR_LOG_MAX_LEN is set to 2000 in manager/managerRuntime.ts", () => {
- expect(readSrc("manager/managerRuntime.ts")).toMatch(/STDERR_LOG_MAX_LEN\s*=\s*2000\b/);
+ it("the removed raw-stderr manager buffer limit stays deleted", () => {
+ expect(readSrc("manager/managerRuntime.ts")).not.toMatch(/\bSTDERR_LOG_MAX_LEN\b/);
});
it("ERROR_EXCERPT_MAX_BYTES is set to 4000 in runtime/errorDiagnostics.ts", () => {
@@ -59,10 +59,6 @@ describe("magic-number extractions", () => {
expect(readSrc("server/wsControlChannel.ts")).toMatch(/DEFAULT_PONG_TIMEOUT_MS\s*=\s*30_?000\b/);
});
- it("KIMI_WIRE_PROTOCOL_VERSION is '1.3' in drivers/kimi.ts", () => {
- expect(readSrc("drivers/kimi.ts")).toMatch(/KIMI_WIRE_PROTOCOL_VERSION\s*=\s*["']1\.3["']/);
- });
-
it("MESSAGE_ID_SHORT_LEN is set to 8 in inbox/projection.ts", () => {
expect(readSrc("inbox/projection.ts")).toMatch(/MESSAGE_ID_SHORT_LEN\s*=\s*8\b/);
});
@@ -78,8 +74,8 @@ describe("deleted symbols stay deleted", () => {
expect(readSrc("cli/daemonStart.ts")).not.toMatch(/MACHINE_KEY_HASH_PREFIX_LEN|fallbackIdForStableKey|function keyHash/);
});
- it("readCommandVersion is no longer exported by drivers/probe.ts", () => {
- expect(readSrc("drivers/probe.ts")).not.toMatch(/\breadCommandVersion\b/);
+ it("readCommandVersion is no longer exported by the driver probe", () => {
+ expect(readSrc("../agent-driver/src/internal/probe.ts")).not.toMatch(/\breadCommandVersion\b/);
});
it("credentialFilesDir is no longer defined in cli/daemonStart.ts", () => {
@@ -90,8 +86,8 @@ describe("deleted symbols stay deleted", () => {
expect(readSrc("drivers/systemPrompt.ts")).not.toMatch(/\bSystemPromptOpts\b/);
});
- it("DEFAULT_CLAUDE_MODEL is no longer defined in drivers/claudeLaunch.ts", () => {
- expect(readSrc("drivers/claudeLaunch.ts")).not.toMatch(/\bDEFAULT_CLAUDE_MODEL\b/);
+ it("DEFAULT_CLAUDE_MODEL is no longer defined in the Claude adapter", () => {
+ expect(readSrc("../agent-driver/src/adapters/claude/launch.ts")).not.toMatch(/\bDEFAULT_CLAUDE_MODEL\b/);
});
it("agent-backend / 1.0.0 identity string no longer appears in daemon source", () => {
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index cce1ad47b..43adbc257 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -1,19 +1,29 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { EventEmitter } from "events";
-import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
createDaemon,
+ createBuiltinDaemonSessionFactory,
createRuntimeRawLineTap,
deriveAuditLogSubcommand,
emitImplicitTypingStopOnSend,
parseRuntimeRawTraceAgentIds,
} from "./createDaemon";
-import { AgentProcessManager } from "../manager/managerRuntime";
+import {
+ AgentProcessManager,
+ type SessionFactory,
+} from "../manager/managerRuntime";
+import type {
+ AgentEvent,
+ AgentSession,
+ AgentSessionResult,
+ BuiltinBackendSpecs,
+} from "@alook/agent-driver";
import { AgentRouter } from "../manager/agentRouter";
import { CredentialBroker } from "../credentials/credentialProxy";
-import type { Driver } from "../types";
+import type { AgentBackend as Driver } from "../drivers/index.js";
import type { Logger } from "../logger";
const timelineSweepHarness = vi.hoisted(() => {
@@ -37,6 +47,10 @@ const timelineSweepHarness = vi.hoisted(() => {
});
const credentialProxyHarness = vi.hoisted(() => ({
+ onInboxPullStart: undefined as ((agentId: string) => unknown) | undefined,
+ onInboxPullResponse: undefined as (
+ ((agentId: string, messages: unknown[], observationToken?: unknown) => void) | undefined
+ ),
onInboxPullObservationError: undefined as ((failure: Record<string, unknown>) => void) | undefined,
}));
@@ -55,6 +69,10 @@ vi.mock("../credentials/index.js", async (importOriginal) => {
startCredentialProxy: (
...args: Parameters<typeof actual.startCredentialProxy>
): ReturnType<typeof actual.startCredentialProxy> => {
+ credentialProxyHarness.onInboxPullStart = args[1]?.onInboxPullStart;
+ credentialProxyHarness.onInboxPullResponse = args[1]?.onInboxPullResponse as
+ | ((agentId: string, messages: unknown[], observationToken?: unknown) => void)
+ | undefined;
credentialProxyHarness.onInboxPullObservationError = args[1]?.onInboxPullObservationError as
| ((failure: Record<string, unknown>) => void)
| undefined;
@@ -68,6 +86,8 @@ afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
timelineSweepHarness.reset();
+ credentialProxyHarness.onInboxPullStart = undefined;
+ credentialProxyHarness.onInboxPullResponse = undefined;
credentialProxyHarness.onInboxPullObservationError = undefined;
for (const dir of startupSweepDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
@@ -152,6 +172,105 @@ function fullFakeDriver(id: string): Driver {
} as unknown as Driver;
}
+type DaemonTestSession = AgentSession<BuiltinBackendSpecs, "codex">;
+
+interface DaemonFakeSession extends DaemonTestSession {
+ fire(event: string, ...args: unknown[]): Promise<void>;
+}
+
+function daemonFakeSession(options: {
+ onStart?: (input: { id: string; text: string }) => void;
+ onSend?: (input: { id: string; text: string; sequence?: number }) => void;
+ establish?: boolean;
+} = {}): DaemonFakeSession {
+ type Event = AgentEvent<BuiltinBackendSpecs, "codex">;
+ let sequence = 0;
+ const queued: Event[] = [];
+ const waiters: Array<(value: IteratorResult<Event>) => void> = [];
+ let ended = false;
+ let resolveClosed!: (result: AgentSessionResult) => void;
+ const closed = new Promise<AgentSessionResult>((resolve) => { resolveClosed = resolve; });
+ const emit = (payload: Omit<Event, "sequence" | "sessionInstanceId" | "at">) => {
+ const event = { ...payload, sequence: ++sequence, sessionInstanceId: "daemon-test", at: Date.now() } as Event;
+ const waiter = waiters.shift();
+ if (waiter) waiter({ done: false, value: event });
+ else queued.push(event);
+ };
+ const session: DaemonFakeSession = {
+ backend: "codex",
+ capabilities: {} as DaemonTestSession["capabilities"],
+ sessionInstanceId: "daemon-test",
+ events: {
+ maxBufferedBytes: 4_194_304,
+ [Symbol.asyncIterator]() {
+ return {
+ next: () => queued.length > 0
+ ? Promise.resolve({ done: false as const, value: queued.shift()! })
+ : new Promise<IteratorResult<Event>>((resolve) => waiters.push(resolve)),
+ };
+ },
+ },
+ closed,
+ async start(input) {
+ options.onStart?.(input);
+ if (options.establish !== false) {
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "test-session" });
+ }
+ emit({ type: "command_accepted", commandId: input.id, turnId: "daemon-test-turn", delivery: "prompt" } as never);
+ emit({ type: "turn_started", turnId: "daemon-test-turn", commandIds: [input.id] } as never);
+ return { status: "accepted", delivery: "prompt", commandId: input.id, turnId: "daemon-test-turn" };
+ },
+ async send(input) {
+ options.onSend?.(input);
+ emit({ type: "command_accepted", commandId: input.id, turnId: "daemon-test-turn", delivery: "steer" } as never);
+ return { status: "accepted", delivery: "steer", commandId: input.id, turnId: "daemon-test-turn" };
+ },
+ async interrupt() { return { status: "not_running" }; },
+ async stop() {
+ if (!ended) {
+ ended = true;
+ const result: AgentSessionResult = { outcome: "stopped", requested: true, exitCode: null, signal: null, cleanup: { status: "released" } };
+ resolveClosed(result);
+ }
+ return { status: "accepted", requestId: "daemon-test-stop" };
+ },
+ snapshot() {
+ return { sessionInstanceId: "daemon-test", state: "working", queuedCommands: [], lastEventSequence: sequence };
+ },
+ async invokeExtension() {
+ return { ok: false, error: { category: "internal", code: "unsupported", message: "unsupported", retryable: false } };
+ },
+ async fire(event, ...args) {
+ if (event === "runtime_event") {
+ const runtime = args[0] as { kind: string; sessionId?: string; text?: string };
+ if (runtime.kind === "session_init") {
+ emit({ type: "session_started", backendSessionId: runtime.sessionId ?? "test-session" } as never);
+ } else if (runtime.kind === "turn_end") {
+ emit({ type: "turn_completed", turnId: "daemon-test-turn", commandIds: [], result: { outcome: "success", backendSessionId: runtime.sessionId } } as never);
+ } else if (runtime.kind === "text") {
+ emit({ type: "text_delta", turnId: "daemon-test-turn", text: runtime.text ?? "" } as never);
+ }
+ } else if (event === "exit") {
+ const result: AgentSessionResult = { outcome: "stopped", requested: true, exitCode: null, signal: null, cleanup: { status: "released" } };
+ ended = true;
+ resolveClosed(result);
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ },
+ } as DaemonFakeSession;
+ return session;
+}
+
+function daemonSessionFactory(
+ options: Parameters<typeof daemonFakeSession>[0] = {},
+): SessionFactory {
+ return () => {
+ const session = daemonFakeSession(options);
+ return session;
+ };
+}
+
function factory(sockets: FakeSocket[]) {
return (url: string, headers: Record<string, string>) => {
const s = new FakeSocket(url, headers);
@@ -161,6 +280,137 @@ function factory(sockets: FakeSocket[]) {
}
describe("createDaemon", () => {
+ it("opens the builtin session factory and reports host preparation failures", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "daemon-builtin-session-"));
+ try {
+ const broker = new CredentialBroker({ upstreamBaseUrl: "https://upstream.test", voucherDir: dir });
+ const ctx = {
+ workingDirectory: dir,
+ agentId: "a1",
+ standingPrompt: "",
+ prompt: "",
+ agentCliPath: process.execPath,
+ launchId: "launch-1",
+ credentialProxy: {
+ broker,
+ proxyUrl: "http://127.0.0.1:9/proxy",
+ runnerKey: "runner-test",
+ capabilities: ["send"],
+ },
+ config: {},
+ };
+ const runtimeConfig = {
+ version: 1 as const,
+ runtime: "codex" as const,
+ model: { kind: "default" as const },
+ mode: { kind: "default" as const },
+ };
+ const session = await createBuiltinDaemonSessionFactory(vi.fn())({ agentId: "a1", ctx, runtimeConfig });
+ expect(session.backend).toBe("codex");
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await expect(createBuiltinDaemonSessionFactory()({
+ agentId: "a1",
+ ctx: { ...ctx, credentialProxy: undefined },
+ runtimeConfig,
+ })).rejects.toMatchObject({ code: "credential_proxy_required" });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("starts the builtin Codex lane from a fresh nested daemon workspace", async () => {
+ const base = mkdtempSync(join(tmpdir(), "daemon-fresh-workspace-"));
+ startupSweepDirs.push(base);
+ const rawLines: string[] = [];
+ const workingDirectory = join(base, "daemon", "agent-fresh");
+ const fakeRuntime = join(base, process.platform === "win32" ? "fake-codex.cmd" : "fake-codex");
+ const fakeModule = join(base, "fake-codex.mjs");
+ writeFileSync(fakeModule, `
+import { createInterface } from "node:readline";
+const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
+for await (const line of createInterface({ input: process.stdin })) {
+ const message = JSON.parse(line);
+ if (message.method === "initialize") {
+ send({ jsonrpc: "2.0", id: message.id, result: {} });
+ } else if (message.method === "thread/start") {
+ send({ jsonrpc: "2.0", id: message.id, result: { thread: { id: "fresh-thread" } } });
+ } else if (message.method === "turn/start") {
+ send({ jsonrpc: "2.0", method: "turn/started", params: { threadId: "fresh-thread", turn: { id: "fresh-turn" } } });
+ }
+}
+`);
+ if (process.platform === "win32") {
+ writeFileSync(fakeRuntime, `@node "%~dp0\\fake-codex.mjs" %*\r\n`);
+ } else {
+ writeFileSync(fakeRuntime, `#!/usr/bin/env node\nawait import(${JSON.stringify(fakeModule)});\n`);
+ chmodSync(fakeRuntime, 0o755);
+ }
+
+ const broker = new CredentialBroker({ upstreamBaseUrl: "https://upstream.test", voucherDir: base });
+ const ctx = {
+ workingDirectory,
+ agentId: "agent-fresh",
+ standingPrompt: "Fresh daemon instructions.",
+ prompt: "",
+ agentCliPath: process.execPath,
+ launchId: "fresh-launch",
+ credentialProxy: {
+ broker,
+ proxyUrl: "http://127.0.0.1:9/proxy",
+ runnerKey: "runner-fresh",
+ capabilities: ["send"],
+ },
+ config: {},
+ };
+ const runtimeConfig = {
+ version: 1 as const,
+ runtime: "codex" as const,
+ model: { kind: "default" as const },
+ mode: { kind: "default" as const },
+ command: fakeRuntime,
+ };
+
+ const session = await createBuiltinDaemonSessionFactory((_, line) => rawLines.push(line))({
+ agentId: "agent-fresh",
+ ctx,
+ runtimeConfig,
+ });
+ const events: AgentEvent<BuiltinBackendSpecs, "codex">[] = [];
+ const collectEvents = (async () => {
+ for await (const event of session.events) events.push(event);
+ })();
+ try {
+ const started = session.start({ id: "first", kind: "user", text: "hello" });
+ const admission = await new Promise<Awaited<typeof started>>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ reject(new Error(
+ `fresh Codex admission timed out; raw stdout: ${JSON.stringify(rawLines)}; events: ${JSON.stringify(events)}`,
+ ));
+ }, 15_000);
+ void started.then(
+ (result) => {
+ clearTimeout(timer);
+ resolve(result);
+ },
+ (error: unknown) => {
+ clearTimeout(timer);
+ reject(error);
+ },
+ );
+ });
+ expect(admission).toMatchObject({ status: "accepted" });
+ expect(readFileSync(join(workingDirectory, "AGENTS.md"), "utf8")).toBe("Fresh daemon instructions.");
+ expect(readFileSync(join(workingDirectory, "CLAUDE.md"), "utf8")).toBe("Fresh daemon instructions.");
+ } finally {
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await session.closed;
+ await collectEvents;
+ // `session.closed` is a teardown ownership boundary: the spawned shell and
+ // every runtime descendant must have released the workspace by this point.
+ rmSync(base, { recursive: true, force: true });
+ }
+ }, 30_000);
+
it("routes local reminder expiry through the manager and cancels on exact-scope wake/stop/removal/daemon stop", async () => {
const realFetch = globalThis.fetch;
const sockets: FakeSocket[] = [];
@@ -194,6 +444,7 @@ describe("createDaemon", () => {
webSocketFactory: factory(sockets) as never,
runtimeReport: [{ id: "mock" }],
driverFor: () => fullFakeDriver("mock"),
+ sessionFactory: daemonSessionFactory(),
capabilities: ["send"],
messageReminderClock: {
now: () => now,
@@ -748,7 +999,7 @@ describe("createDaemon — logging", () => {
global.fetch = originalFetch;
});
- it("asks a woken agent to read unread messages without requiring a reply", async () => {
+ it("asks a woken agent to pull unread messages without exposing the selected channel", async () => {
global.fetch = vi.fn(async (url: string | URL) => {
const href = String(url);
if (href.includes("/enroll-agent")) {
@@ -758,15 +1009,7 @@ describe("createDaemon — logging", () => {
}) as unknown as typeof fetch;
let spawnedPrompt = "";
- const driver: Driver = {
- ...fullFakeDriver("codex"),
- spawn: async (ctx) => {
- spawnedPrompt = ctx.prompt;
- const proc = new EventEmitter() as unknown as { kill: () => void };
- proc.kill = () => { };
- return { process: proc as never };
- },
- } as unknown as Driver;
+ const driver = fullFakeDriver("codex");
const sockets: FakeSocket[] = [];
const daemon = await createDaemon({
@@ -776,6 +1019,9 @@ describe("createDaemon — logging", () => {
webSocketFactory: factory(sockets) as any,
runtimeReport: [{ id: "codex" }],
driverFor: () => driver,
+ sessionFactory: daemonSessionFactory({
+ onStart: ({ text }) => { spawnedPrompt = text; },
+ }),
capabilities: [],
});
sockets[0].emit("open");
@@ -797,12 +1043,100 @@ describe("createDaemon — logging", () => {
);
await new Promise((r) => setTimeout(r, 20));
+ expect(spawnedPrompt).toContain("You have unread messages.");
expect(spawnedPrompt).toContain("Use `alook inbox pull` to read your messages.");
+ expect(spawnedPrompt).not.toContain("/demo#1234/general");
expect(spawnedPrompt).not.toContain("message send");
await daemon.stop();
});
+ it("keeps every working unread covered while coalescing wake bursts into one real session delivery", async () => {
+ global.fetch = vi.fn(async (url: string | URL) => {
+ const href = String(url);
+ if (href.includes("/enroll-agent")) {
+ return new Response(JSON.stringify({ runnerKey: "rk_working_coverage" }), { status: 200 });
+ }
+ return new Response(JSON.stringify({ bots: [] }), { status: 200 });
+ }) as unknown as typeof fetch;
+
+ const channel = "/demo#1234/general";
+ const starts: Array<{ id: string; text: string }> = [];
+ const sends: Array<{ id: string; text: string; sequence?: number }> = [];
+ const sockets: FakeSocket[] = [];
+ const daemon = await createDaemon({
+ machineKey: "cmk_working_coverage",
+ serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets) as any,
+ runtimeReport: [{ id: "codex" }],
+ driverFor: () => fullFakeDriver("codex"),
+ sessionFactory: daemonSessionFactory({
+ onStart: (input) => starts.push(input),
+ onSend: (input) => sends.push(input),
+ }),
+ capabilities: [],
+ });
+ const wake = (seq: number) => sockets[0].emit("message", JSON.stringify({
+ type: "agent:wake",
+ agentId: "bot_working",
+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },
+ launchId: `launch_${seq}`,
+ unreadNotice: { kind: "unread_notice", channel, latestSeq: seq },
+ }));
+ const wakeAcked = (seq: number) => sockets[0].sent.map((frame) => JSON.parse(frame)).some(
+ (frame) => frame.type === "agent_wake_ack" && frame.launchId === `launch_${seq}` && frame.status === "ok",
+ );
+ const observePull = (seq: number) => {
+ const observationToken = credentialProxyHarness.onInboxPullStart?.("bot_working");
+ credentialProxyHarness.onInboxPullResponse?.(
+ "bot_working",
+ [{ channel, seq: `#${seq}` }],
+ observationToken,
+ );
+ };
+
+ try {
+ sockets[0].emit("open");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ sockets[0].emit(
+ "message",
+ JSON.stringify({
+ type: "bot:added",
+ botId: "bot_working",
+ name: "Working Bot",
+ discriminator: "0001",
+ }),
+ );
+
+ wake(1);
+ await vi.waitFor(() => expect(starts).toHaveLength(1));
+ await vi.waitFor(() => expect(wakeAcked(1)).toBe(true));
+ observePull(1);
+
+ for (let seq = 2; seq <= 6; seq++) wake(seq);
+ await vi.waitFor(() => expect(wakeAcked(6)).toBe(true));
+ expect(sends).toHaveLength(1);
+ expect(sends[0]).toMatchObject({ sequence: 2 });
+
+ observePull(6);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(sends).toHaveLength(1);
+
+ wake(7);
+ wake(8);
+ await vi.waitFor(() => expect(wakeAcked(8)).toBe(true));
+ expect(sends).toHaveLength(2);
+ expect(sends[1]).toMatchObject({ sequence: 7 });
+
+ observePull(7);
+ await vi.waitFor(() => expect(sends).toHaveLength(3));
+ expect(sends[2]).toMatchObject({ sequence: 8 });
+ } finally {
+ await daemon.stop();
+ }
+ });
+
it("retries a later wake after handshake_timeout instead of globally disabling the runtime", async () => {
global.fetch = vi.fn(async (url: string | URL) => {
const href = String(url);
@@ -812,15 +1146,12 @@ describe("createDaemon — logging", () => {
return new Response(JSON.stringify({ bots: [] }), { status: 200 });
}) as unknown as typeof fetch;
- const spawn = vi.fn(async () => {
- const proc = new EventEmitter() as unknown as { kill: () => void };
- proc.kill = () => {};
- return { process: proc as never };
- });
- const driver = {
- ...fullFakeDriver("cursor"),
- spawn,
- } as unknown as Driver;
+ const spawn = vi.fn();
+ const driver = fullFakeDriver("cursor");
+ const sessionFactory: SessionFactory = () => {
+ spawn();
+ return daemonFakeSession({ establish: false });
+ };
const sockets: FakeSocket[] = [];
const logger = stubLogger();
const daemon = await createDaemon({
@@ -830,6 +1161,7 @@ describe("createDaemon — logging", () => {
webSocketFactory: factory(sockets) as any,
runtimeReport: [{ id: "cursor" }],
driverFor: () => driver,
+ sessionFactory,
capabilities: [],
handshakeTimeoutMs: 10,
logger,
@@ -946,13 +1278,7 @@ describe("createDaemon — logging", () => {
}) as unknown as typeof fetch;
const seenConfigs: Array<{ agentName?: string; agentHandle?: string }> = [];
- const driver: Driver = {
- ...fullFakeDriver("codex"),
- buildSystemPrompt: (config: { agentName?: string; agentHandle?: string }) => {
- seenConfigs.push(config);
- return "";
- },
- } as unknown as Driver;
+ const driver = fullFakeDriver("codex");
const sockets: FakeSocket[] = [];
const daemon = await createDaemon({
@@ -962,6 +1288,11 @@ describe("createDaemon — logging", () => {
webSocketFactory: factory(sockets) as any,
runtimeReport: [{ id: "codex" }],
driverFor: () => driver,
+ sessionFactory: (hooks) => {
+ const { ctx } = hooks;
+ seenConfigs.push(ctx.config);
+ return daemonFakeSession();
+ },
capabilities: [],
});
sockets[0].emit("open");
@@ -1206,7 +1537,7 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connecti
// A persistent, stdin-capable driver stays `running` after session_init
// without emitting turn_end — so the agent sits in a STEADY working state,
// which is exactly the window 2b exercises.
- const emitters: Array<EventEmitter> = [];
+ const emitters: DaemonFakeSession[] = [];
const persistentDriver = {
id: "codex",
lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,
@@ -1234,6 +1565,11 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connecti
webSocketFactory: factory(sockets) as any,
runtimeReport: [{ id: "codex" }],
driverFor: () => persistentDriver,
+ sessionFactory: () => {
+ const session = daemonFakeSession({ establish: false });
+ emitters.push(session);
+ return session;
+ },
capabilities: [],
tickIntervalMs: 1_000_000, // park the stall/hibernation loop out of the way
});
@@ -1253,7 +1589,7 @@ describe("createDaemon — level-triggered activity heartbeat (2b: live-connecti
// reaches `running` (turnActive) — a steady working state.
await vi.advanceTimersByTimeAsync(50);
expect(emitters.length).toBeGreaterThan(0);
- emitters[0].emit("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await emitters[0].fire("runtime_event", { kind: "session_init", sessionId: "s1" });
await vi.advanceTimersByTimeAsync(1);
const activityFrames = () =>
@@ -1420,18 +1756,7 @@ describe("AgentProcessManager.auditContext", () => {
it("reports launchId once register() has stashed one, and sessionId once a runtime session_init has landed", async () => {
const { AgentProcessManager } = await import("../manager/managerRuntime");
- const listeners = new Map<string, Array<(...args: unknown[]) => void>>();
- const session = {
- on: (event: string, cb: (...args: unknown[]) => void) => {
- const arr = listeners.get(event) ?? [];
- arr.push(cb);
- listeners.set(event, arr);
- },
- start: () => new Promise<void>(() => { }),
- send: () => { },
- stop: () => { },
- get currentSessionId() { return null; },
- };
+ const session = daemonFakeSession({ establish: false });
const mgr = new AgentProcessManager({
driverFor: () => ({
id: "codex",
@@ -1440,13 +1765,13 @@ describe("AgentProcessManager.auditContext", () => {
busyDeliveryMode: "none",
} as never),
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", config: {} }) as never,
- sessionFactory: () => session as never,
+ sessionFactory: () => session,
});
mgr.register("a1", { launchId: "l_XYZ" });
expect(mgr.auditContext("a1")).toEqual({ sessionId: null, launchId: "l_XYZ" });
mgr.deliver("a1", { seq: 1, text: "hi" } as never);
- for (const cb of listeners.get("runtime_event") ?? []) cb({ kind: "session_init", sessionId: "s_ABC" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s_ABC" });
expect(mgr.auditContext("a1")).toEqual({ sessionId: "s_ABC", launchId: "l_XYZ" });
});
});
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 581f04e3b..d7dc9a9b9 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -30,17 +30,18 @@ import { writeStatusFile } from "../util/statusFile.js";
import { WsControlChannel } from "../server/wsControlChannel.js";
import { CredentialBroker, startCredentialProxy } from "../credentials/index.js";
import { AgentProcessManager, AgentRouter, createTypingScopeTracker } from "../manager/index.js";
-import type { ManagerTraceRecord, TypingScopeTracker } from "../manager/index.js";
+import type { ManagerTraceRecord, SessionFactory, TypingScopeTracker } from "../manager/index.js";
import { UnknownBotError, BotEnrollFailedError, UnknownRuntimeError } from "../manager/agentRouter.js";
import { createTimelineRecorder, sweepTimelineHistory } from "../timeline/index.js";
import { resolveAlookCliPathWithFallback } from "../discovery.js";
-import { createPiSdkDriverDeps } from "../drivers/piSdkDeps.js";
import { createLogger, type Logger } from "../logger.js";
-import type { Driver, LaunchContext } from "../types.js";
+import type { AgentBackend } from "../drivers/index.js";
+import type { HostLaunchContext } from "../manager/hostContext.js";
import type { RuntimeConfig } from "../runtimeConfig.js";
-import type { UnreadNotice, HostCommand } from "../server/contract.js";
+import type { HostCommand } from "../server/contract.js";
import { formatHandle } from "@alook/shared/lib/discriminator";
import type { DiagnosticCollectCommand } from "@alook/shared";
+import { createBuiltinAgentDriverSdk } from "@alook/agent-driver/host";
import {
createDiagnosticsCommandListener,
type DiagnosticFailureReport,
@@ -50,6 +51,8 @@ import {
MessageReminderScheduler,
type MessageReminderSchedulerOptions,
} from "./messageReminderScheduler.js";
+import { createDaemonAgentDriverHost } from "../manager/agentDriverHost.js";
+import { toAgentBackendSelection } from "../runtimeConfig.js";
// Cold-start warmup backoff schedule (ms).
const WARMUP_BACKOFF_MS = [250, 500, 1000, 2000, 4000] as const;
@@ -261,7 +264,9 @@ export interface CreateDaemonOptions {
* `agent:wake`) is passed so callers can dispatch on the actual runtime
* the agent asked for; tests may omit it and hand back a stub driver.
*/
- driverFor: (agentId: string, runtimeConfig?: RuntimeConfig) => Driver;
+ driverFor: (agentId: string, runtimeConfig?: RuntimeConfig) => AgentBackend;
+ /** Public-session construction seam used by deterministic daemon tests. */
+ sessionFactory?: SessionFactory;
/** Default capability set granted to each agent's voucher. */
capabilities: string[];
/** Working directory base for agent launch contexts. */
@@ -341,6 +346,32 @@ export interface RunningDaemon {
stop(): Promise<void>;
}
+export function createBuiltinDaemonSessionFactory(
+ onRuntimeRawLine?: (agentId: string, line: string) => void,
+): SessionFactory {
+ return async ({ ctx, runtimeConfig }) => {
+ const selected = toAgentBackendSelection(runtimeConfig);
+ const sdk = createBuiltinAgentDriverSdk({
+ host: createDaemonAgentDriverHost(
+ ctx,
+ onRuntimeRawLine?.bind(null, ctx.agentId),
+ ),
+ });
+ const opened = await sdk.open({
+ backend: selected.backend,
+ launch: {
+ workingDirectory: ctx.workingDirectory,
+ instructions: { format: "markdown", content: ctx.standingPrompt },
+ resumeSessionId: ctx.config.sessionId,
+ launchId: ctx.launchId ?? ctx.agentId,
+ },
+ config: selected.config as never,
+ });
+ if (!opened.ok) throw Object.assign(new Error(opened.error.message), { code: opened.error.code });
+ return opened.session;
+ };
+}
+
/**
* Start a daemon. Connects the control plane, starts the credential proxy (with
* an inboxPull hook for timeline), enrolls agents on first contact, and wires
@@ -772,6 +803,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
}
return opts.driverFor(agentId, runtimeConfig);
},
+ sessionFactory: opts.sessionFactory ?? createBuiltinDaemonSessionFactory(onRuntimeRawLine),
onRuntimeSpawnFailed: (runtimeId, reason) => {
router?.recordRuntimeSpawnFailure(runtimeId, reason);
},
@@ -800,8 +832,8 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
...(botMeta?.ownerName && botMeta?.ownerDiscriminator
? { ownerHandle: `@${formatHandle(botMeta.ownerName, botMeta.ownerDiscriminator)}` }
: {}),
- } as LaunchContext["config"],
- } as Omit<LaunchContext, "prompt" | "standingPrompt"> & { config?: LaunchContext["config"] };
+ } as HostLaunchContext["config"],
+ } as Omit<HostLaunchContext, "prompt" | "standingPrompt"> & { config?: HostLaunchContext["config"] };
},
...(opts.handshakeTimeoutMs !== undefined
? { handshakeTimeoutMs: opts.handshakeTimeoutMs }
@@ -848,9 +880,6 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
...(diagnosticTrace.onFsmTransition
? { onFsmTransition: diagnosticTrace.onFsmTransition }
: {}),
- // Only the "pi" runtime declares `Driver.createSession` today (in-process
- // SDK, no child process) — this is only ever consulted for that case.
- sdkDriverDepsFor: (ctx) => createPiSdkDriverDeps(ctx),
timeline,
wakePromptFooter: "Use `alook inbox pull` to read your messages.",
stampWakePromptTime: true,
@@ -923,8 +952,6 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
}
await enrollAgent(agentId);
},
- formatUnreadNoticeText: (notice: UnreadNotice) =>
- `You have unread messages in channel ${notice.channel}.`,
});
// Machine lifecycle commands are claimed before diagnostics, bot observers,
diff --git a/src/daemon/src/daemon/messageReminderScheduler.ts b/src/daemon/src/daemon/messageReminderScheduler.ts
index 7761cb13d..ccc135c7e 100644
--- a/src/daemon/src/daemon/messageReminderScheduler.ts
+++ b/src/daemon/src/daemon/messageReminderScheduler.ts
@@ -19,7 +19,7 @@ interface ReminderRecord extends MessageReminderArmInput {
}
export interface MessageReminderSchedulerOptions {
- deliver(agentId: string, message: { text: string }): unknown;
+ deliver(agentId: string, message: { id: string; text: string }): unknown;
now?: () => number;
setTimer?: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
clearTimer?: (timer: ReturnType<typeof setTimeout>) => void;
@@ -72,6 +72,7 @@ export class MessageReminderScheduler {
this.reminders.delete(key);
try {
const delivery = this.options.deliver(input.agentId, {
+ id: `${input.agentId}:reminder:${input.channel}:${input.sentSeq}:${startedAt}`,
text: reminderPrompt(input.channel, sentRef, startedAt),
});
// Delivery is best-effort. The manager is currently synchronous, but
diff --git a/src/daemon/src/diagnostics/privacyPolicy.test.ts b/src/daemon/src/diagnostics/privacyPolicy.test.ts
index 0d3ab333c..734c874a5 100644
--- a/src/daemon/src/diagnostics/privacyPolicy.test.ts
+++ b/src/daemon/src/diagnostics/privacyPolicy.test.ts
@@ -25,14 +25,15 @@ async function loadSubject(): Promise<PrivacyPolicyModule> {
return vi.importActual<PrivacyPolicyModule>("./privacyPolicy.js");
}
-const EXPECTED_APM_PHASES = [
+const EXPECTED_DELIVERY_PHASES = [
"idle",
- "tool_wait",
- "tool_boundary",
- "assistant_continuation",
+ "admission_wait",
+ "steering",
+ "next_turn_queued",
"compacting",
"reviewing",
- "error",
+ "tool_wait",
+ "working",
] as const;
const EXPECTED_MANAGER_EVENTS = [
@@ -40,7 +41,7 @@ const EXPECTED_MANAGER_EVENTS = [
"wake",
"spawned",
"session",
- "progress",
+ "root_work",
"turn_end",
"exit",
"tick",
@@ -48,6 +49,8 @@ const EXPECTED_MANAGER_EVENTS = [
"begin_reset",
"rewake_after_reset",
"runtime_signal",
+ "admission_started",
+ "admission_settled",
] as const;
const EXPECTED_MANAGER_EFFECTS = ["spawn", "send", "stop", "terminate_stalled", "force_exit", "gated_hold"] as const;
@@ -118,6 +121,7 @@ const EXPECTED_EXIT_SIGNALS = [
type ProjectionFieldRule = (
| { type: "string"; maxChars: number; nullable?: true }
| { type: "integer"; min: number; max: number; nullable?: true }
+ | { type: "number"; min: number; max: number }
| { type: "boolean" }
| { type: "timestamp" }
| { type: "enum"; values: readonly string[]; maxChars?: number; nullable?: true; unknownBucket?: "other" }
@@ -137,7 +141,16 @@ const FSM_FIELD_RULES: Readonly<Record<string, ProjectionFieldRule>> = {
resetting: { type: "boolean" },
resettingSince: { type: "integer", min: 0, max: Number.MAX_SAFE_INTEGER, nullable: true },
stoppingSince: { type: "integer", min: 0, max: Number.MAX_SAFE_INTEGER, nullable: true },
- apmPhase: { type: "enum", values: EXPECTED_APM_PHASES },
+ deliveryPhase: { type: "enum", values: EXPECTED_DELIVERY_PHASES },
+ physicalOpenCount: { type: "number", min: 0, max: Number.MAX_VALUE, optional: true },
+ turnCount: { type: "number", min: 0, max: Number.MAX_VALUE, optional: true },
+ commandAdmissionCount: { type: "number", min: 0, max: Number.MAX_VALUE, optional: true },
+ commandAdmissionLatencyTotalMs: { type: "number", min: 0, max: Number.MAX_VALUE, optional: true },
+ queueDwellCount: { type: "number", min: 0, max: Number.MAX_VALUE, optional: true },
+ queueDwellTotalMs: { type: "number", min: 0, max: Number.MAX_VALUE, optional: true },
+ sseReconnectCount: { type: "number", min: 0, max: Number.MAX_VALUE, optional: true },
+ resumeOutcome: { type: "enum", values: ["not_requested", "pending", "resumed", "reset_required", "failed"], optional: true },
+ terminalOwnerKind: { type: "enum", values: ["transport_request", "vendor_message", "prompt_invocation", "lane_generation"], optional: true },
effects: { type: "enum_array", values: EXPECTED_MANAGER_EFFECTS, maxItems: 32, dropUnknown: true },
nowMs: { type: "integer", min: 0, max: Number.MAX_SAFE_INTEGER },
timeIso: { type: "timestamp" },
@@ -366,7 +379,7 @@ function baseFsm(overrides: Record<string, unknown> = {}): Record<string, unknow
resetting: false,
resettingSince: null,
stoppingSince: null,
- apmPhase: "idle",
+ deliveryPhase: "idle",
effects: ["spawn", "send", "unknown-effect"],
nowMs: 120,
timeIso: "1970-01-01T00:00:00.120Z",
@@ -399,13 +412,30 @@ function baseTurnSpan(overrides: Record<string, unknown> = {}): Record<string, u
};
}
+const TRACE_METRICS = {
+ physicalOpenCount: 1,
+ turnCount: 2,
+ commandAdmissionCount: 3,
+ commandAdmissionLatencyTotalMs: 4.5,
+ queueDwellCount: 5,
+ queueDwellTotalMs: 6.5,
+ sseReconnectCount: 7,
+ resumeOutcome: "resumed",
+ terminalOwnerKind: "transport_request",
+} as const;
+const TRACE_METRIC_FIELDS = new Set(Object.keys(TRACE_METRICS));
+
function fsmWithField(field: string, value: unknown): Record<string, unknown> {
const context = ["endReason", "terminationCause"].includes(field)
? { event: "turn_end", endReason: "errored", terminationCause: "runtime_error" }
: ["exitCode", "exitSignal", "abnormal", "spawnFailureReason", "terminationSemantics"].includes(field)
? { event: "exit", exitCode: null, exitSignal: null, abnormal: false }
: {};
- return baseFsm({ ...context, [field]: value });
+ return baseFsm({
+ ...context,
+ ...(TRACE_METRIC_FIELDS.has(field) ? TRACE_METRICS : {}),
+ [field]: value,
+ });
}
function turnSpanWithField(field: string, value: unknown): Record<string, unknown> {
@@ -423,6 +453,8 @@ function invalidProjectionValues(rule: ProjectionFieldRule): unknown[] {
return [1, "x".repeat(rule.maxChars + 1)];
case "integer":
return ["1", rule.min - 1, rule.max + 1, rule.min + 0.5, Number.POSITIVE_INFINITY];
+ case "number":
+ return ["1", rule.min - 1, Number.POSITIVE_INFINITY, Number.NaN];
case "boolean":
return ["true", 1];
case "timestamp":
@@ -490,7 +522,7 @@ describe("B2c privacy policy", () => {
resetting: false,
resettingSince: null,
stoppingSince: null,
- apmPhase: "idle",
+ deliveryPhase: "idle",
effects: ["spawn", "send"],
nowMs: 120,
timeIso: "1970-01-01T00:00:00.120Z",
@@ -505,8 +537,8 @@ describe("B2c privacy policy", () => {
});
expect(JSON.stringify(projected)).not.toMatch(/PROMPT_LEAK|SEND_LEAK|RESPONSE_LEAK|THINKING_LEAK|TOOL_LEAK|ERROR_LEAK|RECENT_LEAK|UNKNOWN_LEAK/);
- for (const apmPhase of EXPECTED_APM_PHASES) {
- expect(api.projectFsmTraceRow(baseFsm({ apmPhase }), "target-agent"), apmPhase).toMatchObject({ apmPhase });
+ for (const deliveryPhase of EXPECTED_DELIVERY_PHASES) {
+ expect(api.projectFsmTraceRow(baseFsm({ deliveryPhase }), "target-agent"), deliveryPhase).toMatchObject({ deliveryPhase });
}
for (const event of EXPECTED_MANAGER_EVENTS) {
expect(api.projectFsmTraceRow(baseFsm({ event }), "target-agent"), event).toMatchObject({ event });
@@ -616,6 +648,10 @@ describe("B2c privacy policy", () => {
expect(api.projectFsmTraceRow(turnSpanWithField(field, rule.min), "target-agent"), `span.${field}=min`)
.toMatchObject({ [field]: rule.min });
}
+ if (rule.type === "number") {
+ expect(api.projectFsmTraceRow(fsmWithField(field, rule.min), "target-agent"), `${field}=min`)
+ .toMatchObject({ [field]: rule.min });
+ }
if (rule.type === "string" && field !== "agentId") {
const bounded = "x".repeat(rule.maxChars);
expect(api.projectFsmTraceRow(turnSpanWithField(field, bounded), "target-agent"), `span.${field}=maxChars`)
@@ -638,8 +674,8 @@ describe("B2c privacy policy", () => {
expect(api.projectFsmTraceRow(baseFsm({ recordKind: "unknown" }), "target-agent")).toBeNull();
expect(api.projectFsmTraceRow(baseFsm({ event: "HOSTILE_EVENT" }), "target-agent")).toBeNull();
expect(api.projectFsmTraceRow(baseFsm({ status: "HOSTILE_STATUS" }), "target-agent")).toBeNull();
- expect(api.projectFsmTraceRow(baseFsm({ apmPhase: "working" }), "target-agent")).toBeNull();
- expect(api.projectFsmTraceRow(baseFsm({ apmPhase: "HOSTILE_APM_PHASE" }), "target-agent")).toBeNull();
+ expect(api.projectFsmTraceRow(baseFsm({ deliveryPhase: "tool_boundary" }), "target-agent")).toBeNull();
+ expect(api.projectFsmTraceRow(baseFsm({ deliveryPhase: "HOSTILE_DELIVERY_PHASE" }), "target-agent")).toBeNull();
expect(api.projectFsmTraceRow(baseFsm({ nowMs: Number.POSITIVE_INFINITY }), "target-agent")).toBeNull();
expect(api.projectFsmTraceRow(baseFsm({ traceTurnId: "x".repeat(1025) }), "target-agent")).toBeNull();
const boundedAgentId = "a".repeat(128);
@@ -683,7 +719,9 @@ describe("B2c privacy policy", () => {
.toMatchObject({ [field]: "other" });
}
if (rule.optional) {
- const withoutOptional = fsmWithField(field, rule.type === "enum" ? rule.values[0] : undefined);
+ const withoutOptional = TRACE_METRIC_FIELDS.has(field)
+ ? baseFsm()
+ : fsmWithField(field, rule.type === "enum" ? rule.values[0] : undefined);
delete withoutOptional[field];
expect(api.projectFsmTraceRow(withoutOptional, "target-agent"), `${field}=omitted`).not.toBeNull();
}
@@ -733,7 +771,7 @@ describe("B2c privacy policy", () => {
fields: {
agentId: "target-agent",
runtime: "claude",
- text: "provider failed cmk_ABC123 cmt_XYZ crk_RECONNECT Authorization: Bearer topsecret voucher=/tmp/voucher-token /Users/alice/project /home/bob/work C:\\Users\\alice\\secret \\\\server\\share\\private",
+ text: 'provider failed cmk_ABC123 cmt_XYZ crk_RECONNECT Authorization: Basic topsecret OPENAI_API_KEY=provider-secret {"apiKey":"json-secret"} voucher=/tmp/voucher-token /Users/Alice Smith/private key.json /home/bob/work C:\\Users\\alice\\secret \\\\server\\share\\private https://example.invalid/x?token=query-secret',
prompt: "PROMPT_EXTRA_LEAK",
authorization: "AUTH_EXTRA_LEAK",
otherBotId: "second-agent",
@@ -749,7 +787,7 @@ describe("B2c privacy policy", () => {
fields: { agentId: "target-agent", runtime: "claude" },
});
expect(encoded).toContain("provider failed");
- expect(encoded).not.toMatch(/cmk_|cmt_|crk_|topsecret|voucher-token|\/Users\/alice|\/home\/bob|C:\\\\Users\\\\alice|server\\\\share|PROMPT_EXTRA|AUTH_EXTRA|second-agent/);
+ expect(encoded).not.toMatch(/cmk_|cmt_|crk_|topsecret|provider-secret|json-secret|voucher-token|Alice Smith|private key|\/home\/bob|C:\\\\Users\\\\alice|server\\\\share|query-secret|PROMPT_EXTRA|AUTH_EXTRA|second-agent/);
});
it("drops every non-allowlisted field from every admitted daemon tuple", async () => {
diff --git a/src/daemon/src/diagnostics/privacyPolicy.ts b/src/daemon/src/diagnostics/privacyPolicy.ts
index c8d436d6b..454d8cbc2 100644
--- a/src/daemon/src/diagnostics/privacyPolicy.ts
+++ b/src/daemon/src/diagnostics/privacyPolicy.ts
@@ -1,4 +1,5 @@
import type { LogLevel } from "../logger.js";
+import { scrubAgentDriverDiagnosticText } from "@alook/agent-driver/host";
type FieldRule =
| { type: "string"; maxChars: number; values?: readonly string[]; scrub?: true; nullable?: true }
@@ -102,13 +103,7 @@ function boundedString(value: unknown, maxChars: number): value is string {
}
export function scrubDiagnosticText(value: string): string {
- let scrubbed = value
- .replace(/\b(?:cmk|cmt|crk)_[A-Za-z0-9_-]+\b/g, "[redacted-token]")
- .replace(/Authorization\s*:\s*Bearer\s+[^\s]+/gi, "Authorization: Bearer [redacted]")
- .replace(/\bvoucher\s*=\s*[^\s]+/gi, "voucher=[redacted]")
- .replace(/\\\\[^\\\s]+\\[^\s]+/g, "[redacted-path]")
- .replace(/\b[A-Za-z]:\\(?:[^\\\s]+\\)*[^\s]*/g, "[redacted-path]")
- .replace(/(?<![A-Za-z0-9:/])\/(?:Users|home|tmp|var|etc|opt|private|usr|Library|Volumes|Applications|root|run|srv|mnt)(?:\/[^\s]*)?/g, "[redacted-path]");
+ let scrubbed = scrubAgentDriverDiagnosticText(value);
const encoded = Buffer.from(scrubbed, "utf8");
if (encoded.byteLength > 65_536) {
let bytes = 0;
@@ -169,10 +164,12 @@ export function projectDaemonLogRow(value: unknown, targetAgentId: string): Reco
};
}
-const MANAGER_EVENTS = ["register", "wake", "spawned", "session", "progress", "turn_end", "exit", "tick", "reset_session", "begin_reset", "rewake_after_reset", "runtime_signal"] as const;
+const MANAGER_EVENTS = ["register", "wake", "spawned", "session", "root_work", "turn_end", "exit", "tick", "reset_session", "begin_reset", "rewake_after_reset", "runtime_signal", "admission_started", "admission_settled"] as const;
const MANAGER_EFFECTS = ["spawn", "send", "stop", "terminate_stalled", "force_exit", "gated_hold"] as const;
const AGENT_STATUSES = ["idle", "starting", "running", "stopping"] as const;
-const APM_PHASES = ["idle", "tool_wait", "tool_boundary", "assistant_continuation", "compacting", "reviewing", "error"] as const;
+const DELIVERY_PHASES = ["idle", "admission_wait", "steering", "next_turn_queued", "compacting", "reviewing", "tool_wait", "working"] as const;
+const RESUME_OUTCOMES = ["not_requested", "pending", "resumed", "reset_required", "failed"] as const;
+const TERMINAL_OWNER_KINDS = ["transport_request", "vendor_message", "prompt_invocation", "lane_generation"] as const;
const TERMINATION_CAUSES = ["runtime_error", "killed_stalled", "other"] as const;
const SPAWN_FAILURE_REASONS = ["ENOENT", "handshake_timeout", "pre_handshake_exit", "spawn_threw", "other"] as const;
const TERMINATION_SEMANTICS = ["killed_stalled", "idle_stop", "force_exit", "other"] as const;
@@ -192,6 +189,13 @@ function copyInteger(row: Record<string, unknown>, output: Record<string, unknow
return true;
}
+function copyFiniteNumber(row: Record<string, unknown>, output: Record<string, unknown>, key: string): boolean {
+ const value = row[key];
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return false;
+ output[key] = value;
+ return true;
+}
+
function copyString(row: Record<string, unknown>, output: Record<string, unknown>, key: string, maxChars: number, optional = false, nullable = false): boolean {
if (!(key in row) || row[key] === undefined) return optional;
if (row[key] === null && nullable) { output[key] = null; return true; }
@@ -222,8 +226,8 @@ function projectFsm(row: Record<string, unknown>, targetAgentId: string): Record
if (!output) return null;
const event = enumValue(row.event, MANAGER_EVENTS);
const status = enumValue(row.status, AGENT_STATUSES);
- const apmPhase = enumValue(row.apmPhase, APM_PHASES);
- if (!event || !status || !apmPhase || typeof row.turnActive !== "boolean" || typeof row.resetting !== "boolean") return null;
+ const deliveryPhase = enumValue(row.deliveryPhase, DELIVERY_PHASES);
+ if (!event || !status || !deliveryPhase || typeof row.turnActive !== "boolean" || typeof row.resetting !== "boolean") return null;
Object.assign(output, { event, status, turnActive: row.turnActive });
if (!copyInteger(row, output, "inbox")
|| !copyInteger(row, output, "lastDeliverAt", { nullable: true })
@@ -232,12 +236,33 @@ function projectFsm(row: Record<string, unknown>, targetAgentId: string): Record
output.resetting = row.resetting;
if (!copyInteger(row, output, "resettingSince", { nullable: true })
|| !copyInteger(row, output, "stoppingSince", { nullable: true })) return null;
- output.apmPhase = apmPhase;
+ output.deliveryPhase = deliveryPhase;
if (!copyInteger(row, output, "sinceProgressMs")
|| !copyInteger(row, output, "sinceDeliverMs", { nullable: true })
|| !copyInteger(row, output, "sinceStoppingMs", { nullable: true })
|| !projectOptionalSpanMetadata(row, output)) return null;
+ const metricKeys = [
+ "physicalOpenCount",
+ "turnCount",
+ "commandAdmissionCount",
+ "commandAdmissionLatencyTotalMs",
+ "queueDwellCount",
+ "queueDwellTotalMs",
+ "sseReconnectCount",
+ ] as const;
+ const hasMetrics = metricKeys.some((key) => key in row || row[key] !== undefined)
+ || "resumeOutcome" in row
+ || "terminalOwnerKind" in row;
+ if (hasMetrics) {
+ if (!metricKeys.every((key) => copyFiniteNumber(row, output, key))) return null;
+ const resumeOutcome = enumValue(row.resumeOutcome, RESUME_OUTCOMES);
+ const terminalOwnerKind = enumValue(row.terminalOwnerKind, TERMINAL_OWNER_KINDS);
+ if (!resumeOutcome || !terminalOwnerKind) return null;
+ output.resumeOutcome = resumeOutcome;
+ output.terminalOwnerKind = terminalOwnerKind;
+ }
+
if ("endReason" in row && row.endReason !== undefined) {
if (event !== "turn_end" || row.endReason !== "errored") return null;
output.endReason = "errored";
diff --git a/src/daemon/src/discovery.test.ts b/src/daemon/src/discovery.test.ts
index 8a5b7639f..d98f3f81d 100644
--- a/src/daemon/src/discovery.test.ts
+++ b/src/daemon/src/discovery.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeAll, afterEach } from "vitest";
+import { describe, it, expect, beforeAll, afterEach, vi } from "vitest";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
@@ -10,11 +10,9 @@ import {
detectRuntimes,
getAvailableRuntimes,
} from "./discovery";
-import { listRuntimeIds, getDriver } from "./drivers/index";
+import * as drivers from "./drivers/index";
-// The advertised (selectable) set — kept as a policy in discovery.ts, so assert
-// against the literal expectation here rather than importing a private const.
-const EXPECTED_SELECTABLE = ["claude", "codex", "opencode", "pi", "cursor"];
+const EXPECTED_RUNTIMES = ["claude", "codex", "cursor", "opencode", "pi"];
const tmpDirs: string[] = [];
function mkTmp(): string {
@@ -23,6 +21,7 @@ function mkTmp(): string {
return d;
}
afterEach(() => {
+ vi.restoreAllMocks();
for (const d of tmpDirs.splice(0)) fs.rmSync(d, { recursive: true, force: true });
});
@@ -139,7 +138,7 @@ describe("resolveAlookCliPathWithFallback", () => {
// `detectRuntimes()` probes every registered runtime by resolving its binary
// on PATH (a spawned subprocess per runtime — `which` on POSIX, `where` on
-// Windows). Even a fast per-spawn cost adds up across ~9 runtimes probed
+// Windows). Even a fast per-spawn cost adds up across the runtimes probed
// sequentially, so share ONE probe across all assertions in this describe
// block (via `beforeAll`) instead of re-running it per `it()`.
describe("detectRuntimes", () => {
@@ -176,28 +175,38 @@ describe("detectRuntimes", () => {
}
});
- it("advertises ONLY the selectable runtimes — hidden ones are not offered", () => {
+ it("advertises exactly the five supported runtimes", () => {
const advertised = runtimes.map((r) => r.id).sort();
- expect(advertised).toEqual([...EXPECTED_SELECTABLE].sort());
- // The hidden drivers exist in the registry but must not be advertised.
- for (const hidden of ["antigravity", "copilot", "gemini", "kimi"]) {
- expect(advertised).not.toContain(hidden);
- }
+ expect(advertised).toEqual([...EXPECTED_RUNTIMES].sort());
+ });
+
+ it("reports an explicit unhealthy probe result", async () => {
+ vi.spyOn(drivers, "getDriver").mockReturnValue({
+ probe: async () => ({ status: "unhealthy", error: { code: "missing_binary", message: "missing" } }),
+ } as never);
+ const result = await detectRuntimes();
+ expect(result).toHaveLength(EXPECTED_RUNTIMES.length);
+ expect(result[0]).toMatchObject({ status: "unhealthy", lastError: "missing_binary" });
+ });
+
+ it("reports an explicit healthy probe result with its version", async () => {
+ vi.spyOn(drivers, "getDriver").mockReturnValue({
+ probe: async () => ({ status: "healthy", version: "9.8.7" }),
+ } as never);
+ const result = await detectRuntimes();
+ expect(result).toHaveLength(EXPECTED_RUNTIMES.length);
+ expect(result[0]).toEqual({ id: EXPECTED_RUNTIMES[0], status: "healthy", version: "9.8.7" });
});
});
-describe("driver allowlist (hide, not delete)", () => {
- it("the advertised set is a strict subset of the full registry", () => {
- const all = listRuntimeIds();
- for (const id of EXPECTED_SELECTABLE) expect(all).toContain(id);
- expect(EXPECTED_SELECTABLE.length).toBeLessThan(all.length);
+describe("driver registry", () => {
+ it("contains exactly the five supported runtimes", () => {
+ expect(drivers.listRuntimeIds().slice().sort()).toEqual([...EXPECTED_RUNTIMES].sort());
});
- it("getDriver STILL resolves a hidden runtime — existing bots on it keep working on resume", () => {
- // The whole point of hide-not-delete: a bot created on gemini/kimi/etc.
- // before the shrink must still get a driver when it wakes.
- for (const hidden of ["antigravity", "copilot", "gemini", "kimi"]) {
- expect(() => getDriver(hidden)).not.toThrow();
+ it("rejects removed and unknown runtimes", () => {
+ for (const removed of ["antigravity", "copilot", "gemini", "kimi", "unknown-runtime"]) {
+ expect(() => drivers.getDriver(removed)).toThrow(/Unknown runtime/);
}
});
});
diff --git a/src/daemon/src/discovery.ts b/src/daemon/src/discovery.ts
index d66abbd65..c9bd68a4c 100644
--- a/src/daemon/src/discovery.ts
+++ b/src/daemon/src/discovery.ts
@@ -8,18 +8,6 @@ import * as path from "path";
import * as fs from "fs";
import { fileURLToPath } from "url";
import { getDriver, listRuntimeIds, type RuntimeId } from "./drivers/index.js";
-import type { ProbeResult } from "./types.js";
-
-/**
- * Runtimes offered for NEW bot creation. A registered driver NOT in this set
- * stays fully functional (getDriver resolves it, existing bots keep running) —
- * it's just not advertised, so it can't be picked in the create-bot UI/API.
- * This is a POLICY (what's open to selection), deliberately kept separate from
- * the driver registry (what exists) in drivers/index.ts. Filtering happens at
- * the single advertise point, `detectRuntimes`.
- * Hidden 2026-08-05 (Gus): antigravity/copilot/gemini/kimi unverified.
- */
-const SELECTABLE_RUNTIMES: ReadonlySet<RuntimeId> = new Set(["claude", "codex", "opencode", "pi", "cursor"]);
/* ------------------------------------------------------------------ */
/* Agent CLI path resolution */
@@ -121,25 +109,24 @@ export interface RuntimeInfo {
* plans/community-machine-presence-fix.md.
*/
export async function detectRuntimes(): Promise<RuntimeInfo[]> {
- // Advertise only the selectable subset (SELECTABLE_RUNTIMES). Hidden runtimes
- // stay registered (getDriver resolves them for existing bots on resume) but
- // are never advertised, so the create-bot UI + API won't offer/accept them.
- const ids = listRuntimeIds().filter((id) => SELECTABLE_RUNTIMES.has(id));
+ const ids = listRuntimeIds();
const results: RuntimeInfo[] = [];
const nowIso = new Date().toISOString();
for (const id of ids) {
try {
const driver = getDriver(id);
- const probe: ProbeResult = await driver.probe();
- const healthy = probe.status === "healthy";
- results.push({
- id,
- status: healthy ? "healthy" : "unhealthy",
- version: probe.version,
- lastError: healthy ? undefined : probe.lastError ?? "probe_failed",
- lastErrorAt: healthy ? undefined : nowIso,
- });
+ const probe = await driver.probe();
+ if (probe.status === "healthy") {
+ results.push({ id, status: "healthy", version: probe.version });
+ } else {
+ results.push({
+ id,
+ status: "unhealthy",
+ lastError: probe.error.code ?? "probe_failed",
+ lastErrorAt: nowIso,
+ });
+ }
} catch (err) {
results.push({
id,
diff --git a/src/daemon/src/drivers/antigravity.ts b/src/daemon/src/drivers/antigravity.ts
deleted file mode 100644
index 6db59714f..000000000
--- a/src/daemon/src/drivers/antigravity.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * Antigravity driver — per-turn, PLAIN-TEXT output, no steering.
- *
- * The odd one out: `agy --print --print-timeout <t> --dangerously-skip-permissions`
- * emits plain text, not JSON. The normalizer treats every non-empty line as a
- * `text` event unless it matches an error pattern. Models are suggestion-only
- * (not passed at launch). The prompt is written to stdin then closed.
- */
-import { randomUUID } from "crypto";
-import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
-import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { spawnAgentProcess } from "../runtime/killTree.js";
-import { writeToStdinAndDetach } from "./utils.js";
-
-const ERROR_LINE_PATTERNS: RegExp[] = [/^error[:\s]/i, /\bfatal\b/i, /\bpanic\b/i, /unable to/i];
-
-/**
- * Wall-clock cap for a single Antigravity print run — chosen high because the
- * `agy` binary uses per-turn spawn and its own long-form reasoning routinely
- * runs many minutes on heavy inputs; 30m is the ceiling we're comfortable
- * letting a single turn hold before we assume it's wedged.
- */
-const ANTIGRAVITY_PRINT_TIMEOUT = "30m";
-
-export function buildAntigravityArgs(ctx: LaunchContext): string[] {
- const args = ["--print", "--print-timeout", ANTIGRAVITY_PRINT_TIMEOUT, "--dangerously-skip-permissions"];
- // `agy` has no by-id resume — the only resume flag is `--continue`, which
- // follows the most recent session in cwd. We compensate by stashing
- // `ctx.config.sessionId` in `this.sessionId` so the daemon still records the
- // logical id, but the CLI itself will re-attach to whatever ran last.
- // Reflected in `capabilities.sessionResumeMode = "most-recent"`.
- if (ctx.config.sessionId) args.push("--continue");
- return args;
-}
-
-export class AntigravityDriver implements Driver {
- readonly id = "antigravity";
- readonly lifecycle = {
- kind: "per_turn",
- start: "immediate",
- exit: "natural",
- inFlightWake: "spawn_new",
- } as const;
- readonly session = { recovery: "resume_or_fresh" } as const;
- readonly model = {
- detectedModelsVerifiedAs: "suggestion_only",
- toLaunchSpec: (_modelId: string) => ({ args: [] }),
- } as const;
-
-
- readonly capabilities = {
- reasoningEffort: false,
- fastMode: false,
- disallowedTools: false,
- command: true,
- sessionResumeMode: "most-recent",
- } as const;
-
- private sessionId: string | null = null;
- private sentInit = false;
-
- probe() {
- return probeCliRuntime("agy");
- }
-
- async spawn(ctx: LaunchContext): Promise<SpawnResult> {
- this.sessionId = ctx.config.sessionId ?? randomUUID();
- this.sentInit = false;
- const { spawnEnv } = await prepareCliTransport(ctx, {
- // Antigravity is sensitive to inherited SSH context — clear it.
- SSH_CLIENT: "",
- SSH_CONNECTION: "",
- SSH_TTY: "",
- });
- // Cross-platform spawn: on Windows the agy entry is often a `.cmd`
- // shim, which `child_process.spawn` can't exec without a shell.
- const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
- const spec = resolveSpawnSpec("agy", buildAntigravityArgs(ctx), override);
- const proc = spawnAgentProcess(spec.command, spec.args, {
- cwd: ctx.workingDirectory,
- env: spawnEnv,
- shell: spec.shell,
- });
- writeToStdinAndDetach(proc, ctx.prompt);
- return { process: proc };
- }
-
- parseLine(line: string): ParsedEvent[] {
- const trimmed = line.trim();
- if (!trimmed) return [];
- const out: ParsedEvent[] = [];
- if (!this.sentInit) {
- this.sentInit = true;
- out.push({ kind: "session_init", sessionId: this.sessionId! });
- }
- if (ERROR_LINE_PATTERNS.some((re) => re.test(trimmed))) out.push({ kind: "error", message: trimmed });
- else out.push({ kind: "text", text: line });
- return out;
- }
-
- get currentSessionId(): string | null {
- return this.sessionId;
- }
-
- encodeStdinMessage(): string | null {
- return null;
- }
-
- buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config);
- }
-}
diff --git a/src/daemon/src/drivers/capabilities.test.ts b/src/daemon/src/drivers/capabilities.test.ts
deleted file mode 100644
index 3cac0acdc..000000000
--- a/src/daemon/src/drivers/capabilities.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { getDriver, listRuntimeIds, type RuntimeId } from "./index";
-import type { DriverCapabilities } from "../types";
-
-/**
- * Every driver declares which `RuntimeConfig` fields it actually consumes,
- * per the plan's capability matrix. This test pins that declaration so a
- * silent drift (e.g. someone adds `reasoningEffort` to a driver's `buildArgs`
- * without updating `capabilities`) trips CI.
- */
-const EXPECTED: Record<RuntimeId, DriverCapabilities> = {
- claude: { reasoningEffort: true, fastMode: true, disallowedTools: true, command: true, sessionResumeMode: "by-id" },
- codex: { reasoningEffort: true, fastMode: true, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
- kimi: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
- gemini: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
- copilot: { reasoningEffort: true, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
- cursor: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
- opencode: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
- antigravity: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "most-recent" },
- pi: { reasoningEffort: true, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
-};
-
-describe("driver.capabilities", () => {
- it.each(listRuntimeIds())("%s declares the expected capability record", (id) => {
- const driver = getDriver(id);
- expect(driver.capabilities).toEqual(EXPECTED[id]);
- });
-});
diff --git a/src/daemon/src/drivers/claude.ts b/src/daemon/src/drivers/claude.ts
deleted file mode 100644
index 08dc29d30..000000000
--- a/src/daemon/src/drivers/claude.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * Claude Code driver — persistent, stream-json, gated steering.
- *
- * Lifecycle: one long-lived process per session. stdin is a stream-json NDJSON
- * channel; the initial prompt and every subsequent message are written as
- * `{type:"user", message:{role:"user", content:[{type:"text",text}]}}` lines.
- * Because mid-stream injection can collide with signed thinking blocks, busy
- * delivery is `gated` — held until a safe boundary (see runtime/apmStateMachine).
- */
-import type { Driver, EncodeOpts, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
-import { prepareCliTransport, buildCliTransportSystemPrompt, DEFAULT_CLI_CONFIG } from "./cliTransport.js";
-import { buildClaudeProviderIsolationEnv } from "./claudeProviderIsolation.js";
-import { buildClaudeArgs } from "./claudeLaunch.js";
-import { ClaudeEventNormalizer } from "./claudeEventNormalizer.js";
-import { probeClaude, resolveSpawnSpec, resolveClaudeCommand } from "./probe.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { spawnAgentProcess } from "../runtime/killTree.js";
-
-export class ClaudeDriver implements Driver {
- readonly id = "claude";
- readonly lifecycle = { kind: "persistent", stdin: "gated", inFlightWake: "queue" } as const;
- readonly session = { recovery: "resume_or_fresh" } as const;
- readonly model = {
- detectedModelsVerifiedAs: "launchable",
- toLaunchSpec: (modelId: string) => ({ args: ["--model", modelId] }),
- } as const;
-
- readonly supportsNativeStandingPrompt = true;
-
- readonly capabilities = {
- reasoningEffort: true,
- fastMode: true,
- disallowedTools: true,
- command: true,
- sessionResumeMode: "by-id",
- } as const;
-
- private readonly eventNormalizer = new ClaudeEventNormalizer();
-
- probe() {
- return probeClaude();
- }
-
- async spawn(ctx: LaunchContext): Promise<SpawnResult> {
- const cliConfig = ctx.agentCliPath
- ? { ...DEFAULT_CLI_CONFIG, hostCliPath: ctx.agentCliPath }
- : undefined;
- // prepareCliTransport writes AGENTS.md (+ CLAUDE.md symlink) into the
- // workdir as part of the shared transport setup — Claude Code auto-reads
- // CLAUDE.md from cwd, no CLI flag needed.
- const { spawnEnv } = await prepareCliTransport(ctx, buildClaudeProviderIsolationEnv(ctx), cliConfig);
- const args = buildClaudeArgs(ctx.config);
-
- // Let Claude detect it is NOT nested in another Claude Code session.
- delete spawnEnv.CLAUDECODE;
-
- // Claude has an extra bespoke discovery step (macOS `.app` bundle
- // fallback via `resolveClaudeCommand`) that no other driver needs, but
- // the spawn spec itself is the same as everyone else's. `runtimeConfig.command`
- // wins over the discovered path when set (uniform across drivers).
- //
- // The discovery probe stays lazy: `resolveClaudeCommand` shells out to
- // `which`/`where` (up to PROBE_TIMEOUT_MS), so when the user pinned an
- // explicit `command` we must not pay for — or block on — a lookup whose
- // result `resolveSpawnSpec` would immediately discard.
- //
- // Both branches feed the chosen path through `resolveSpawnSpec`'s override
- // slot, whose "already looks like a path → don't re-resolve" rule keeps us
- // from PATH-probing a path `resolveClaudeCommand` just resolved.
- const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command?.trim();
- const claudeCommand = override || resolveClaudeCommand() || "claude";
- const spec = resolveSpawnSpec("claude", args, claudeCommand);
- const proc = spawnAgentProcess(spec.command, spec.args, {
- cwd: ctx.workingDirectory,
- env: spawnEnv,
- shell: spec.shell,
- });
-
- // Deliver the initial prompt as the first stream-json line.
- const stdinMsg = JSON.stringify({
- type: "user",
- message: { role: "user", content: [{ type: "text", text: ctx.prompt }] },
- ...(ctx.config.sessionId ? { session_id: ctx.config.sessionId } : {}),
- });
- proc.stdin?.write(stdinMsg + "\n");
-
- return { process: proc };
- }
-
- parseLine(line: string): ParsedEvent[] {
- return this.eventNormalizer.normalizeLine(line);
- }
-
- get currentSessionId(): string | null {
- return this.eventNormalizer.currentSessionId;
- }
-
- /** Both idle and busy messages use the same stream-json user-message shape. */
- encodeStdinMessage(text: string, sessionId: string | null, _opts?: EncodeOpts): string {
- return JSON.stringify({
- type: "user",
- message: { role: "user", content: [{ type: "text", text }] },
- ...(sessionId ? { session_id: sessionId } : {}),
- });
- }
-
- buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config);
- }
-}
diff --git a/src/daemon/src/drivers/cliTransport.test.ts b/src/daemon/src/drivers/cliTransport.test.ts
deleted file mode 100644
index 8c56611ef..000000000
--- a/src/daemon/src/drivers/cliTransport.test.ts
+++ /dev/null
@@ -1,351 +0,0 @@
-import { describe, it, expect, afterEach, vi } from "vitest";
-import * as fs from "fs";
-import * as os from "os";
-import * as path from "path";
-import { prepareCliTransport, type CliTransportConfig } from "./cliTransport";
-import { CredentialBroker } from "../credentials/credentialProxy";
-import type { LaunchContext } from "../types";
-import { makeRuntimeConfig } from "../runtimeConfig";
-
-// The git-identity two-author split reads the HOST owner's `git config`
-// (readHostGitIdentity) at spawn. That would make GIT_AUTHOR_* depend on
-// whatever git identity the test machine happens to have — flaky across
-// dev/CI. Mock the read to a controllable value; keep buildGitIdentityEnv
-// real. Hoisted vi.mock is file-scoped (no cross-file leak). Default: no host
-// identity → agent is both author+committer (the pre-two-author behavior the
-// existing assertions expect); the two-author test overrides it.
-const mockReadHostGitIdentity = vi.fn<() => { name?: string; email?: string } | null>(() => null);
-vi.mock("./gitIdentityEnv.js", async (importActual) => {
- const actual = await importActual<typeof import("./gitIdentityEnv.js")>();
- return { ...actual, readHostGitIdentity: () => mockReadHostGitIdentity() };
-});
-
-const tmpDirs: string[] = [];
-function mkTmp(): string {
- const d = fs.mkdtempSync(path.join(os.tmpdir(), "clitransport-"));
- tmpDirs.push(d);
- return d;
-}
-afterEach(() => {
- for (const d of tmpDirs.splice(0)) fs.rmSync(d, { recursive: true, force: true });
-});
-
-function broker(): CredentialBroker {
- return new CredentialBroker({
- upstreamBaseUrl: "https://upstream.test",
- voucherDir: mkTmp(),
- });
-}
-
-function baseCtx(workingDirectory: string, overrides: Partial<LaunchContext> = {}): LaunchContext {
- return {
- agentId: "agent_1",
- launchId: "launch_1",
- workingDirectory,
- standingPrompt: "",
- prompt: "",
- credentialProxy: { broker: broker(), proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] },
- config: {},
- // These transport tests aren't exercising the agent-CLI shim (no
- // agentCliPath), so opt into the mock path — otherwise prepareCliTransport
- // now fails loud on a real launch with no resolvable host CLI.
- mockCliTransport: true,
- ...overrides,
- };
-}
-
-describe("prepareCliTransport — layered spawn env", () => {
- it("throws without a credential proxy (no plaintext fallback)", async () => {
- const ctx = baseCtx(mkTmp());
- delete (ctx as { credentialProxy?: unknown }).credentialProxy;
- await expect(prepareCliTransport(ctx, {}, undefined, "linux")).rejects.toThrow(/credentialProxy is required/);
- });
-
- it("throws a legible error when credentialProxy.capabilities is undefined (wiring bug)", async () => {
- const ctx = baseCtx(mkTmp(), {
- credentialProxy: {
- broker: broker(),
- proxyUrl: "http://127.0.0.1:9/proxy",
- runnerKey: "sk_agent_test",
- } as unknown as LaunchContext["credentialProxy"],
- });
- await expect(prepareCliTransport(ctx, {}, undefined, "linux")).rejects.toThrow(
- /credentialProxy\.capabilities is required/,
- );
- });
-
- it("throws when a capability entry contains a comma (would silently widen scope)", async () => {
- const ctx = baseCtx(mkTmp(), {
- credentialProxy: {
- broker: broker(),
- proxyUrl: "http://127.0.0.1:9/proxy",
- runnerKey: "sk_agent_test",
- capabilities: ["send,read"],
- },
- });
- await expect(prepareCliTransport(ctx, {}, undefined, "linux")).rejects.toThrow(
- /contains a comma/,
- );
- });
-
- it("accepts an empty capabilities array (legitimate zero-capability launch)", async () => {
- const cred = broker();
- const { spawnEnv, tokenFile } = await prepareCliTransport(
- baseCtx(mkTmp(), {
- credentialProxy: {
- broker: cred,
- proxyUrl: "http://127.0.0.1:9/proxy",
- runnerKey: "sk_agent_test",
- capabilities: [],
- },
- }),
- {},
- undefined,
- "linux",
- );
- // capabilities.join(",") on an empty array = "" → the env var is present
- // but empty, and the proxy reads that as "no capabilities granted".
- expect(spawnEnv.ALOOK_ACTIVE_CAPABILITIES).toBe("");
- // The minted voucher must reject every capability check (the Set is empty).
- const voucher = fs.readFileSync(tokenFile, "utf8");
- expect(cred.check(`Bearer ${voucher}`, "send").ok).toBe(false);
- expect(cred.check(`Bearer ${voucher}`, "attach").ok).toBe(false);
- });
-
- it("prepends the per-launch bin dir to PATH", async () => {
- const wd = mkTmp();
- const { spawnEnv, stateDir } = await prepareCliTransport(baseCtx(wd), {}, undefined, "linux");
- const first = (spawnEnv.PATH ?? "").split(path.delimiter)[0];
- expect(first).toBe(path.join(stateDir, "bin"));
- });
-
- it("injects the typed <PREFIX>_* contract + voucher path", async () => {
- const { spawnEnv, tokenFile } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
- expect(spawnEnv.ALOOK_ID).toBe("agent_1");
- expect(spawnEnv.ALOOK_CLI).toBe("alook");
- expect(spawnEnv.ALOOK_LAUNCH_ID).toBe("launch_1");
- expect(spawnEnv.ALOOK_PROXY_URL).toBe("http://127.0.0.1:9/proxy");
- expect(spawnEnv.ALOOK_PROXY_TOKEN_FILE).toBe(tokenFile);
- });
-
- it("provider-derived keys (protected) survive a colliding driver/user env", async () => {
- const ctx = baseCtx(mkTmp(), {
- config: {
- runtimeConfig: makeRuntimeConfig({
- runtime: "claude",
- provider: { kind: "custom", apiUrl: "https://endpoint.test", apiKey: "sk_provider" },
- }),
- },
- });
- // A driver layer trying to shadow the provider key must NOT win.
- const { spawnEnv } = await prepareCliTransport(ctx, { ANTHROPIC_API_KEY: "sk_spoofed" }, undefined, "linux");
- expect(spawnEnv.ANTHROPIC_BASE_URL).toBe("https://endpoint.test");
- expect(spawnEnv.ANTHROPIC_API_KEY).toBe("sk_provider");
- });
-
- it("driver extraEnv (e.g. NO_COLOR) still applies when it doesn't collide", async () => {
- const { spawnEnv } = await prepareCliTransport(baseCtx(mkTmp()), { NO_COLOR: "1" }, undefined, "linux");
- expect(spawnEnv.NO_COLOR).toBe("1");
- });
-
- it("sets NO_COLOR=1 and FORCE_COLOR=0 by default, even without a driver setting them", async () => {
- const { spawnEnv } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
- expect(spawnEnv.NO_COLOR).toBe("1");
- expect(spawnEnv.FORCE_COLOR).toBe("0");
- });
-
- it("sets NO_PROXY for loopback", async () => {
- const { spawnEnv } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
- expect(spawnEnv.NO_PROXY).toContain("127.0.0.1");
- expect(spawnEnv.NO_PROXY).toContain("localhost");
- });
-
- it("injects per-agent GIT_AUTHOR_*/GIT_COMMITTER_* from the agent identity", async () => {
- const ctx = baseCtx(mkTmp(), {
- agentId: "a3f90c21beef",
- config: { agentName: "Melisa", agentDiscriminator: "1043" },
- });
- const { spawnEnv } = await prepareCliTransport(ctx, {}, undefined, "linux");
- expect(spawnEnv.GIT_AUTHOR_NAME).toBe("Melisa");
- expect(spawnEnv.GIT_AUTHOR_EMAIL).toBe("[email protected]");
- expect(spawnEnv.GIT_COMMITTER_NAME).toBe("Melisa");
- expect(spawnEnv.GIT_COMMITTER_EMAIL).toBe(spawnEnv.GIT_AUTHOR_EMAIL);
- });
-
- it("falls back to a valid generic git identity when no agent name/discriminator is set", async () => {
- // config: {} (baseCtx default) — degraded/unknown-bot spawn with no name
- // and no discriminator, so identity falls back to the generic value.
- const { spawnEnv } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
- expect(spawnEnv.GIT_AUTHOR_NAME).toBe("Alook Agent");
- expect(spawnEnv.GIT_AUTHOR_EMAIL).toBe("[email protected]");
- expect(spawnEnv.GIT_AUTHOR_NAME).not.toBe("");
- });
-
- it("a driver trying to spoof GIT_AUTHOR_NAME does NOT win (gitIdentity precedence 35 > driver 30)", async () => {
- const ctx = baseCtx(mkTmp(), {
- agentId: "a3f90c21beef",
- config: { agentName: "Melisa", agentDiscriminator: "1043" },
- });
- const { spawnEnv } = await prepareCliTransport(ctx, { GIT_AUTHOR_NAME: "Someone Else" }, undefined, "linux");
- expect(spawnEnv.GIT_AUTHOR_NAME).toBe("Melisa");
- });
-
- it("two-author: host owner git identity ⇒ AUTHOR = owner, COMMITTER = agent", async () => {
- mockReadHostGitIdentity.mockReturnValueOnce({ name: "Gus", email: "[email protected]" });
- const ctx = baseCtx(mkTmp(), {
- agentId: "a3f90c21beef",
- config: { agentName: "Melisa", agentDiscriminator: "1043" },
- });
- const { spawnEnv } = await prepareCliTransport(ctx, {}, undefined, "linux");
- // Author = the human owner (they wrote it), committer = the agent.
- expect(spawnEnv.GIT_AUTHOR_NAME).toBe("Gus");
- expect(spawnEnv.GIT_AUTHOR_EMAIL).toBe("[email protected]");
- expect(spawnEnv.GIT_COMMITTER_NAME).toBe("Melisa");
- expect(spawnEnv.GIT_COMMITTER_EMAIL).toBe("[email protected]");
- });
-
- it("creates a symlink when hostCliPath is set", async () => {
- const wd = mkTmp();
- const host = path.join(wd, "real.js");
- fs.writeFileSync(host, "#!/usr/bin/env node\n", { mode: 0o755 });
- const cli: CliTransportConfig = { cliName: "alook", envPrefix: "ALOOK", stateDirName: ".alook", hostCliPath: host };
- const { stateDir } = await prepareCliTransport(baseCtx(wd), {}, cli, "linux");
- const link = path.join(stateDir, "bin", "alook");
- expect(fs.lstatSync(link).isSymbolicLink()).toBe(true);
- });
-
- it("defaults hostCliPath from ctx.agentCliPath — the shim works with the default cli config (no per-driver plumbing)", async () => {
- const wd = mkTmp();
- const host = path.join(wd, "agent-cli.js");
- fs.writeFileSync(host, "#!/usr/bin/env node\n", { mode: 0o755 });
- // No explicit cli.hostCliPath; agentCliPath on the ctx is the only source —
- // this is the path codex/cursor/opencode/etc. now get for free.
- const { stateDir } = await prepareCliTransport(
- baseCtx(wd, { agentCliPath: host, mockCliTransport: false }),
- {},
- undefined,
- "linux",
- );
- const link = path.join(stateDir, "bin", "alook");
- expect(fs.lstatSync(link).isSymbolicLink()).toBe(true);
- expect(fs.realpathSync(link)).toBe(fs.realpathSync(host));
- });
-
- it("FAILS LOUD on a real launch with no resolvable host CLI (not a silent empty bin)", async () => {
- // The bug shape: a real launch (not mock) whose agentCliPath didn't resolve.
- // Must throw, not silently leave an empty bin that PATH-falls-through to the
- // host `alook` (which lacks the agent subcommands).
- await expect(
- prepareCliTransport(baseCtx(mkTmp(), { agentCliPath: undefined, mockCliTransport: false }), {}, undefined, "linux"),
- ).rejects.toThrow(/no host CLI path/);
- });
-
- it("mock launch (mockCliTransport) stays silent — bin dir, no link, no throw", async () => {
- const { stateDir } = await prepareCliTransport(
- baseCtx(mkTmp(), { agentCliPath: undefined, mockCliTransport: true }),
- {},
- undefined,
- "linux",
- );
- const binDir = path.join(stateDir, "bin");
- expect(fs.existsSync(binDir)).toBe(true);
- expect(fs.existsSync(path.join(binDir, "alook"))).toBe(false);
- });
-
- it("revokes the agent's previous voucher before minting a new one on respawn", async () => {
- // Without this, every stop+respawn of the same agent leaves the OLD
- // voucher registered forever — an unbounded leak in the broker's map,
- // since revoke/revokeAgent is never called anywhere else in production
- // code (see plans/fix-credential-proxy-connection-leak.md).
- const cred = broker();
- const first = await prepareCliTransport(
- baseCtx(mkTmp(), { credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] } }),
- {},
- undefined,
- "linux",
- );
- expect(cred.size).toBe(1);
- const firstVoucher = fs.readFileSync(first.tokenFile, "utf8");
- expect(cred.check(`Bearer ${firstVoucher}`).ok).toBe(true);
-
- const second = await prepareCliTransport(
- baseCtx(mkTmp(), { credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] } }),
- {},
- undefined,
- "linux",
- );
-
- // Still exactly one live registration for this agent — the old one was
- // revoked, not left dangling, regardless of how many times it respawns.
- expect(cred.size).toBe(1);
- expect(cred.check(`Bearer ${firstVoucher}`).ok).toBe(false);
- const secondVoucher = fs.readFileSync(second.tokenFile, "utf8");
- expect(cred.check(`Bearer ${secondVoucher}`).ok).toBe(true);
- });
-
- it("mints the voucher with the capability set from the handoff", async () => {
- const cred = broker();
- const { tokenFile } = await prepareCliTransport(
- baseCtx(mkTmp(), {
- credentialProxy: {
- broker: cred,
- proxyUrl: "http://127.0.0.1:9/proxy",
- runnerKey: "sk_agent_test",
- capabilities: ["attach"],
- },
- }),
- {},
- undefined,
- "linux",
- );
- const voucher = fs.readFileSync(tokenFile, "utf8");
- expect(cred.check(`Bearer ${voucher}`, "attach").ok).toBe(true);
- expect(cred.check(`Bearer ${voucher}`, "send").ok).toBe(false);
- });
-
- it("does not revoke a DIFFERENT agent's voucher on respawn", async () => {
- const cred = broker();
- await prepareCliTransport(
- baseCtx(mkTmp(), {
- agentId: "agent_1",
- credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] },
- }),
- {},
- undefined,
- "linux",
- );
- await prepareCliTransport(
- baseCtx(mkTmp(), {
- agentId: "agent_2",
- credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] },
- }),
- {},
- undefined,
- "linux",
- );
- expect(cred.size).toBe(2);
- });
-});
-
-describe("prepareCliTransport — unified AGENTS.md packing", () => {
- it("writes AGENTS.md (+ CLAUDE.md symlink) into the workdir when standingPrompt is non-empty", async () => {
- const wd = mkTmp();
- await prepareCliTransport(baseCtx(wd, { standingPrompt: "You are an AI agent." }), {}, undefined, "linux");
- expect(fs.readFileSync(path.join(wd, "AGENTS.md"), "utf-8")).toBe("You are an AI agent.");
- expect(fs.lstatSync(path.join(wd, "CLAUDE.md")).isSymbolicLink()).toBe(true);
- });
-
- it("does not write AGENTS.md when standingPrompt is empty", async () => {
- const wd = mkTmp();
- await prepareCliTransport(baseCtx(wd), {}, undefined, "linux");
- expect(fs.existsSync(path.join(wd, "AGENTS.md"))).toBe(false);
- });
-
- it("every child-process driver gets the same file regardless of its own delivery mechanism", async () => {
- // Simulates what claude/kimi/codex/gemini/etc. all do: call prepareCliTransport
- // with a real standingPrompt before their driver-specific spawn logic.
- const wd = mkTmp();
- await prepareCliTransport(baseCtx(wd, { standingPrompt: "standing prompt content" }), { NO_COLOR: "1" }, undefined, "linux");
- expect(fs.readFileSync(path.join(wd, "AGENTS.md"), "utf-8")).toBe("standing prompt content");
- });
-});
diff --git a/src/daemon/src/drivers/cliTransport.ts b/src/daemon/src/drivers/cliTransport.ts
deleted file mode 100644
index 85faeef1c..000000000
--- a/src/daemon/src/drivers/cliTransport.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-/**
- * Shared CLI transport — the common launch scaffolding for every CLI-style
- * runtime (Claude, Codex, Gemini, Kimi, Copilot, Cursor, OpenCode, Antigravity).
- *
- * The runtime child process talks back to its host platform through a small
- * **Alook CLI**, reached purely via the exec environment (PATH + env vars). The
- * agent always invokes a stable `cliName`; a per-launch link in a PATH-prepended
- * bin dir points it at the host's real `hostCliPath` (POSIX symlink / Windows
- * `.cmd` shim — see `cliLink.ts`), so the host binary can be renamed/relocated
- * without touching the agent-facing surface, and no forwarding script is written
- * on POSIX.
- *
- * This module is deliberately host-agnostic: it ships an Alook-branded, swappable
- * CLI config (`alook` name + `ALOOK_*` env contract, no real `hostCliPath`). A
- * real deployment passes its own `CliTransportConfig` — the backend never
- * hardcodes any particular platform.
- *
- * `prepareCliTransport` builds the spawn environment from explicit layers (see
- * `spawnEnv.ts`) so override precedence is data, not spread order; the child can:
- * - invoke the stable `cliName` (link → host `hostCliPath`) via PATH,
- * - authenticate back to the host, and
- * - see the neutral `<PREFIX>_*` runtime-context env vars.
- *
- * It also writes the assembled standing prompt as `AGENTS.md` (+ `CLAUDE.md`
- * symlink) into the agent's workdir — the ONE packing step every child-process
- * driver relies on, mirroring `src/cli/daemon/execenv/index.ts`'s
- * `writeInstructionFileIfChanged`, which does the same thing unconditionally
- * regardless of which runtime is about to be spawned. Every mainstream
- * coding-agent CLI this backend drives (Claude Code, Codex, Kimi, OpenCode,
- * Gemini, Cursor, Copilot, Antigravity) auto-reads `AGENTS.md`/`CLAUDE.md`
- * from cwd, so no driver needs its own bespoke delivery channel — there is
- * exactly one packing mechanism, not nine. (`pi` is the sole exception: it
- * runs in-process with no child process, so it doesn't go through
- * `prepareCliTransport` at all — it calls `writeAgentFile` directly with the
- * same file, for the same reason: its SDK auto-reads `AGENTS.md` from cwd.)
- *
- * AUTH IS ZERO-TRUST ONLY. The host must pass `ctx.credentialProxy` (a running
- * `CredentialBroker` + proxy URL); the transport mints a per-launch voucher and
- * injects `<PREFIX>_PROXY_URL` + `<PREFIX>_PROXY_TOKEN_FILE` as a sensitive layer.
- * The real key never enters the child's environment. There is no plaintext
- * fallback — without a credential proxy, `prepareCliTransport` throws. See
- * `src/credentials`.
- */
-import * as fs from "fs";
-import * as path from "path";
-import type { LaunchContext, LaunchConfig } from "../types.js";
-import { buildCliSystemPrompt } from "./systemPrompt.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { writeCliLink } from "./cliLink.js";
-import { mergeEnvLayers, platformEnv, runtimeContextEnv, type EnvLayer } from "./spawnEnv.js";
-import { buildGitIdentityEnv, readHostGitIdentity } from "./gitIdentityEnv.js";
-import { writeAgentFile } from "./agentFile.js";
-
-export interface PreparedCliTransport {
- /** Per-launch state directory created under the working directory. */
- stateDir: string;
- /**
- * Path to the credential file the child reads — the per-launch `vch_` voucher
- * (never the real key). The child sends it to the proxy, which swaps in the key.
- */
- tokenFile: string;
- spawnEnv: NodeJS.ProcessEnv;
-}
-
-/**
- * Host-supplied knobs for the CLI transport.
- *
- * The transport places a per-launch link named `cliName` in a `bin` dir and
- * prepends that dir to PATH. The agent always invokes the same stable name
- * (`cliName`, default `alook`); on POSIX the link is a symlink to `hostCliPath`,
- * on Windows a `.cmd` shim. This **decouples the agent-facing CLI name from the
- * host's real binary name** — the backend's prompts/contract never depend on what
- * the host actually calls its CLI, and the host can rename or relocate its binary
- * without touching the agent surface.
- */
-export interface CliTransportConfig {
- /** Stable command name the agent invokes (the link's filename). */
- cliName: string;
- /** Prefix for injected env vars, e.g. "ALOOK" → ALOOK_ID, ALOOK_PROXY_TOKEN_FILE. */
- envPrefix: string;
- /** Name of the per-launch state directory under the working directory. */
- stateDirName: string;
- /**
- * Absolute path to the host's real agent CLI entrypoint the link points at.
- * Decoupled from `cliName`. On POSIX it MUST be a self-executable entrypoint
- * (shebang + executable bit — an npm `bin` symlink satisfies this); a host that
- * needs an interpreter prefix (`node script.js`) must ship its own self-exec
- * wrapper and pass that here. When omitted (the mock), no link is created and
- * `cliName` won't resolve.
- */
- hostCliPath?: string;
- /** Extra static env vars the host wants every runtime to see. */
- extraEnv?: Record<string, string>;
-}
-
-/**
- * The default Alook CLI config template. No `hostCliPath` is wired — a real
- * deployment overrides it with `{ ...DEFAULT_CLI_CONFIG, hostCliPath }`.
- */
-export const DEFAULT_CLI_CONFIG: CliTransportConfig = {
- cliName: "alook",
- envPrefix: "ALOOK",
- stateDirName: ".alook",
-};
-
-function resolveStateHome(envPrefix: string): string {
- return (
- process.env[`${envPrefix}_HOME`] ||
- path.join(process.env.HOME || process.env.USERPROFILE || ".", `.${envPrefix.toLowerCase()}`)
- );
-}
-
-/**
- * Prepare the launch transport for a runtime child process.
- *
- * Creates a per-launch state dir + token file + a `bin/<cliName>` link (POSIX
- * symlink / Windows `.cmd` shim) prepended to PATH, so the agent always invokes
- * the stable `cliName` while the host's real `hostCliPath` stays decoupled behind
- * it. `spawnEnv` is assembled from explicit, precedence-ordered layers (see
- * `spawnEnv.ts`): base → host static → user env → driver → platform contract →
- * runtime context → network → provider-protected → credential (sensitive).
- *
- * @param ctx launch context (agent id, working dir, config, …)
- * @param extraEnv runtime-specific extra env (e.g. `{ NO_COLOR: "1" }`)
- * @param cli CLI transport config (defaults to the Alook mock config)
- * @param platform override for testing; defaults to process.platform
- */
-export async function prepareCliTransport(
- ctx: LaunchContext,
- extraEnv: NodeJS.ProcessEnv = {},
- cli: CliTransportConfig = DEFAULT_CLI_CONFIG,
- platform: NodeJS.Platform = process.platform,
-): Promise<PreparedCliTransport> {
- const E = cli.envPrefix;
- const stateHome = resolveStateHome(E);
- const stateDir = path.join(ctx.workingDirectory, cli.stateDirName);
- await fs.promises.mkdir(stateDir, { recursive: true });
-
- // Unified packing step for every child-process driver: write the standing
- // prompt as AGENTS.md (+ CLAUDE.md symlink) so any runtime that auto-reads
- // it from cwd picks it up, with no driver-specific plumbing required.
- if (ctx.standingPrompt) writeAgentFile(ctx.workingDirectory, ctx.standingPrompt);
-
- // Resolve the host CLI the agent-facing `cliName` links to. A caller may set
- // `cli.hostCliPath` explicitly (claude/pi do); otherwise default it from
- // `ctx.agentCliPath` — the daemon threads the resolved agent-CLI path there
- // for EVERY launch, so this one fallback gives all child-process drivers the
- // shim without each repeating claude's construction (the omission that left
- // codex/cursor/opencode/… invoking the HOST `alook`, which lacks the agent
- // subcommands). Explicit `cli.hostCliPath` still wins.
- const hostCliPath = cli.hostCliPath ?? ctx.agentCliPath;
-
- // Fail loud when a REAL launch can't resolve a host CLI. Silently leaving an
- // empty bin dir lets the agent's `alook` fall through to the host CLI on
- // PATH — the agent looks like it runs but uses the wrong binary, which is
- // very hard to trace. Only an explicit `mockCliTransport` opt-in may skip the
- // shim (test harnesses); the ABSENCE of a path is the bug shape, so it can't
- // double as the mock signal.
- if (!hostCliPath && !ctx.mockCliTransport) {
- throw new Error(
- "prepareCliTransport: no host CLI path — set ctx.agentCliPath (or cli.hostCliPath) " +
- "so the agent's `alook` resolves to the injected agent CLI, not the host binary. " +
- "For an intentional no-CLI test launch, set ctx.mockCliTransport = true.",
- );
- }
-
- // Decouple the agent-facing `cliName` from the host binary via a filesystem
- // link in a PATH-prepended bin dir (symlink on POSIX, .cmd shim on Windows).
- // With no hostCliPath (mock launch) writeCliLink creates only the bin dir.
- const binDir = writeCliLink(stateDir, cli.cliName, hostCliPath, platform);
-
- // Zero-trust credential handoff (no plaintext fallback). The broker mints a
- // per-launch voucher (writing the 0600 voucher file and keeping the real key);
- // the child gets only the proxy URL + voucher path (a sensitive layer below).
- if (!ctx.credentialProxy) {
- throw new Error(
- "prepareCliTransport: ctx.credentialProxy is required — start a credential proxy " +
- "(see src/credentials) and pass { broker, proxyUrl }. There is no plaintext mode.",
- );
- }
- const capabilities = ctx.credentialProxy.capabilities;
- // Guard: `capabilities` must be a real array. `undefined` is a caller wiring
- // bug (typically `{} as CredentialProxyHandoff` in a test) — surface it at
- // spawn time instead of crashing later inside `spawnEnv`'s `capabilities.join(",")`
- // with an opaque "Cannot read properties of undefined (reading 'join')". An
- // empty array IS allowed — that's a legitimate zero-capability launch.
- if (!Array.isArray(capabilities)) {
- throw new Error(
- "prepareCliTransport: credentialProxy.capabilities is required " +
- "(empty array is allowed for zero-capability launches; undefined is a wiring bug)",
- );
- }
- // The proxy uses `,` as the sole separator between capabilities on the wire
- // (`spawnEnv.ts` joins with "," and the proxy re-splits on ","). A capability
- // entry containing a comma would silently widen the enforced scope — reject
- // at wiring time so nobody smuggles in "send,attach" as a single token.
- for (const c of capabilities) {
- if (typeof c !== "string" || c.includes(",")) {
- throw new Error(
- `prepareCliTransport: capability entry ${JSON.stringify(c)} contains a comma ` +
- `(each capability must be a single token; use ["send","read"] instead of ["send,read"])`,
- );
- }
- }
- // Revoke this agent's previous voucher(s) before minting a new one — an
- // agent has at most one live launch at a time, so this bounds the broker's
- // registration map to "one live entry per active agent" regardless of how
- // many times it gets stopped and respawned. Without this, every respawn
- // leaves the old registration behind forever (nothing else in production
- // code ever calls revoke/revokeAgent) — an unbounded memory leak.
- ctx.credentialProxy.broker.revokeAgent(ctx.agentId);
- const reg = ctx.credentialProxy.broker.mint(
- ctx.agentId,
- ctx.launchId ?? "default",
- capabilities,
- ctx.credentialProxy.runnerKey,
- );
- const tokenFile = reg.voucherFile;
-
- const resolved = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
- const pathValue = [binDir, process.env.PATH ?? ""].filter(Boolean).join(path.delimiter);
-
- // Explicit precedence-ordered layers (higher wins; sensitive applied last).
- const layers: EnvLayer[] = [
- { name: "hostStatic", precedence: 10, vars: cli.extraEnv ?? {} },
- { name: "userEnv", precedence: 20, vars: resolved.envVars },
- { name: "driver", precedence: 30, vars: extraEnv as Record<string, string | undefined> },
- // Per-agent git identity (GIT_AUTHOR_*/GIT_COMMITTER_*). Two-author
- // attribution: when the host owner has a git identity, AUTHOR = the owner
- // (they wrote it) and COMMITTER = the agent (it applied it); with no host
- // identity, the agent is both. ENV-ONLY for WRITES — reads the owner's
- // existing `git config user.*` to credit them, but never writes
- // ~/.gitconfig or any repo .git/config, so the owner's git state is
- // untouched. Above `driver` (30) so a driver can't clobber it; below
- // `platformContract` (40) though keys don't overlap. Not sensitive.
- {
- name: "gitIdentity",
- precedence: 35,
- vars: buildGitIdentityEnv({
- agentName: ctx.config.agentName,
- discriminator: ctx.config.agentDiscriminator,
- hostUser: readHostGitIdentity() ?? undefined,
- }),
- },
- {
- name: "platformContract",
- precedence: 40,
- vars: {
- ...platformEnv(E, {
- stateHome,
- agentId: ctx.agentId,
- cliName: cli.cliName,
- // Absolute path to the injected shim (present iff we wrote a link, i.e.
- // hostCliPath resolved). `<PREFIX>_CLI` points here so the agent calls
- // the CLI by absolute path, never a bare name PATH could resolve to a
- // host binary. On a mock launch (no shim) it stays undefined → bare name.
- cliPath: hostCliPath ? path.join(binDir, cli.cliName) : undefined,
- serverUrl: ctx.config.serverUrl,
- capabilities,
- launchId: ctx.launchId,
- traceDir: ctx.cliTransportTraceDir,
- }),
- // Baseline color-off for every runtime CLI: ANSI escapes have no
- // meaning to the stream-json / JSON-RPC parsers on the other side and
- // routinely corrupt event boundaries. Every driver used to hand-set
- // NO_COLOR here — now it's a default all runtimes (including Claude)
- // inherit.
- //
- // A driver CANNOT opt out via its own `extraEnv`: that layer sits at
- // precedence 30, below this one (40), so a driver-supplied value is
- // overwritten here. If some future CLI genuinely misreads NO_COLOR,
- // opt it out by making these two keys conditional on a driver flag —
- // not by setting them in `extraEnv`, which silently does nothing.
- FORCE_COLOR: "0",
- NO_COLOR: "1",
- },
- },
- { name: "runtimeContext", precedence: 50, vars: runtimeContextEnv(E, ctx.config.runtimeContext) },
- {
- name: "network",
- precedence: 60,
- vars: { NO_PROXY: ["127.0.0.1", "localhost", process.env.NO_PROXY].filter(Boolean).join(","), PATH: pathValue },
- },
- // Provider-derived keys: protected so user/driver env can't accidentally
- // shadow them, but not secret enough to redact like the credential voucher.
- { name: "providerProtected", precedence: 70, vars: resolved.providerEnv },
- // Credential voucher path — sensitive: always wins, redacted in provenance.
- {
- name: "credential",
- precedence: 100,
- sensitive: true,
- vars: { [`${E}_PROXY_URL`]: ctx.credentialProxy.proxyUrl, [`${E}_PROXY_TOKEN_FILE`]: tokenFile },
- },
- ];
-
- const { env: spawnEnv } = mergeEnvLayers(process.env, layers);
-
- return { stateDir, tokenFile, spawnEnv };
-}
-
-/** Shared system-prompt entry point for CLI drivers. */
-export function buildCliTransportSystemPrompt(config: LaunchConfig): string {
- return buildCliSystemPrompt(config);
-}
diff --git a/src/daemon/src/drivers/codexEventNormalizer.test.ts b/src/daemon/src/drivers/codexEventNormalizer.test.ts
deleted file mode 100644
index 604f34d2c..000000000
--- a/src/daemon/src/drivers/codexEventNormalizer.test.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-/**
- * Tests for `CodexEventNormalizer` — in particular the tool_call/tool_output
- * symmetry fix from plans/wire-gated-busy-steering-daemon.md (§9c): before
- * this fix, `handleItemCompleted` had no case for `fileChange`, `webSearch`,
- * or `collabAgentToolCall`, so `outstandingToolUses` (tracked by the manager
- * via these `ParsedEvent`s) would permanently increment on the first such
- * item of a turn and never come back down.
- */
-import { describe, it, expect } from "vitest";
-import { CodexEventNormalizer } from "./codexEventNormalizer";
-
-function notify(method: string, params: unknown): string {
- return JSON.stringify({ jsonrpc: "2.0", method, params });
-}
-
-describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
- it("fileChange: item/started then item/completed emits tool_call then tool_output", () => {
- const n = new CodexEventNormalizer();
- const started = n.normalizeLine(notify("item/started", { item: { type: "fileChange" } }));
- expect(started).toEqual([{ kind: "tool_call", name: "file_change", input: {} }]);
-
- const completed = n.normalizeLine(notify("item/completed", { item: { type: "fileChange" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "file_change" }]);
- });
-
- it("fileChange consumes raw changes at the adapter boundary and emits only an ordered-unique flat path", () => {
- const n = new CodexEventNormalizer();
- const started = n.normalizeLine(notify("item/started", {
- item: {
- type: "fileChange",
- changes: [
- { path: " a.ts ", diff: "secret-a" },
- { path: "" },
- { path: 42 },
- { path: "b.ts", content: "secret-b" },
- { path: "a.ts" },
- ],
- path: "ignored-fallback.ts",
- diff: "top-secret",
- content: "top-secret-content",
- },
- }));
-
- expect(started).toEqual([
- { kind: "tool_call", name: "file_change", input: { path: "a.ts, b.ts" } },
- ]);
- expect(JSON.stringify(started)).not.toContain("changes");
- expect(JSON.stringify(started)).not.toContain("secret");
-
- const completed = n.normalizeLine(notify("item/completed", { item: { type: "fileChange" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "file_change" }]);
- });
-
- it("fileChange flattens a legacy top-level path when changes are absent", () => {
- const started = new CodexEventNormalizer().normalizeLine(notify("item/started", {
- item: { type: "fileChange", path: " legacy.ts ", diff: "secret" },
- }));
-
- expect(started).toEqual([
- { kind: "tool_call", name: "file_change", input: { path: "legacy.ts" } },
- ]);
- });
-
- it("fileChange falls back to a valid top-level path when changes contain no valid paths", () => {
- const started = new CodexEventNormalizer().normalizeLine(notify("item/started", {
- item: {
- type: "fileChange",
- changes: [{ path: " " }, { path: 42 }, { diff: "secret" }],
- path: "fallback.ts",
- },
- }));
-
- expect(started).toEqual([
- { kind: "tool_call", name: "file_change", input: { path: "fallback.ts" } },
- ]);
- });
-
- it("webSearch: item/started then item/completed emits tool_call then tool_output", () => {
- const n = new CodexEventNormalizer();
- const started = n.normalizeLine(notify("item/started", { item: { type: "webSearch" } }));
- expect(started).toEqual([{ kind: "tool_call", name: "web_search", input: { type: "webSearch" } }]);
-
- const completed = n.normalizeLine(notify("item/completed", { item: { type: "webSearch" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "web_search" }]);
- });
-
- it("collabAgentToolCall: item/started then item/completed emits tool_call then tool_output", () => {
- const n = new CodexEventNormalizer();
- const started = n.normalizeLine(notify("item/started", { item: { type: "collabAgentToolCall" } }));
- expect(started).toEqual([{ kind: "tool_call", name: "collab_tool_call", input: { type: "collabAgentToolCall" } }]);
-
- const completed = n.normalizeLine(notify("item/completed", { item: { type: "collabAgentToolCall" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "collab_tool_call" }]);
- });
-
- it("commandExecution: item/started then item/completed still pairs correctly (regression — 9b removed markProgress from this handler)", () => {
- const n = new CodexEventNormalizer();
- const started = n.normalizeLine(notify("item/started", { item: { type: "commandExecution" } }));
- expect(started).toEqual([{ kind: "tool_call", name: "shell", input: { type: "commandExecution" } }]);
-
- const completed = n.normalizeLine(notify("item/completed", { item: { type: "commandExecution" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "shell" }]);
- });
-
- it("mcpToolCall: item/started then item/completed still pairs correctly (regression — 9b removed markProgress from this handler)", () => {
- const n = new CodexEventNormalizer();
- const started = n.normalizeLine(notify("item/started", { item: { type: "mcpToolCall", name: "search" } }));
- expect(started).toEqual([
- { kind: "tool_call", name: "mcp_search", input: { type: "mcpToolCall", name: "search" } },
- ]);
-
- const completed = n.normalizeLine(notify("item/completed", { item: { type: "mcpToolCall", name: "search" } }));
- expect(completed).toEqual([{ kind: "tool_output", name: "mcp_search" }]);
- });
-
- it("does not expose canSteerBusy or a turnState field (dead/redundant driver-level gate must not silently reappear)", () => {
- const n = new CodexEventNormalizer();
- expect((n as unknown as { canSteerBusy?: unknown }).canSteerBusy).toBeUndefined();
- expect((n as unknown as { turnState?: unknown }).turnState).toBeUndefined();
- });
-});
-
-describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurnId)", () => {
- it("captures params.turn.id on turn/started and exposes it via currentTurnId", () => {
- const n = new CodexEventNormalizer();
- expect(n.currentTurnId).toBeNull();
- n.normalizeLine(notify("turn/started", { threadId: "th_1", turn: { id: "turn_abc", status: "inProgress" } }));
- expect(n.currentTurnId).toBe("turn_abc");
- });
-
- it("clears the turn id on turn/completed (no live turn to steer after)", () => {
- const n = new CodexEventNormalizer();
- n.normalizeLine(notify("turn/started", { threadId: "th_1", turn: { id: "turn_abc" } }));
- expect(n.currentTurnId).toBe("turn_abc");
- n.normalizeLine(notify("turn/completed", { status: "completed" }));
- expect(n.currentTurnId).toBeNull();
- });
-
- it("clears the turn id on an interrupted/failed turn too", () => {
- const n = new CodexEventNormalizer();
- n.normalizeLine(notify("turn/started", { threadId: "th_1", turn: { id: "turn_x" } }));
- n.normalizeLine(notify("turn/completed", { status: "failed" }));
- expect(n.currentTurnId).toBeNull();
- });
-});
-
-describe("CodexEventNormalizer — session_init dedup (result + thread/started notification)", () => {
- function result(id: string): string {
- return JSON.stringify({ jsonrpc: "2.0", id: 2, result: { thread: { id } } });
- }
- it("emits session_init ONCE for a thread announced twice (result then notification)", () => {
- const n = new CodexEventNormalizer();
- const a = n.normalizeLine(result("th_1"));
- const b = n.normalizeLine(notify("thread/started", { thread: { id: "th_1" } }));
- expect(a.filter((e) => e.kind === "session_init")).toHaveLength(1);
- expect(b.filter((e) => e.kind === "session_init")).toHaveLength(0); // deduped
- // but the id is still adopted regardless of which arrived.
- expect(n.currentSessionId).toBe("th_1");
- });
- it("emits session_init again for a DIFFERENT thread (fresh-thread fallback)", () => {
- const n = new CodexEventNormalizer();
- n.normalizeLine(result("th_1"));
- const fresh = n.normalizeLine(result("th_2")); // e.g. missing-rollout fallback fresh thread
- expect(fresh.filter((e) => e.kind === "session_init")).toHaveLength(1);
- expect(n.currentSessionId).toBe("th_2");
- });
- it("adopts the id from the notification even when the result never emitted it (notification first)", () => {
- const n = new CodexEventNormalizer();
- const b = n.normalizeLine(notify("thread/started", { thread: { id: "th_x" } }));
- expect(b.filter((e) => e.kind === "session_init")).toHaveLength(1);
- expect(n.currentSessionId).toBe("th_x");
- });
-});
diff --git a/src/daemon/src/drivers/codexEventNormalizer.ts b/src/daemon/src/drivers/codexEventNormalizer.ts
deleted file mode 100644
index 1e308943d..000000000
--- a/src/daemon/src/drivers/codexEventNormalizer.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-/**
- * CodexEventNormalizer — maps Codex's JSON-RPC 2.0 app-server protocol into
- * `ParsedEvent`s.
- *
- * Codex speaks JSON-RPC over stdio (`app-server --listen stdio://`). After an
- * `initialize` handshake the daemon starts/resumes a thread; the thread then
- * streams `item/*` and `turn/*` notifications. Session id = the thread id from
- * the `thread/started` (or thread/resume) result.
- *
- * It also folds in two telemetry streams via the sidecar mapper:
- * - `thread/tokenUsage/updated` → cumulative-session token telemetry
- * - `account/rateLimits/updated` → rate-limit telemetry
- */
-import type { ParsedEvent } from "../types.js";
-import { mapCodexTelemetry } from "./codexTelemetrySidecar.js";
-import { tryParseJsonLine } from "./utils.js";
-
-function normalizeFileChangeInput(item: any): { path?: string } {
- const paths: string[] = [];
- const seen = new Set<string>();
- const changePaths = Array.isArray(item?.changes)
- ? item.changes.map((change: any) => change?.path)
- : [];
- for (const candidate of changePaths) {
- if (typeof candidate !== "string") continue;
- const path = candidate.trim();
- if (!path || seen.has(path)) continue;
- seen.add(path);
- paths.push(path);
- }
- if (paths.length === 0 && typeof item?.path === "string") {
- const path = item.path.trim();
- if (path) paths.push(path);
- }
- return paths.length > 0 ? { path: paths.join(", ") } : {};
-}
-
-export class CodexEventNormalizer {
- private threadId: string | null = null;
- /**
- * The active turn's id, from `turn/started`'s `params.turn.id`. Codex requires
- * it as `expectedTurnId` on a `turn/steer` (a busy-steer against the in-flight
- * turn) — without it codex rejects the steer ("missing field expectedTurnId").
- * Set on `turn/started`, cleared on `turn/completed`. Null when no turn is live
- * (then a message is a fresh `turn/start`, which takes no expectedTurnId).
- */
- private turnId: string | null = null;
- /**
- * The threadId we've already emitted `session_init` for — dedups codex's
- * double thread announcement (result + notification). See `adoptAndInit`.
- */
- private sessionInitEmittedFor: string | null = null;
-
- get currentSessionId(): string | null {
- return this.threadId;
- }
-
- /** The in-flight turn's id, or null when no turn is active. */
- get currentTurnId(): string | null {
- return this.turnId;
- }
-
- adoptThreadId(threadId: string | null): void {
- this.threadId = threadId;
- }
-
- /**
- * Emit `session_init` for `threadId` ONLY the first time this thread is seen.
- * Codex announces a thread TWICE — the `thread/start` RESULT and the
- * `thread/started` NOTIFICATION — both carrying the same id. Both must adopt
- * the id (so `currentSessionId` is set no matter which arrives first), but
- * only ONE should surface `session_init`: downstream consumers that RECORD on
- * session_init (the timeline/reset-audit recorder) would otherwise log the
- * event twice — the "two identical reset records for codex only" bug. Other
- * runtimes emit session_init once, hence codex-only. The submit-once prompt
- * latch never needed the duplicate; this dedups at the source.
- */
- private adoptAndInit(threadId: string): ParsedEvent[] {
- const firstSight = threadId !== this.sessionInitEmittedFor;
- this.threadId = threadId;
- if (!firstSight) return [];
- this.sessionInitEmittedFor = threadId;
- return [{ kind: "session_init", sessionId: threadId }];
- }
-
- normalizeLine(line: string): ParsedEvent[] {
- const msg = tryParseJsonLine(line) as any;
- if (!msg) return [];
-
- // JSON-RPC error response.
- if (msg?.error && msg.id !== undefined) {
- return [{ kind: "error", message: msg.error?.message ?? "Codex RPC error" }];
- }
-
- // Result of thread/start | thread/resume carries the thread id.
- if (msg?.result?.thread?.id) {
- return this.adoptAndInit(msg.result.thread.id);
- }
-
- if (msg?.method) return this.handleNotification(msg.method, msg.params ?? {});
- return [];
- }
-
- private handleNotification(method: string, params: any): ParsedEvent[] {
- switch (method) {
- case "thread/started":
- return params?.thread?.id ? this.adoptAndInit(params.thread.id) : [];
-
- case "turn/started":
- // Capture the turn id — codex needs it back as `expectedTurnId` on a
- // `turn/steer` against this turn (see CodexDriver.encodeStdinMessage).
- if (params?.turn?.id) this.turnId = params.turn.id;
- return [{ kind: "thinking", text: "" }];
-
- case "item/reasoning/textDelta":
- case "item/reasoning/summaryTextDelta":
- return [{ kind: "thinking", text: params?.delta ?? "" }];
-
- case "item/agentMessage/delta":
- return [{ kind: "text", text: params?.delta ?? "" }];
-
- case "item/started":
- return this.handleItemStarted(params);
-
- case "item/completed":
- return this.handleItemCompleted(params);
-
- // A raw response item is a liveness signal (no user-visible content).
- case "rawResponseItem/completed":
- return [{ kind: "internal_progress", source: "codex_raw_item", itemType: "rawResponseItem" }];
-
- // Non-fatal diagnostics surfaced by Codex.
- case "configWarning":
- case "warning":
- case "guardianWarning":
- case "deprecationNotice":
- return [
- { kind: "runtime_diagnostic", severity: "warning", source: method, message: params?.message ?? method },
- ];
-
- case "turn/completed":
- // Turn is over — no live turn to steer against anymore.
- this.turnId = null;
- if (params?.status === "failed") return [{ kind: "error", message: "Codex turn failed" }];
- if (params?.status === "interrupted") {
- return [{ kind: "error", message: "Codex turn interrupted" }, { kind: "turn_end", sessionId: this.threadId ?? undefined }];
- }
- return [{ kind: "turn_end", sessionId: this.threadId ?? undefined }];
-
- case "error":
- return [{ kind: "error", message: params?.message ?? "Codex error" }];
-
- case "thread/tokenUsage/updated":
- case "account/rateLimits/updated":
- return mapCodexTelemetry(method, params);
-
- default:
- return [];
- }
- }
-
- private handleItemStarted(params: any): ParsedEvent[] {
- const t = params?.item?.type ?? params?.type;
- switch (t) {
- case "commandExecution":
- return [{ kind: "tool_call", name: "shell", input: params?.item }];
- case "contextCompaction":
- return [{ kind: "compaction_started" }];
- case "enteredReviewMode":
- return [{ kind: "review_started" }];
- case "fileChange":
- return [{ kind: "tool_call", name: "file_change", input: normalizeFileChangeInput(params?.item) }];
- case "mcpToolCall":
- return [{ kind: "tool_call", name: `mcp_${params?.item?.name ?? "tool"}`, input: params?.item }];
- case "webSearch":
- return [{ kind: "tool_call", name: "web_search", input: params?.item }];
- case "collabAgentToolCall":
- return [{ kind: "tool_call", name: "collab_tool_call", input: params?.item }];
- default:
- return [];
- }
- }
-
- private handleItemCompleted(params: any): ParsedEvent[] {
- const t = params?.item?.type ?? params?.type;
- switch (t) {
- case "commandExecution":
- return [{ kind: "tool_output", name: "shell" }];
- case "contextCompaction":
- return [{ kind: "compaction_finished" }];
- case "exitedReviewMode":
- return [{ kind: "review_finished" }];
- case "fileChange":
- return [{ kind: "tool_output", name: "file_change" }];
- case "mcpToolCall":
- return [{ kind: "tool_output", name: `mcp_${params?.item?.name ?? "tool"}` }];
- case "webSearch":
- return [{ kind: "tool_output", name: "web_search" }];
- case "collabAgentToolCall":
- return [{ kind: "tool_output", name: "collab_tool_call" }];
- case "agentMessage":
- return [{ kind: "text", text: params?.item?.text ?? "" }];
- case "reasoning":
- return [{ kind: "thinking", text: params?.item?.text ?? "" }];
- default:
- return [];
- }
- }
-}
diff --git a/src/daemon/src/drivers/copilot.ts b/src/daemon/src/drivers/copilot.ts
deleted file mode 100644
index 0bd6b2e1e..000000000
--- a/src/daemon/src/drivers/copilot.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * Copilot driver — per-turn, JSON output, no steering.
- *
- * `copilot --output-format json --allow-all-tools --allow-all-paths -p <prompt>`
- * is launched per wake; the prompt is passed as the `-p` argument (nothing is
- * written to stdin). Emits a JSON event stream and exits.
- */
-import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
-import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { spawnAgentProcess } from "../runtime/killTree.js";
-import { tryParseJsonLine } from "./utils.js";
-
-export class CopilotDriver implements Driver {
- readonly id = "copilot";
- readonly lifecycle = {
- kind: "per_turn",
- start: "immediate",
- exit: "natural",
- inFlightWake: "spawn_new",
- } as const;
- readonly session = { recovery: "resume_or_fresh" } as const;
- readonly model = {
- detectedModelsVerifiedAs: "launchable",
- toLaunchSpec: (modelId: string) => ({ args: ["--model", modelId] }),
- } as const;
-
-
- readonly capabilities = {
- reasoningEffort: true,
- fastMode: false,
- disallowedTools: false,
- command: true,
- sessionResumeMode: "by-id",
- } as const;
-
- private sessionId: string | null = null;
-
- probe() {
- // Detection is `copilot --version` via the shared probe. On a machine where
- // the real Copilot CLI isn't installed, the `copilot` that resolves on PATH
- // is often the VS Code extension shim (e.g.
- // `~/Library/Application Support/Code/User/globalStorage/github.copilot-chat/copilotCli/copilot`),
- // which exits 0 and prints `Install GitHub Copilot CLI? ['y/N']` instead of
- // a version. `probeCommandVersion`'s version-shape validation rejects that
- // output, so this reports `unhealthy` (not-installed) rather than surfacing
- // the prompt text as a bogus version. Verified on macOS.
- return probeCliRuntime("copilot");
- }
-
- async spawn(ctx: LaunchContext): Promise<SpawnResult> {
- this.sessionId = ctx.config.sessionId ?? null;
- const { spawnEnv } = await prepareCliTransport(ctx);
- const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
- const args = ["--output-format", "json", "--allow-all-tools", "--allow-all-paths", "-p", ctx.prompt];
- if (f.model) args.push("--model", f.model);
- if (f.reasoningEffort) args.push("--effort", f.reasoningEffort);
- if (ctx.config.sessionId) args.push(`--resume=${ctx.config.sessionId}`);
-
- // Cross-platform spawn: on Windows the copilot entry is often a `.cmd`
- // shim, which `child_process.spawn` can't exec without a shell.
- const spec = resolveSpawnSpec("copilot", args, f.command);
- const proc = spawnAgentProcess(spec.command, spec.args, {
- cwd: ctx.workingDirectory,
- env: spawnEnv,
- shell: spec.shell,
- });
- return { process: proc };
- }
-
- parseLine(line: string): ParsedEvent[] {
- const event = tryParseJsonLine(line) as any;
- if (!event) return [];
- switch (event?.type) {
- case "assistant.turn_start":
- if (event.sessionId) this.sessionId = event.sessionId;
- return this.sessionId ? [{ kind: "session_init", sessionId: this.sessionId }] : [];
- case "assistant.reasoning":
- return [{ kind: "thinking", text: event.content ?? "" }];
- case "assistant.message_delta":
- return [{ kind: "text", text: event.deltaContent ?? "" }];
- case "assistant.message": {
- const reqs = event.message?.toolRequests ?? [];
- return reqs.map((req: any) => ({
- kind: "tool_call" as const,
- name: req.name ?? req.toolName ?? "unknown_tool",
- input: req.arguments ?? req.parameters ?? req.input ?? {},
- }));
- }
- case "assistant.turn_end":
- return [{ kind: "turn_end", sessionId: this.sessionId ?? undefined }];
- case "result":
- if (event.sessionId) this.sessionId = event.sessionId;
- return event.exitCode && event.exitCode !== 0
- ? [{ kind: "error", message: `Copilot exited with code ${event.exitCode}` }, { kind: "turn_end" }]
- : [{ kind: "turn_end", sessionId: this.sessionId ?? undefined }];
- default:
- return [];
- }
- }
-
- get currentSessionId(): string | null {
- return this.sessionId;
- }
-
- encodeStdinMessage(): string | null {
- return null;
- }
-
- buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config);
- }
-}
diff --git a/src/daemon/src/drivers/cursor.test.ts b/src/daemon/src/drivers/cursor.test.ts
deleted file mode 100644
index b91faf648..000000000
--- a/src/daemon/src/drivers/cursor.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-import { EventEmitter } from "events";
-import * as fs from "fs";
-import * as os from "os";
-import * as path from "path";
-import { CursorDriver } from "./cursor";
-import type { LaunchContext } from "../types";
-import { CredentialBroker } from "../credentials/credentialProxy";
-
-// Capture the argv the driver spawns with, so we can assert the flag set the
-// cursor-agent CLI actually accepts today (the `--yolo/--approve-mcps/--trust`
-// trio was removed — passing them fails arg-parse → pre_handshake_exit).
-let lastSpawn: { command: string; args: string[]; opts: any } | null = null;
-
-vi.mock("../runtime/killTree", async () => {
- const actual = await vi.importActual<typeof import("../runtime/killTree")>("../runtime/killTree");
- return {
- ...actual,
- spawnAgentProcess: (command: string, args: string[], opts: any) => {
- lastSpawn = { command, args, opts };
- const proc = new EventEmitter() as EventEmitter & { stdin: { write: ReturnType<typeof vi.fn> } };
- proc.stdin = { write: vi.fn() };
- return proc as never;
- },
- };
-});
-
-function mkTmp(): string {
- return fs.mkdtempSync(path.join(os.tmpdir(), "cursor-test-"));
-}
-
-function baseCtx(): LaunchContext {
- const tmp = mkTmp();
- return {
- agentId: "agent_1",
- launchId: "launch_1",
- workingDirectory: tmp,
- standingPrompt: "You are Cursor.",
- prompt: "say hi",
- credentialProxy: {
- broker: new CredentialBroker({ upstreamBaseUrl: "https://u.test", voucherDir: mkTmp() }),
- proxyUrl: "http://127.0.0.1:9/proxy",
- runnerKey: "sk_agent_test",
- capabilities: ["send", "read"],
- },
- config: {},
- mockCliTransport: true,
- };
-}
-
-describe("CursorDriver spawn args", () => {
- it("launches with --force and NOT the removed --yolo/--approve-mcps/--trust flags", async () => {
- lastSpawn = null;
- const driver = new CursorDriver();
- await driver.spawn(baseCtx());
-
- expect(lastSpawn).not.toBeNull();
- const args = lastSpawn!.args;
- // The current cursor-agent permission posture.
- expect(args).toContain("--force");
- expect(args).toEqual(expect.arrayContaining(["--print", "--output-format", "stream-json"]));
- // The removed flags must be gone — any of them makes cursor-agent exit at
- // arg-parse ("unknown option") before the handshake (pre_handshake_exit).
- expect(args).not.toContain("--yolo");
- expect(args).not.toContain("--approve-mcps");
- expect(args).not.toContain("--trust");
- // Prompt is passed as the trailing arg (per-turn, no stdin).
- expect(args[args.length - 1]).toBe("say hi");
- // stdin MUST be "ignore" — cursor-agent hangs on a piped stdin (emits
- // nothing → handshake_timeout) even with the prompt in a positional arg.
- expect(lastSpawn!.opts.stdin).toBe("ignore");
- });
-
- it("appends --resume when resuming, still with --force and no removed flags", async () => {
- lastSpawn = null;
- const driver = new CursorDriver();
- const ctx = baseCtx();
- ctx.config = { sessionId: "chat_42" };
- await driver.spawn(ctx);
-
- const args = lastSpawn!.args;
- expect(args).toContain("--force");
- expect(args).toEqual(expect.arrayContaining(["--resume", "chat_42"]));
- expect(args).not.toContain("--yolo");
- expect(args).not.toContain("--approve-mcps");
- expect(args).not.toContain("--trust");
- });
-});
diff --git a/src/daemon/src/drivers/cursor.ts b/src/daemon/src/drivers/cursor.ts
deleted file mode 100644
index 630ec0bd3..000000000
--- a/src/daemon/src/drivers/cursor.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-/**
- * Cursor driver — per-turn, stream-json, no steering.
- *
- * `cursor-agent --print --output-format stream-json --force <prompt>` is
- * launched per wake. Emits Anthropic-style stream-json (system/assistant/result
- * envelopes) and exits.
- *
- * Flag note: the older `--yolo --approve-mcps --trust` trio was removed when the
- * cursor-agent CLI changed — passing them now fails arg-parse ("unknown option
- * '--yolo'"), so the process exits before the handshake (pre_handshake_exit).
- * The auto-approve execution posture is now `--force` ("allow commands unless
- * explicitly denied") on top of `--print` (which already grants full tool
- * access, write+bash). MCP approval moved out of the CLI into config
- * (`.cursor/mcp.json` + `cursor-agent mcp login`), so it has no launch flag.
- */
-import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
-import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { spawnAgentProcess } from "../runtime/killTree.js";
-import { tryParseJsonLine } from "./utils.js";
-
-export class CursorDriver implements Driver {
- readonly id = "cursor";
- readonly lifecycle = {
- kind: "per_turn",
- start: "immediate",
- exit: "natural",
- inFlightWake: "spawn_new",
- } as const;
- readonly session = { recovery: "resume_or_fresh" } as const;
- readonly model = {
- detectedModelsVerifiedAs: "launchable",
- toLaunchSpec: (modelId: string) => ({ args: ["--model", modelId] }),
- } as const;
-
-
- readonly capabilities = {
- reasoningEffort: false,
- fastMode: false,
- disallowedTools: false,
- command: true,
- sessionResumeMode: "by-id",
- } as const;
-
- private sessionId: string | null = null;
-
- probe() {
- return probeCliRuntime("cursor-agent");
- }
-
- async spawn(ctx: LaunchContext): Promise<SpawnResult> {
- this.sessionId = ctx.config.sessionId ?? null;
- const { spawnEnv } = await prepareCliTransport(ctx);
- const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
- const args = ["--print", "--output-format", "stream-json", "--force"];
- if (f.model) args.push("--model", f.model);
- if (ctx.config.sessionId) args.push("--resume", ctx.config.sessionId);
- args.push(ctx.prompt);
-
- // Cross-platform spawn: on Windows the cursor-agent entry is often a
- // `.cmd` shim, which `child_process.spawn` can't exec without a shell.
- const spec = resolveSpawnSpec("cursor-agent", args, f.command);
- const proc = spawnAgentProcess(spec.command, spec.args, {
- cwd: ctx.workingDirectory,
- env: spawnEnv,
- shell: spec.shell,
- // cursor-agent blocks waiting on a piped stdin even with the prompt in a
- // positional arg — it emits nothing and the daemon times out. It never
- // reads stdin (per-turn, encodeStdinMessage returns null), so ignore it.
- stdin: "ignore",
- });
- return { process: proc };
- }
-
- parseLine(line: string): ParsedEvent[] {
- const event = tryParseJsonLine(line) as any;
- if (!event) return [];
- if (event?.type === "system") {
- if (event.subtype === "init") {
- this.sessionId = event.session_id ?? this.sessionId;
- return this.sessionId ? [{ kind: "session_init", sessionId: this.sessionId }] : [];
- }
- if (event.subtype === "status" && event.status === "compacting") return [{ kind: "compaction_started" }];
- if (event.subtype === "compact_boundary") return [{ kind: "compaction_finished" }];
- return [];
- }
- if (event?.type === "assistant") {
- const content = event.message?.content ?? [];
- const out: ParsedEvent[] = [];
- for (const block of content) {
- if (block?.type === "thinking") out.push({ kind: "thinking", text: block.thinking ?? "" });
- else if (block?.type === "text") out.push({ kind: "text", text: block.text ?? "" });
- else if (block?.type === "tool_use")
- out.push({ kind: "tool_call", name: block.name ?? "unknown_tool", input: block.input });
- }
- return out;
- }
- if (event?.type === "result") {
- const out: ParsedEvent[] = [];
- if (event.subtype !== "success" || event.is_error) {
- const detail = (event.errors ?? []).map((e: any) => e?.message).filter(Boolean).join("; ");
- out.push({ kind: "error", message: detail || String(event.result ?? "Cursor error") });
- }
- out.push({ kind: "turn_end", sessionId: event.session_id ?? this.sessionId ?? undefined });
- return out;
- }
- return [];
- }
-
- get currentSessionId(): string | null {
- return this.sessionId;
- }
-
- encodeStdinMessage(): string | null {
- return null;
- }
-
- buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config);
- }
-}
diff --git a/src/daemon/src/drivers/gemini.test.ts b/src/daemon/src/drivers/gemini.test.ts
deleted file mode 100644
index 983f32aaa..000000000
--- a/src/daemon/src/drivers/gemini.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { buildGeminiArgs, GeminiDriver } from "./gemini";
-import { makeRuntimeConfig } from "../runtimeConfig";
-import type { LaunchConfig } from "../types";
-
-describe("GeminiDriver", () => {
- it("declares detectedModelsVerifiedAs 'launchable' (its --model flag actually launches)", () => {
- const driver = new GeminiDriver();
- expect(driver.model.detectedModelsVerifiedAs).toBe("launchable");
- });
-});
-
-describe("buildGeminiArgs — model flag is conditional on f.model", () => {
- it("omits --model when the runtime config leaves it default", () => {
- const config: LaunchConfig = { runtimeConfig: makeRuntimeConfig({ runtime: "gemini" }) };
- const args = buildGeminiArgs(config);
- expect(args).not.toContain("--model");
- });
-
- it("pushes --model <name> when a named model is set", () => {
- const config: LaunchConfig = {
- runtimeConfig: makeRuntimeConfig({ runtime: "gemini", model: { kind: "named", name: "gemini-2.5-pro" } }),
- };
- const args = buildGeminiArgs(config);
- const idx = args.indexOf("--model");
- expect(idx).toBeGreaterThan(-1);
- expect(args[idx + 1]).toBe("gemini-2.5-pro");
- });
-});
diff --git a/src/daemon/src/drivers/gemini.ts b/src/daemon/src/drivers/gemini.ts
deleted file mode 100644
index 526101904..000000000
--- a/src/daemon/src/drivers/gemini.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * Gemini driver — per-turn, stream-json, no steering.
- *
- * Gemini CLI is launched once per wake with `--output-format stream-json
- * --yolo -p ""`; the prompt is written to stdin and stdin is then closed. The
- * process produces a stream-json transcript and exits — that exit IS the turn
- * boundary. No mid-session input is possible (`encodeStdinMessage` → null), so
- * new messages mean a brand-new process and the agent polls the inbox.
- */
-import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
-import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { spawnAgentProcess } from "../runtime/killTree.js";
-import { tryParseJsonLine, writeToStdinAndDetach } from "./utils.js";
-
-export function buildGeminiArgs(config: LaunchConfig): string[] {
- const f = resolveLaunchFieldsOrDefault(config.runtimeConfig);
- return [
- "--output-format",
- "stream-json",
- "--yolo",
- "-p",
- "",
- ...(f.model ? ["--model", f.model] : []),
- ...(config.sessionId ? ["--resume", config.sessionId] : []),
- ];
-}
-
-export class GeminiDriver implements Driver {
- readonly id = "gemini";
- readonly lifecycle = {
- kind: "per_turn",
- start: "immediate",
- exit: "natural",
- inFlightWake: "spawn_new",
- } as const;
- readonly session = { recovery: "resume_or_fresh" } as const;
- readonly model = {
- detectedModelsVerifiedAs: "launchable",
- toLaunchSpec: (modelId: string) =>
- modelId ? { args: ["--model", modelId] } : { args: [] },
- } as const;
-
-
- readonly capabilities = {
- reasoningEffort: false,
- fastMode: false,
- disallowedTools: false,
- command: true,
- sessionResumeMode: "by-id",
- } as const;
-
- private sessionId: string | null = null;
-
- probe() {
- return probeCliRuntime("gemini");
- }
-
- async spawn(ctx: LaunchContext): Promise<SpawnResult> {
- this.sessionId = ctx.config.sessionId ?? null;
- const { spawnEnv } = await prepareCliTransport(ctx);
- // Gemini refuses to run in a workspace it doesn't "trust" — an interactive
- // gate that has no meaning for a headless spawn. Force-trust the workdir
- // unconditionally; the sandboxing that gate is intended to provide is
- // already covered by the credential proxy + capability scope.
- spawnEnv.GEMINI_CLI_TRUST_WORKSPACE ??= "true";
- if (process.platform === "win32") spawnEnv.GEMINI_PTY_INFO ??= "child_process";
-
- // Cross-platform spawn: on Windows the gemini entry is often a `.cmd` shim.
- const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
- const spec = resolveSpawnSpec("gemini", buildGeminiArgs(ctx.config), override);
- const proc = spawnAgentProcess(spec.command, spec.args, {
- cwd: ctx.workingDirectory,
- env: spawnEnv,
- shell: spec.shell,
- });
- // Prompt in, then close stdin — one-shot.
- writeToStdinAndDetach(proc, ctx.prompt);
- return { process: proc };
- }
-
- parseLine(line: string): ParsedEvent[] {
- const event = tryParseJsonLine(line) as any;
- if (!event) return [];
- switch (event?.type) {
- case "init":
- this.sessionId = event.session_id ?? this.sessionId;
- return this.sessionId ? [{ kind: "session_init", sessionId: this.sessionId }] : [];
- case "message":
- if (event.role === "assistant" && event.content) return [{ kind: "text", text: event.content }];
- return [];
- case "tool_use":
- return [{ kind: "tool_call", name: event.tool_name ?? "unknown_tool", input: event.parameters }];
- case "error":
- return [{ kind: "error", message: event.message ?? "Gemini error" }];
- case "result":
- return event.status && event.status !== "success"
- ? [{ kind: "error", message: String(event.status) }, { kind: "turn_end", sessionId: this.sessionId ?? undefined }]
- : [{ kind: "turn_end", sessionId: this.sessionId ?? undefined }];
- default:
- return [];
- }
- }
-
- get currentSessionId(): string | null {
- return this.sessionId;
- }
-
- encodeStdinMessage(): string | null {
- return null; // per-turn: no mid-session input
- }
-
- buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config);
- }
-}
diff --git a/src/daemon/src/drivers/index.ts b/src/daemon/src/drivers/index.ts
index 34d4a3d11..44e6709f1 100644
--- a/src/daemon/src/drivers/index.ts
+++ b/src/daemon/src/drivers/index.ts
@@ -1,65 +1,32 @@
-/**
- * Driver registry — the single place that maps a runtime id to its driver.
- *
- * `getDriver(runtimeId)` is how the daemon obtains a backend. The runtime is
- * an explicit choice made at agent-create time — there is no auto-migration
- * or alias between runtimes.
- */
-import type { Driver } from "../types.js";
-import { ClaudeDriver } from "./claude.js";
-import { CodexDriver } from "./codex.js";
-import { GeminiDriver } from "./gemini.js";
-import { CopilotDriver } from "./copilot.js";
-import { CursorDriver } from "./cursor.js";
-import { OpenCodeDriver } from "./opencode.js";
-import { AntigravityDriver } from "./antigravity.js";
-import { KimiDriver } from "./kimi.js";
-import { PiDriver } from "./pi.js";
+import {
+ BUILTIN_BACKEND_IDS,
+ createAgentDriverSdk,
+ getBuiltinBackendCapabilities,
+ type BackendCapabilities,
+ type BackendProbe,
+ type BuiltinBackendId,
+} from "@alook/agent-driver";
-export type RuntimeId =
- | "claude"
- | "codex"
- | "antigravity"
- | "copilot"
- | "cursor"
- | "gemini"
- | "kimi"
- | "opencode"
- | "pi";
+export type RuntimeId = BuiltinBackendId;
-const driverFactories: Record<RuntimeId, () => Driver> = {
- claude: () => new ClaudeDriver(),
- codex: () => new CodexDriver(),
- antigravity: () => new AntigravityDriver(),
- copilot: () => new CopilotDriver(),
- cursor: () => new CursorDriver(),
- gemini: () => new GeminiDriver(),
- kimi: () => new KimiDriver(),
- opencode: () => new OpenCodeDriver(),
- pi: () => new PiDriver(),
-};
+export interface AgentBackend {
+ readonly id: RuntimeId;
+ readonly capabilities: BackendCapabilities;
+ probe(): Promise<BackendProbe<BackendCapabilities>>;
+}
-export function getDriver(runtimeId: string): Driver {
- const createDriver = (driverFactories as Record<string, (() => Driver) | undefined>)[runtimeId];
- const driver = createDriver?.();
- if (!driver) {
- throw new Error(`Unknown runtime: ${runtimeId}. Available: ${Object.keys(driverFactories).join(", ")}`);
+export function getDriver(runtimeId: string): AgentBackend {
+ if (!(BUILTIN_BACKEND_IDS as readonly string[]).includes(runtimeId)) {
+ throw new Error(`Unknown runtime: ${runtimeId}. Available: ${BUILTIN_BACKEND_IDS.join(", ")}`);
}
- return driver;
+ const id = runtimeId as RuntimeId;
+ return {
+ id,
+ capabilities: getBuiltinBackendCapabilities(id),
+ probe: () => createAgentDriverSdk().probe({ backend: id }),
+ };
}
export function listRuntimeIds(): RuntimeId[] {
- return Object.keys(driverFactories) as RuntimeId[];
+ return [...BUILTIN_BACKEND_IDS];
}
-
-export {
- ClaudeDriver,
- CodexDriver,
- GeminiDriver,
- CopilotDriver,
- CursorDriver,
- OpenCodeDriver,
- AntigravityDriver,
- KimiDriver,
- PiDriver,
-};
diff --git a/src/daemon/src/drivers/kimi.test.ts b/src/daemon/src/drivers/kimi.test.ts
deleted file mode 100644
index 77a0a04a4..000000000
--- a/src/daemon/src/drivers/kimi.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-import { EventEmitter } from "events";
-import * as fs from "fs";
-import * as os from "os";
-import * as path from "path";
-import { KimiDriver, KIMI_WIRE_PROTOCOL_VERSION } from "./kimi";
-import type { LaunchContext } from "../types";
-import { CredentialBroker } from "../credentials/credentialProxy";
-import { readDaemonVersion } from "../version";
-
-vi.mock("../runtime/killTree", async () => {
- const actual = await vi.importActual<typeof import("../runtime/killTree")>("../runtime/killTree");
- return {
- ...actual,
- spawnAgentProcess: () => {
- const proc = new EventEmitter() as EventEmitter & { stdin: { write: ReturnType<typeof vi.fn> } };
- proc.stdin = { write: vi.fn() };
- return proc as never;
- },
- };
-});
-
-function mkTmp(): string {
- return fs.mkdtempSync(path.join(os.tmpdir(), "kimi-test-"));
-}
-
-function baseCtx(): LaunchContext {
- const tmp = mkTmp();
- return {
- agentId: "agent_1",
- launchId: "launch_1",
- workingDirectory: tmp,
- standingPrompt: "You are Kimi.",
- prompt: "hi",
- credentialProxy: {
- broker: new CredentialBroker({ upstreamBaseUrl: "https://u.test", voucherDir: mkTmp() }),
- proxyUrl: "http://127.0.0.1:9/proxy",
- runnerKey: "sk_agent_test",
- capabilities: ["send", "read"],
- },
- config: {},
- mockCliTransport: true,
- };
-}
-
-describe("KimiDriver initialize payload", () => {
- it("sends alook-daemon identity and the named protocol version", async () => {
- const driver = new KimiDriver();
- const ctx = baseCtx();
- const { process: proc } = await driver.spawn(ctx);
- const stdin = (proc as unknown as { stdin: { write: ReturnType<typeof vi.fn> } }).stdin;
-
- // First stdin write is `initialize`.
- const firstCall = stdin.write.mock.calls[0][0] as string;
- const initPayload = JSON.parse(firstCall.trim());
-
- expect(initPayload.jsonrpc).toBe("2.0");
- expect(initPayload.method).toBe("initialize");
- expect(initPayload.params.protocol_version).toBe(KIMI_WIRE_PROTOCOL_VERSION);
- expect(initPayload.params.client).toEqual({ name: "alook-daemon", version: readDaemonVersion() });
- });
-});
diff --git a/src/daemon/src/drivers/kimi.ts b/src/daemon/src/drivers/kimi.ts
deleted file mode 100644
index 271469881..000000000
--- a/src/daemon/src/drivers/kimi.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-/**
- * Kimi driver — persistent child-process CLI over JSON-RPC, DIRECT steering.
- *
- * `kimi --wire --yolo --session <id>` runs a long-lived process speaking
- * JSON-RPC 2.0 over stdio (the "wire" protocol). The standing prompt is
- * delivered via the `AGENTS.md` that `prepareCliTransport` writes into the
- * workdir (Kimi auto-reads it from cwd). On spawn we send `initialize` then a
- * `prompt`; thereafter idle messages are `prompt` and busy messages are `steer`.
- */
-import { randomUUID } from "crypto";
-import type { Driver, EncodeOpts, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
-import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { spawnAgentProcess } from "../runtime/killTree.js";
-import { jsonRpcRequest, tryParseJsonLine } from "./utils.js";
-import { getDaemonClientInfo } from "../version.js";
-
-/** Kimi `--wire` handshake protocol version. Bump when the vendor CLI does. */
-export const KIMI_WIRE_PROTOCOL_VERSION = "1.3";
-
-function parseToolArguments(args: unknown): unknown {
- if (typeof args !== "string") return args ?? {};
- try {
- return JSON.parse(args);
- } catch {
- return { raw: args };
- }
-}
-
-export class KimiDriver implements Driver {
- readonly id = "kimi";
- readonly lifecycle = { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const;
- readonly session = { recovery: "resume_or_fresh" } as const;
- readonly model = {
- detectedModelsVerifiedAs: "launchable",
- toLaunchSpec: (modelId: string) => ({ args: ["--model", modelId] }),
- } as const;
-
-
- readonly capabilities = {
- reasoningEffort: false,
- fastMode: false,
- disallowedTools: false,
- command: true,
- sessionResumeMode: "by-id",
- } as const;
-
- // Kimi's `--wire` handshake requires the client to supply the session id up
- // front (there's no "server picks the id" path). We accept the caller's id
- // when resuming and mint a fresh UUID otherwise; the id is the resume key.
- private sessionId = "";
- private sentInit = false;
- private promptRequestId = randomUUID();
-
- probe() {
- return probeCliRuntime("kimi");
- }
-
- async spawn(ctx: LaunchContext): Promise<SpawnResult> {
- this.sessionId = ctx.config.sessionId || randomUUID();
- const isResume = Boolean(ctx.config.sessionId);
- // The standing prompt reaches Kimi via the AGENTS.md that prepareCliTransport
- // writes into the workdir (unified packing — see cliTransport.ts) — Kimi
- // auto-reads it from cwd, no --agent-file flag needed.
- const { spawnEnv } = await prepareCliTransport(ctx);
-
- const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
- const args = ["--wire", "--yolo", "--session", this.sessionId];
- if (f.model) args.push("--model", f.model);
-
- // Cross-platform spawn: on Windows the kimi entry is often a `.cmd`
- // shim, which `child_process.spawn` can't exec without a shell.
- const spec = resolveSpawnSpec("kimi", args, f.command);
- const proc = spawnAgentProcess(spec.command, spec.args, {
- cwd: ctx.workingDirectory,
- env: spawnEnv,
- shell: spec.shell,
- });
-
- proc.stdin?.write(
- jsonRpcRequest("initialize", {
- protocol_version: KIMI_WIRE_PROTOCOL_VERSION,
- client: getDaemonClientInfo(),
- capabilities: { supports_question: false, supports_plan_mode: false },
- }) + "\n",
- );
- proc.stdin?.write(
- jsonRpcRequest(
- "prompt",
- {
- user_input: isResume
- ? ctx.prompt
- : "Your system prompt contains your standing instructions. Follow it now and begin listening for messages.",
- },
- this.promptRequestId,
- ) + "\n",
- );
-
- return { process: proc };
- }
-
- parseLine(line: string): ParsedEvent[] {
- const msg = tryParseJsonLine(line) as any;
- if (!msg) return [];
- const out: ParsedEvent[] = [];
- if (!this.sentInit) {
- this.sentInit = true;
- out.push({ kind: "session_init", sessionId: this.sessionId });
- }
-
- if (msg?.error) {
- out.push({ kind: "error", message: msg.error?.message ?? "Unknown Kimi error" });
- out.push({ kind: "turn_end", sessionId: this.sessionId });
- return out;
- }
- if (msg?.method !== "event") return out;
-
- const payload = msg.params ?? {};
- switch (payload.event) {
- case "StepBegin":
- out.push({ kind: "thinking", text: "" });
- break;
- case "CompactionBegin":
- out.push({ kind: "compaction_started" });
- break;
- case "CompactionEnd":
- out.push({ kind: "compaction_finished" });
- break;
- case "ContentPart":
- if (payload.type === "think") out.push({ kind: "thinking", text: payload.think ?? "" });
- else if (payload.type === "text") out.push({ kind: "text", text: payload.text ?? "" });
- break;
- case "ToolCall":
- out.push({
- kind: "tool_call",
- name: payload.function?.name ?? "unknown_tool",
- input: parseToolArguments(payload.function?.arguments),
- });
- break;
- case "TurnEnd":
- out.push({ kind: "turn_end", sessionId: this.sessionId });
- break;
- case "StepInterrupted":
- out.push({ kind: "error", message: "Turn interrupted" });
- out.push({ kind: "turn_end", sessionId: this.sessionId });
- break;
- }
- return out;
- }
-
- get currentSessionId(): string | null {
- return this.sessionId || null;
- }
-
- /** idle → `prompt`; busy → `steer`. */
- encodeStdinMessage(text: string, _sessionId: string | null, opts?: EncodeOpts): string | null {
- const method = opts?.mode === "idle" ? "prompt" : "steer";
- return jsonRpcRequest(method, { user_input: text });
- }
-
- buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config);
- }
-}
diff --git a/src/daemon/src/drivers/opencode.test.ts b/src/daemon/src/drivers/opencode.test.ts
deleted file mode 100644
index 057fd5752..000000000
--- a/src/daemon/src/drivers/opencode.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { describe, it, expect, beforeEach } from "vitest";
-import { OpenCodeDriver } from "./opencode";
-
-describe("OpenCodeDriver.parseLine — step_finish turn-end timing", () => {
- let driver: OpenCodeDriver;
-
- beforeEach(() => {
- driver = new OpenCodeDriver();
- });
-
- function line(obj: unknown): string {
- return JSON.stringify(obj);
- }
-
- it("does NOT end the turn on an intermediate step_finish (reason: tool-calls)", () => {
- const events = driver.parseLine(
- line({ type: "step_finish", sessionID: "ses_1", part: { type: "step-finish", reason: "tool-calls" } }),
- );
- expect(events.some((e) => e.kind === "turn_end")).toBe(false);
- });
-
- it("ends the turn on the final step_finish (reason: stop)", () => {
- const events = driver.parseLine(
- line({ type: "step_finish", sessionID: "ses_1", part: { type: "step-finish", reason: "stop" } }),
- );
- expect(events.some((e) => e.kind === "turn_end")).toBe(true);
- });
-
- it("a multi-step turn (tool-calls step, then a stop step) emits turn_end exactly once, after the final step", () => {
- const afterToolCallStep = driver.parseLine(
- line({ type: "step_finish", sessionID: "ses_1", part: { type: "step-finish", reason: "tool-calls" } }),
- );
- const afterFinalStep = driver.parseLine(
- line({ type: "step_finish", sessionID: "ses_1", part: { type: "step-finish", reason: "stop" } }),
- );
-
- expect(afterToolCallStep.filter((e) => e.kind === "turn_end")).toHaveLength(0);
- expect(afterFinalStep.filter((e) => e.kind === "turn_end")).toHaveLength(1);
- });
-
- it("does not throw on a step_finish with no part (defensive)", () => {
- expect(() => driver.parseLine(line({ type: "step_finish", sessionID: "ses_1" }))).not.toThrow();
- // Missing `part.reason` is treated as "not tool-calls" -> turn ends, which
- // is the safe default (never getting stuck waiting for a turn_end that
- // never comes).
- const events = driver.parseLine(line({ type: "step_finish", sessionID: "ses_1" }));
- expect(events.some((e) => e.kind === "turn_end")).toBe(true);
- });
-});
diff --git a/src/daemon/src/drivers/opencode.ts b/src/daemon/src/drivers/opencode.ts
deleted file mode 100644
index d3fd595d4..000000000
--- a/src/daemon/src/drivers/opencode.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * OpenCode driver — per-turn, JSON output, deferred-spawn + terminate-on-end.
- *
- * Distinctive lifecycle: it DEFERS spawning until a concrete message arrives
- * (bookkeeping-only wakes don't launch a process) and explicitly TERMINATES the
- * process when the turn ends (rather than relying on natural exit). The
- * standing prompt reaches OpenCode via the `AGENTS.md` that `prepareCliTransport`
- * writes into the workdir (OpenCode auto-reads it from cwd); the user message
- * is the trailing `-- <prompt>` positional.
- */
-import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
-import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
-import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { spawnAgentProcess } from "../runtime/killTree.js";
-import { tryParseJsonLine } from "./utils.js";
-
-export class OpenCodeDriver implements Driver {
- readonly id = "opencode";
- readonly lifecycle = {
- kind: "per_turn",
- start: "defer_until_concrete_message",
- exit: "terminate_on_turn_end",
- inFlightWake: "coalesce_into_pending",
- } as const;
- readonly session = { recovery: "resume_or_fresh" } as const;
- readonly model = {
- detectedModelsVerifiedAs: "launchable",
- toLaunchSpec: (modelId: string) => ({ args: ["--model", modelId] }),
- } as const;
-
- readonly terminateProcessOnTurnEnd = true;
- readonly deferSpawnUntilMessage = true;
-
- readonly capabilities = {
- reasoningEffort: false,
- fastMode: false,
- disallowedTools: false,
- command: true,
- sessionResumeMode: "by-id",
- } as const;
-
- private sessionId: string | null = null;
-
- /** System task wakes (first-message bookkeeping) should not spawn a process. */
- shouldDeferWakeMessage(message: { type?: string }): boolean {
- return message?.type === "system";
- }
-
- probe() {
- return probeCliRuntime("opencode");
- }
-
- async spawn(ctx: LaunchContext): Promise<SpawnResult> {
- this.sessionId = ctx.config.sessionId ?? null;
- const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
- // prepareCliTransport writes AGENTS.md into the workdir (unified packing) —
- // OpenCode auto-reads it from cwd, no custom `host` agent config needed.
- const { spawnEnv } = await prepareCliTransport(ctx);
-
- const args = ["run", "--format", "json", "--dangerously-skip-permissions", "--pure", "--dir", ctx.workingDirectory];
- if (f.model) args.push("--model", f.model);
- if (ctx.config.sessionId) args.push("--session", ctx.config.sessionId);
- const promptArg = ctx.prompt === ctx.standingPrompt ? "No new messages are pending. Stop now." : ctx.prompt;
- args.push("--", promptArg);
-
- // Cross-platform spawn: on Windows the opencode entry is often a `.cmd`
- // shim, which `child_process.spawn` can't exec without a shell.
- const spec = resolveSpawnSpec("opencode", args, f.command);
- const proc = spawnAgentProcess(spec.command, spec.args, {
- cwd: ctx.workingDirectory,
- env: spawnEnv,
- shell: spec.shell,
- });
- proc.stdin?.end();
- return { process: proc };
- }
-
- parseLine(line: string): ParsedEvent[] {
- const event = tryParseJsonLine(line) as any;
- if (!event) return [];
- const out: ParsedEvent[] = [];
- if (event?.sessionID && this.sessionId !== event.sessionID) {
- this.sessionId = event.sessionID;
- out.push({ kind: "session_init", sessionId: this.sessionId! });
- }
- switch (event?.type) {
- case "step_start":
- out.push({ kind: "thinking", text: "" });
- break;
- case "text":
- if (typeof event.part?.text === "string" && event.part.text.length > 0)
- out.push({ kind: "text", text: event.part.text });
- break;
- case "tool_use":
- out.push({ kind: "tool_call", name: event.part?.tool ?? "unknown_tool", input: event.part?.state?.input });
- break;
- case "step_finish":
- // `reason` lives under `part` (e.g. `part: { reason: "stop" | "tool-calls" | ... }`),
- // not at the top level — reading `event.reason` directly is always
- // `undefined`, which made every step (including intermediate
- // tool-call steps) look like the final one.
- if (event.part?.reason !== "tool-calls") out.push({ kind: "turn_end", sessionId: this.sessionId ?? undefined });
- break;
- case "error":
- out.push({
- kind: "error",
- message: event.error?.data?.message ?? event.error?.message ?? "OpenCode error",
- });
- out.push({ kind: "turn_end", sessionId: this.sessionId ?? undefined });
- break;
- }
- return out;
- }
-
- get currentSessionId(): string | null {
- return this.sessionId;
- }
-
- encodeStdinMessage(): string | null {
- return null;
- }
-
- buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config);
- }
-}
diff --git a/src/daemon/src/drivers/pi.test.ts b/src/daemon/src/drivers/pi.test.ts
deleted file mode 100644
index c0b0e3e33..000000000
--- a/src/daemon/src/drivers/pi.test.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import * as fs from "fs";
-import * as os from "os";
-import * as path from "path";
-import { PiDriver, resolvePiSdkVersionFromPath, resolvePiSdkPackageDir, findPiSessionFile } from "./pi";
-import { CANONICAL_FILE } from "./agentFile";
-import type { LaunchContext } from "../types";
-
-let tmpDir: string;
-
-beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-driver-test-"));
-});
-afterEach(() => {
- fs.rmSync(tmpDir, { recursive: true, force: true });
-});
-
-function baseCtx(overrides: Partial<LaunchContext> = {}): LaunchContext {
- return {
- agentId: "agent_1",
- workingDirectory: tmpDir,
- standingPrompt: "You are Pi.",
- prompt: "hello",
- config: {},
- credentialProxy: {} as LaunchContext["credentialProxy"],
- ...overrides,
- };
-}
-
-function fakeDeps() {
- const session = {
- prompt: vi.fn().mockResolvedValue(undefined),
- steer: vi.fn(),
- abort: vi.fn(),
- dispose: vi.fn(),
- isStreaming: false,
- subscribe: vi.fn(),
- };
- const createAgentSession = vi.fn().mockResolvedValue({ session, sessionId: "sess_1" });
- const buildSpawnEnv = vi.fn().mockResolvedValue({});
- return { buildSpawnEnv, createAgentSession, session };
-}
-
-describe("PiDriver.createSession — AGENTS.md packing", () => {
- it("does not write AGENTS.md itself — prepareCliTransport (inside piSdkDeps.buildSpawnEnv) is the single packing point", async () => {
- const driver = new PiDriver();
- const deps = fakeDeps();
-
- await driver.createSession(baseCtx(), deps);
-
- // The driver no longer writes AGENTS.md — buildSpawnEnv already did, and
- // duplicating the write here would risk hash-dedup drift.
- expect(fs.existsSync(path.join(tmpDir, CANONICAL_FILE))).toBe(false);
-
- const sessionOpts = deps.createAgentSession.mock.calls[0][0];
- expect(sessionOpts).not.toHaveProperty("standingPrompt");
- });
-});
-
-describe("PiDriver.createSession — does not fire the initial prompt itself", () => {
- it("returns without calling session.prompt — the caller (SdkManagedSession) sends the first turn", async () => {
- const driver = new PiDriver();
- const deps = fakeDeps();
-
- const runtimeSession = await driver.createSession(baseCtx(), deps);
-
- expect(deps.session.prompt).not.toHaveBeenCalled();
- expect(runtimeSession.currentSessionId).toBe("sess_1");
- });
-
- it("wires session.subscribe before returning, so events fired by a later prompt() call are not lost", async () => {
- const driver = new PiDriver();
- const deps = fakeDeps();
-
- const runtimeSession = await driver.createSession(baseCtx(), deps);
- const received: unknown[] = [];
- runtimeSession.on("runtime_event", (e) => received.push(e));
-
- // Simulate the SDK emitting a text_delta while handling a prompt sent
- // later, via the subscribe callback deps.session.subscribe captured.
- const subscribeCb = deps.session.subscribe.mock.calls[0][0];
- subscribeCb({ type: "message_update", delta: { type: "text_delta", delta: "hi" } });
-
- expect(received).toEqual([
- { kind: "session_init", sessionId: "sess_1" },
- { kind: "text", text: "hi" },
- ]);
- });
-});
-
-describe("findPiSessionFile", () => {
- it("matches an entry ending in `_${sessionId}.jsonl`", () => {
- const sessionDir = path.join(tmpDir, "sessions");
- fs.mkdirSync(sessionDir, { recursive: true });
- fs.writeFileSync(path.join(sessionDir, "2026-01-01_someone-else.jsonl"), "");
- fs.writeFileSync(path.join(sessionDir, "2026-05-01_target-id.jsonl"), "");
-
- expect(findPiSessionFile(sessionDir, "target-id")).toBe(
- path.join(sessionDir, "2026-05-01_target-id.jsonl"),
- );
- });
-
- it("returns null when no entry matches the id", () => {
- const sessionDir = path.join(tmpDir, "sessions");
- fs.mkdirSync(sessionDir, { recursive: true });
- fs.writeFileSync(path.join(sessionDir, "2026-01-01_someone-else.jsonl"), "");
-
- expect(findPiSessionFile(sessionDir, "target-id")).toBeNull();
- });
-
- it("returns null when the session directory is unreadable / missing", () => {
- expect(findPiSessionFile(path.join(tmpDir, "does-not-exist"), "target-id")).toBeNull();
- });
-});
-
-describe("resolvePiSdkVersionFromPath — globally-installed pi fallback detection", () => {
- it("finds the SDK version by following the `pi` binary's symlink up to its package.json (simulates npm/Homebrew/pnpm global installs)", () => {
- // Simulate a global install layout:
- // <root>/lib/node_modules/@earendil-works/pi-coding-agent/{package.json,dist/cli.js}
- // <root>/bin/pi -> ../lib/node_modules/@earendil-works/pi-coding-agent/dist/cli.js
- const pkgDir = path.join(tmpDir, "lib", "node_modules", "@earendil-works", "pi-coding-agent");
- fs.mkdirSync(path.join(pkgDir, "dist"), { recursive: true });
- fs.writeFileSync(
- path.join(pkgDir, "package.json"),
- JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.80.3" }),
- );
- const entryFile = path.join(pkgDir, "dist", "cli.js");
- fs.writeFileSync(entryFile, "#!/usr/bin/env node\n");
-
- const binDir = path.join(tmpDir, "bin");
- fs.mkdirSync(binDir, { recursive: true });
- const binPath = path.join(binDir, "pi");
- fs.symlinkSync(entryFile, binPath);
-
- const version = resolvePiSdkVersionFromPath({ which: (cmd) => (cmd === "pi" ? binPath : null) });
- expect(version).toBe("0.80.3");
- });
-
- it("returns undefined when `pi` is not on PATH", () => {
- const version = resolvePiSdkVersionFromPath({ which: () => null });
- expect(version).toBeUndefined();
- });
-
- it("returns undefined (does not throw) when the resolved binary isn't part of the pi-coding-agent package", () => {
- const otherDir = path.join(tmpDir, "some-other-tool");
- fs.mkdirSync(otherDir, { recursive: true });
- fs.writeFileSync(path.join(otherDir, "package.json"), JSON.stringify({ name: "unrelated-tool", version: "1.0.0" }));
- const binPath = path.join(otherDir, "pi");
- fs.writeFileSync(binPath, "#!/usr/bin/env node\n");
-
- const version = resolvePiSdkVersionFromPath({ which: (cmd) => (cmd === "pi" ? binPath : null) });
- expect(version).toBeUndefined();
- });
-
- it("returns undefined (does not throw) when the resolved path doesn't exist on disk", () => {
- const version = resolvePiSdkVersionFromPath({ which: () => path.join(tmpDir, "nonexistent", "pi") });
- expect(version).toBeUndefined();
- });
-
- // Regression test: on Windows, npm writes the `.cmd` shim as a real file
- // directly in the global prefix root (e.g. `%AppData%\npm`) — NOT a
- // symlink into the package like POSIX — so `realpathSync` never walks us
- // inside it. The package instead sits in a SIBLING `node_modules` folder
- // at that same level, never an ancestor of the shim's own directory.
- it("finds the SDK version via a sibling node_modules dir (simulates a Windows npm global install, where the shim is a real file next to node_modules, not a symlink into it)", () => {
- // Simulate: %AppData%\npm\pi.cmd (a real file, not a symlink) and
- // %AppData%\npm\node_modules\@earendil-works\pi-coding-agent\
- const npmRoot = path.join(tmpDir, "AppData", "npm");
- const pkgDir = path.join(npmRoot, "node_modules", "@earendil-works", "pi-coding-agent");
- fs.mkdirSync(pkgDir, { recursive: true });
- fs.writeFileSync(
- path.join(pkgDir, "package.json"),
- JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.90.1" }),
- );
- const binPath = path.join(npmRoot, "pi.cmd");
- fs.writeFileSync(binPath, "@echo off\r\n"); // a real file, not a symlink
-
- const version = resolvePiSdkVersionFromPath({ which: (cmd) => (cmd === "pi" ? binPath : null) });
- expect(version).toBe("0.90.1");
- });
-
- it("resolvePiSdkPackageDir returns the sibling package dir itself, not the shim's own directory", () => {
- const npmRoot = path.join(tmpDir, "AppData", "npm");
- const pkgDir = path.join(npmRoot, "node_modules", "@earendil-works", "pi-coding-agent");
- fs.mkdirSync(pkgDir, { recursive: true });
- fs.writeFileSync(path.join(pkgDir, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.90.1" }));
- const binPath = path.join(npmRoot, "pi.cmd");
- fs.writeFileSync(binPath, "@echo off\r\n");
-
- const dir = resolvePiSdkPackageDir({ which: (cmd) => (cmd === "pi" ? binPath : null) });
- // Compare via realpath — on macOS, tmpdir() itself sits behind a
- // `/var` -> `/private/var` symlink unrelated to the thing under test.
- expect(dir && fs.realpathSync(dir)).toBe(fs.realpathSync(pkgDir));
- });
-});
diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.ts
index 5dbd6f1d2..11712ceff 100644
--- a/src/daemon/src/drivers/systemPrompt.test.ts
+++ b/src/daemon/src/drivers/systemPrompt.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
import { buildCliSystemPrompt } from "./systemPrompt";
-import type { LaunchConfig } from "../types";
+import type { HostLaunchConfig as LaunchConfig } from "../manager/hostContext.js";
const baseConfig: LaunchConfig = {
runtimeContext: {
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index ec06627c4..85cc93cbc 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -2,7 +2,7 @@
* Shared system-prompt builder.
* Every CLI driver's `buildSystemPrompt` funnels through here.
*/
-import type { LaunchConfig } from "../types.js";
+import type { HostLaunchConfig } from "../manager/hostContext.js";
// The agent invokes the CLI via the `$ALOOK_CLI` env var, NOT a bare `alook`.
// `$ALOOK_CLI` is an ABSOLUTE path the daemon injects (see spawnEnv
@@ -23,7 +23,7 @@ const CLI = "$ALOOK_CLI";
* privacy defaults, and channel etiquette elsewhere in the prompt all
* derive from it. Placed first so identity and role read together.
*/
-function identitySection(config: LaunchConfig): string {
+function identitySection(config: HostLaunchConfig): string {
const parts: string[] = ["## Identity", ""];
const name = config.agentName ?? "a member of the household";
@@ -498,7 +498,7 @@ function workspaceMemorySection(): string {
* depend on which runtime is about to be spawned (see
* `systemPrompt.test.ts`).
*/
-export function buildCliSystemPrompt(config: LaunchConfig): string {
+export function buildCliSystemPrompt(config: HostLaunchConfig): string {
const sections: string[] = [
identitySection(config),
cliCommandsSection(),
diff --git a/src/daemon/src/index.ts b/src/daemon/src/index.ts
index 0a9e332e2..9cc1a5aa3 100644
--- a/src/daemon/src/index.ts
+++ b/src/daemon/src/index.ts
@@ -1,33 +1,12 @@
-/**
- * Public entry point for the daemon's driver layer.
- *
- * Typical use:
- * import { getDriver, createChildProcessRuntimeSession } from "@alook/daemon";
- * const driver = getDriver("claude");
- * const session = createChildProcessRuntimeSession(driver, ctx);
- * session.on("runtime_event", (e) => handle(e));
- * await session.start({ text: initialPrompt });
- * session.send({ text: "new message", mode: "busy" }); // steer mid-turn
- */
-export * from "./types.js";
+export * from "@alook/agent-driver";
export * from "./drivers/index.js";
-export {
- ChildProcessRuntimeSession,
- createChildProcessRuntimeSession,
- descriptorFromDriver,
- type RuntimeSessionDescriptor,
-} from "./runtime/runtimeSession.js";
-export { SdkRuntimeSession, type SdkSessionHandle } from "./runtime/sdkRuntimeSession.js";
export { RuntimeProgressState } from "./runtime/progressState.js";
export { RuntimeNotificationState } from "./runtime/notificationState.js";
-export * from "./runtime/apmStateMachine.js";
export * from "./runtime/errorDiagnostics.js";
export * from "./inbox/index.js";
export * from "./manager/index.js";
export * from "./credentials/index.js";
export * from "./daemon/index.js";
-export * from "./drivers/codexHome.js";
-export { resolveSpawnSpec, type SpawnSpec } from "./drivers/probe.js";
export {
resolveAlookCliPath,
resolveAlookCliPathWithFallback,
diff --git a/src/daemon/src/manager/agentDriverHost.test.ts b/src/daemon/src/manager/agentDriverHost.test.ts
new file mode 100644
index 000000000..85fcb1a47
--- /dev/null
+++ b/src/daemon/src/manager/agentDriverHost.test.ts
@@ -0,0 +1,145 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+import { CredentialBroker } from "../credentials/credentialProxy.js";
+import type { HostLaunchContext } from "./hostContext.js";
+import { createDaemonAgentDriverHost } from "./agentDriverHost.js";
+
+const tmpDirs: string[] = [];
+function tmp(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "driver-host-"));
+ tmpDirs.push(dir);
+ return dir;
+}
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const dir of tmpDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+function context(
+ broker: CredentialBroker,
+ overrides: Partial<HostLaunchContext> = {},
+): HostLaunchContext {
+ return {
+ agentId: "agent_1",
+ launchId: "launch_1",
+ workingDirectory: tmp(),
+ standingPrompt: "",
+ prompt: "",
+ agentCliPath: process.execPath,
+ credentialProxy: {
+ broker,
+ proxyUrl: "http://127.0.0.1:9/proxy",
+ runnerKey: "runner-test",
+ capabilities: ["send", "read"],
+ },
+ config: {},
+ ...overrides,
+ };
+}
+
+function broker(): CredentialBroker {
+ return new CredentialBroker({ upstreamBaseUrl: "https://upstream.test", voucherDir: tmp() });
+}
+
+describe("createDaemonAgentDriverHost", () => {
+ it("fails closed without a credential proxy", async () => {
+ const ctx = context(broker());
+ delete ctx.credentialProxy;
+ expect(await createDaemonAgentDriverHost(ctx).prepareExecution({ backend: "claude", launchId: "l", workingDirectory: ctx.workingDirectory }))
+ .toMatchObject({ ok: false, error: { code: "credential_proxy_required" } });
+ });
+
+ it("fails loudly when the daemon cannot resolve its agent CLI", async () => {
+ const ctx = context(broker(), { agentCliPath: undefined });
+ expect(await createDaemonAgentDriverHost(ctx).prepareExecution({ backend: "claude", launchId: "l", workingDirectory: ctx.workingDirectory }))
+ .toMatchObject({ ok: false, error: { code: "agent_cli_required" } });
+ });
+
+ it("rejects missing and comma-containing capability lists", async () => {
+ const first = context(broker());
+ first.credentialProxy!.capabilities = undefined as never;
+ expect(await createDaemonAgentDriverHost(first).prepareExecution({ backend: "claude", launchId: "l", workingDirectory: first.workingDirectory }))
+ .toMatchObject({ ok: false, error: { code: "invalid_capabilities" } });
+ const second = context(broker());
+ second.credentialProxy!.capabilities = ["send,read"];
+ expect(await createDaemonAgentDriverHost(second).prepareExecution({ backend: "claude", launchId: "l", workingDirectory: second.workingDirectory }))
+ .toMatchObject({ ok: false, error: { code: "invalid_capabilities" } });
+ });
+
+ it("accepts an empty capability set and mints a zero-scope voucher", async () => {
+ const cred = broker();
+ const ctx = context(cred);
+ ctx.credentialProxy!.capabilities = [];
+ const result = await createDaemonAgentDriverHost(ctx).prepareExecution({ backend: "claude", launchId: "l", workingDirectory: ctx.workingDirectory });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.resource.environmentLayers.platformProtected.ALOOK_ACTIVE_CAPABILITIES).toBe("");
+ const voucher = fs.readFileSync(String(result.resource.environmentLayers.credentialSensitive.ALOOK_PROXY_TOKEN_FILE), "utf8");
+ expect(cred.check(`Bearer ${voucher}`, "send").ok).toBe(false);
+ });
+
+ it("injects protected platform, runtime, network, identity, and credential layers", async () => {
+ const cred = broker();
+ const ctx = context(cred, {
+ agentId: "a3f90c21beef",
+ config: {
+ agentName: "Melisa",
+ agentDiscriminator: "1043",
+ runtimeContext: {
+ agentId: "a3f90c21beef", serverId: "srv", computerId: "pc", computerName: "Workstation",
+ hostname: "host", os: "linux", daemonVersion: "1.2.3", workspacePath: "/work",
+ },
+ },
+ });
+ const result = await createDaemonAgentDriverHost(ctx).prepareExecution({ backend: "claude", launchId: "l", workingDirectory: ctx.workingDirectory });
+ if (!result.ok) throw new Error(result.error.message);
+ expect(result.resource.environmentLayers.identityProtected).toMatchObject({
+ GIT_COMMITTER_NAME: "Melisa",
+ GIT_COMMITTER_EMAIL: "[email protected]",
+ });
+ expect(result.resource.environmentLayers.platformProtected).toMatchObject({
+ ALOOK_ID: "a3f90c21beef",
+ ALOOK_LAUNCH_ID: "launch_1",
+ ALOOK_ACTIVE_CAPABILITIES: "send,read",
+ });
+ expect(result.resource.environmentLayers.runtimeProtected).toMatchObject({ ALOOK_SERVER_ID: "srv", ALOOK_WORKSPACE_PATH: "/work" });
+ expect(result.resource.environmentLayers.networkProtected.NO_PROXY).toContain("localhost");
+ expect(result.resource.environmentLayers.credentialSensitive.ALOOK_PROXY_URL).toBe("http://127.0.0.1:9/proxy");
+ });
+
+ it("revokes the previous same-agent voucher before mint and release revokes the current one exactly once", async () => {
+ const cred = broker();
+ const ctx = context(cred);
+ const first = await createDaemonAgentDriverHost(ctx).prepareExecution({ backend: "codex", launchId: "one", workingDirectory: ctx.workingDirectory });
+ if (!first.ok) throw new Error(first.error.message);
+ const firstVoucher = fs.readFileSync(String(first.resource.environmentLayers.credentialSensitive.ALOOK_PROXY_TOKEN_FILE), "utf8");
+ expect(cred.check(`Bearer ${firstVoucher}`).ok).toBe(true);
+ const second = await createDaemonAgentDriverHost(ctx).prepareExecution({ backend: "codex", launchId: "two", workingDirectory: ctx.workingDirectory });
+ if (!second.ok) throw new Error(second.error.message);
+ expect(cred.size).toBe(1);
+ expect(cred.check(`Bearer ${firstVoucher}`).ok).toBe(false);
+ const secondVoucher = fs.readFileSync(String(second.resource.environmentLayers.credentialSensitive.ALOOK_PROXY_TOKEN_FILE), "utf8");
+ await second.resource.release({ reason: "normal", signal: new AbortController().signal, deadlineAt: Date.now() + 100 });
+ expect(cred.check(`Bearer ${secondVoucher}`).ok).toBe(false);
+ });
+
+ it("does not revoke a different agent's voucher", async () => {
+ const cred = broker();
+ const one = context(cred, { agentId: "agent_1" });
+ const two = context(cred, { agentId: "agent_2", launchId: "launch_2" });
+ await createDaemonAgentDriverHost(one).prepareExecution({ backend: "claude", launchId: "one", workingDirectory: one.workingDirectory });
+ await createDaemonAgentDriverHost(two).prepareExecution({ backend: "claude", launchId: "two", workingDirectory: two.workingDirectory });
+ expect(cred.size).toBe(2);
+ });
+
+ it("forwards only stdout raw output", () => {
+ const raw = vi.fn();
+ const host = createDaemonAgentDriverHost(context(broker()), raw);
+ host.onRawOutput({ backend: "codex", launchId: "l", stream: "stderr", text: "no" });
+ host.onRawOutput({ backend: "codex", launchId: "l", stream: "stdout", text: "yes" });
+ expect(raw).toHaveBeenCalledOnce();
+ expect(raw).toHaveBeenCalledWith("yes");
+ });
+});
diff --git a/src/daemon/src/manager/agentDriverHost.ts b/src/daemon/src/manager/agentDriverHost.ts
new file mode 100644
index 000000000..f93cdd0bc
--- /dev/null
+++ b/src/daemon/src/manager/agentDriverHost.ts
@@ -0,0 +1,111 @@
+import { randomUUID } from "node:crypto";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import type { AgentDriverHost, PreparedExecutionResource } from "@alook/agent-driver/host";
+import type { HostLaunchContext } from "./hostContext.js";
+import { buildGitIdentityEnv, readHostGitIdentity } from "../drivers/gitIdentityEnv.js";
+
+function runtimeEnvironment(ctx: HostLaunchContext): Record<string, string | undefined> {
+ const runtime = ctx.config.runtimeContext;
+ if (!runtime) return {};
+ return {
+ ALOOK_AGENT_ID: runtime.agentId,
+ ALOOK_SERVER_ID: runtime.serverId,
+ ALOOK_COMPUTER_ID: runtime.computerId,
+ ALOOK_COMPUTER_NAME: runtime.computerName,
+ ALOOK_HOSTNAME: runtime.hostname,
+ ALOOK_OS: runtime.os,
+ ALOOK_DAEMON_VERSION: runtime.daemonVersion,
+ ALOOK_WORKSPACE_PATH: runtime.workspacePath,
+ };
+}
+
+export function createDaemonAgentDriverHost(
+ ctx: HostLaunchContext,
+ onRawLine?: (line: string) => void,
+): AgentDriverHost {
+ return {
+ async prepareExecution() {
+ const handoff = ctx.credentialProxy;
+ if (!handoff) {
+ return {
+ ok: false,
+ error: {
+ category: "configuration" as const,
+ code: "credential_proxy_required",
+ message: "Daemon launches require a credential proxy handoff",
+ retryable: false,
+ },
+ };
+ }
+ if (!Array.isArray(handoff.capabilities) || handoff.capabilities.some((item) => item.includes(","))) {
+ return {
+ ok: false,
+ error: {
+ category: "configuration" as const,
+ code: "invalid_capabilities",
+ message: "Credential capabilities must be comma-free string tokens",
+ retryable: false,
+ },
+ };
+ }
+ if (!ctx.agentCliPath) {
+ return {
+ ok: false,
+ error: {
+ category: "configuration" as const,
+ code: "agent_cli_required",
+ message: "Daemon launches require a resolvable agent CLI path",
+ retryable: false,
+ },
+ };
+ }
+ handoff.broker.revokeAgent(ctx.agentId);
+ const registration = handoff.broker.mint(
+ ctx.agentId,
+ ctx.launchId ?? "default",
+ handoff.capabilities,
+ handoff.runnerKey,
+ );
+ const resource: PreparedExecutionResource = {
+ executablePath: ctx.agentCliPath,
+ environmentLayers: {
+ base: { ...process.env },
+ hostStatic: {},
+ identityProtected: buildGitIdentityEnv({
+ agentName: ctx.config.agentName,
+ discriminator: ctx.config.agentDiscriminator,
+ hostUser: readHostGitIdentity() ?? undefined,
+ }),
+ platformProtected: {
+ ALOOK_HOME: process.env.ALOOK_HOME ?? join(homedir(), ".alook"),
+ ALOOK_ID: ctx.agentId,
+ ALOOK_CLI: ctx.agentCliPath,
+ ALOOK_SERVER_URL: ctx.config.serverUrl,
+ ALOOK_ACTIVE_CAPABILITIES: handoff.capabilities.join(","),
+ ALOOK_LAUNCH_ID: ctx.launchId,
+ ALOOK_TRACE_DIR: ctx.cliTransportTraceDir,
+ },
+ runtimeProtected: runtimeEnvironment(ctx),
+ networkProtected: {
+ NO_PROXY: ["127.0.0.1", "localhost", process.env.NO_PROXY].filter(Boolean).join(","),
+ PATH: process.env.PATH,
+ },
+ credentialSensitive: {
+ ALOOK_PROXY_URL: handoff.proxyUrl,
+ ALOOK_PROXY_TOKEN_FILE: registration.voucherFile,
+ },
+ },
+ async release() {
+ handoff.broker.revoke(registration.voucher);
+ },
+ };
+ return { ok: true, resource };
+ },
+ onRawOutput(event) {
+ if (event.stream === "stdout") onRawLine?.(event.text);
+ },
+ now: () => Date.now(),
+ createId: () => randomUUID(),
+ };
+}
diff --git a/src/daemon/src/manager/agentProfile.test.ts b/src/daemon/src/manager/agentProfile.test.ts
index e93dbedb8..5ee5b54b6 100644
--- a/src/daemon/src/manager/agentProfile.test.ts
+++ b/src/daemon/src/manager/agentProfile.test.ts
@@ -1,14 +1,14 @@
import { describe, it, expect } from "vitest";
import { AgentProcessManager } from "./managerRuntime";
-import type { LaunchContext } from "../types";
+import type { HostLaunchContext as LaunchContext } from "./hostContext.js";
import { makeRuntimeConfig } from "../runtimeConfig";
+import type { AgentSessionResult } from "@alook/agent-driver";
/**
* The daemon does not invent an agent's identity: when the server downlinks a
* RuntimeConfig (via agent:wake → manager.register), its `instruction` becomes
- * the description on the LaunchConfig. The driver's `buildSystemPrompt(config)`
- * is called to assemble the full standing prompt — the daemon never passes raw
- * instruction text as the prompt.
+ * the description on the host launch config. The daemon assembles the standing
+ * prompt once, independently of the selected backend.
*/
function managerCapturingCtx(): {
mgr: AgentProcessManager;
@@ -16,12 +16,7 @@ function managerCapturingCtx(): {
} {
const ctxs: LaunchContext[] = [];
const mgr = new AgentProcessManager({
- driverFor: () =>
- ({
- lifecycle: { kind: "persistent", stdin: "gated", inFlightWake: "queue" },
- buildSystemPrompt: (config: { description?: string }) =>
- config.description ? `[system] ${config.description}` : "",
- }) as never,
+ driverFor: () => ({ id: "codex", capabilities: {} as never, probe: async () => ({} as never) }),
baseContextFor: (agentId) => ({
agentId,
workingDirectory: "/tmp/x",
@@ -30,15 +25,28 @@ function managerCapturingCtx(): {
sessionFactory: ({ ctx }) => {
ctxs.push(ctx);
return {
- on: () => {},
- get currentSessionId() {
- return null;
+ backend: "codex" as const,
+ capabilities: {} as never,
+ sessionInstanceId: "agent-profile-test",
+ events: {
+ maxBufferedBytes: 4_194_304 as const,
+ async *[Symbol.asyncIterator]() { await new Promise(() => {}); },
},
- async start() {},
- send() {
- return { ok: true };
+ closed: new Promise<AgentSessionResult>(() => {}),
+ async start(message: { id: string }) {
+ return { status: "accepted" as const, delivery: "prompt" as const, commandId: message.id, turnId: "profile-turn" };
+ },
+ async send(message: { id: string }) {
+ return { status: "accepted" as const, delivery: "steer" as const, commandId: message.id, turnId: "profile-turn" };
+ },
+ async interrupt() { return { status: "not_running" as const }; },
+ async stop() { return { status: "accepted" as const, requestId: "profile-stop" }; },
+ snapshot() {
+ return { sessionInstanceId: "agent-profile-test", state: "working" as const, queuedCommands: [], lastEventSequence: 0 };
+ },
+ async invokeExtension() {
+ return { ok: false as const, error: { category: "internal" as const, code: "unsupported", message: "unsupported", retryable: false } };
},
- async stop() {},
};
},
tickIntervalMs: 10_000,
@@ -47,7 +55,7 @@ function managerCapturingCtx(): {
}
describe("agent profile from server-downlinked RuntimeConfig", () => {
- it("calls driver.buildSystemPrompt to assemble the standing prompt", () => {
+ it("assembles the standing prompt from the server-downlinked description", () => {
const { mgr, ctxs } = managerCapturingCtx();
mgr.register("agent_1", {
runtimeConfig: makeRuntimeConfig({
@@ -59,10 +67,8 @@ describe("agent profile from server-downlinked RuntimeConfig", () => {
mgr.deliver("agent_1", { seq: 1, text: "hello" });
expect(ctxs).toHaveLength(1);
- // instruction flows to config.description → driver.buildSystemPrompt wraps it
- expect(ctxs[0].standingPrompt).toBe(
- "[system] You are the onboarding assistant.",
- );
+ expect(ctxs[0].standingPrompt).toContain("You are the onboarding assistant.");
+ expect(ctxs[0].standingPrompt).toContain("### Role");
expect(ctxs[0].config.description).toBe(
"You are the onboarding assistant.",
);
@@ -71,13 +77,14 @@ describe("agent profile from server-downlinked RuntimeConfig", () => {
);
});
- it("returns empty standingPrompt when driver.buildSystemPrompt produces nothing", () => {
+ it("uses the agent name as the fallback role description", () => {
const { mgr, ctxs } = managerCapturingCtx();
mgr.register("agent_2", {
runtimeConfig: makeRuntimeConfig({ runtime: "mock", agentName: "Bot" }),
});
mgr.deliver("agent_2", { seq: 1, text: "hi" });
- expect(ctxs[0].standingPrompt).toBe("[system] Bot");
+ expect(ctxs[0].standingPrompt).toContain("### Role");
+ expect(ctxs[0].standingPrompt).toContain("Bot");
expect(ctxs[0].config.description).toBe("Bot");
});
});
diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.ts
index 851f091db..d3533204b 100644
--- a/src/daemon/src/manager/agentRouter.test.ts
+++ b/src/daemon/src/manager/agentRouter.test.ts
@@ -103,7 +103,7 @@ function fakeChannel() {
}
describe("AgentRouter — agent:wake", () => {
- it("registers the runtime config, delivers the notice text, and acks the wake", async () => {
+ it("registers the runtime config, delivers a generic notice, and acks the wake", async () => {
const { mgr, delivers, registers } = fakeManager();
const { ch, wakeAcks, fire } = fakeChannel();
const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "mock" }] });
@@ -118,7 +118,7 @@ describe("AgentRouter — agent:wake", () => {
});
expect(registers).toEqual([{ agentId: "a1", sessionId: undefined, launchId: "l1" }]);
- expect(delivers).toEqual([{ agentId: "a1", text: "You have unread messages in channel /demo#1234/general.", seq: 7 }]);
+ expect(delivers).toEqual([{ agentId: "a1", text: "You have unread messages.", seq: 7 }]);
expect(wakeAcks).toEqual([{ agentId: "a1", launchId: "l1", status: "ok" }]);
});
@@ -274,7 +274,7 @@ describe("AgentRouter — agent:reset", () => {
});
it("UnknownRuntimeError from resetSession → forwards session.error{runtime_not_available}, running set untouched", async () => {
- const throwing = new UnknownRuntimeError("gemini", ["claude", "codex"]);
+ const throwing = new UnknownRuntimeError("unknown-runtime", ["claude", "codex"]);
const mgr = {
resetSession: async () => { throw throwing; },
liveSessionReports: () => [],
@@ -286,7 +286,7 @@ describe("AgentRouter — agent:reset", () => {
await fire({
type: "agent:reset",
agentId: "a1",
- config: { ...CFG, runtime: "gemini" },
+ config: { ...CFG, runtime: "unknown-runtime" },
launchId: "l1",
});
expect(sessionErrors).toHaveLength(1);
@@ -294,7 +294,7 @@ describe("AgentRouter — agent:reset", () => {
type: "session.error",
code: "runtime_not_available",
agentId: "a1",
- payload: { requested: "gemini", available: ["claude", "codex"] },
+ payload: { requested: "unknown-runtime", available: ["claude", "codex"] },
});
expect(router.buildReady().runningAgents).not.toContain("a1");
});
@@ -439,7 +439,7 @@ describe("AgentRouter — agent:model_switch", () => {
});
it("UnknownRuntimeError → session.error{runtime_not_available}; generic error → warn, running set untouched", async () => {
- const throwing = new UnknownRuntimeError("gemini", ["claude", "codex"]);
+ const throwing = new UnknownRuntimeError("unknown-runtime", ["claude", "codex"]);
const mgrUnknown = {
switchModel: async () => { throw throwing; },
liveSessionReports: () => [],
@@ -447,7 +447,7 @@ describe("AgentRouter — agent:model_switch", () => {
const { ch, sessionErrors, fire } = fakeChannel();
const router = new AgentRouter({ manager: mgrUnknown, channel: ch, runtimeReport: [{ id: "claude" }, { id: "codex" }] });
await router.start();
- await fire({ type: "agent:model_switch", agentId: "a1", config: { ...CFG, runtime: "gemini" }, launchId: "l1" });
+ await fire({ type: "agent:model_switch", agentId: "a1", config: { ...CFG, runtime: "unknown-runtime" }, launchId: "l1" });
expect(sessionErrors).toHaveLength(1);
expect(sessionErrors[0]).toMatchObject({ type: "session.error", code: "runtime_not_available", agentId: "a1" });
expect(router.buildReady().runningAgents).not.toContain("a1");
@@ -514,7 +514,7 @@ describe("AgentRouter — unknown runtime → session.error", () => {
it("catches UnknownRuntimeError from driverFor and forwards session.error{runtime_not_available}", async () => {
// Manager whose register() re-throws whatever driverFor throws — mimics
// the real AgentProcessManager which calls opts.driverFor eagerly.
- const throwing: UnknownRuntimeError = new UnknownRuntimeError("gemini", ["claude", "codex"]);
+ const throwing: UnknownRuntimeError = new UnknownRuntimeError("unknown-runtime", ["claude", "codex"]);
const mgr = {
register() {
throw throwing;
@@ -530,7 +530,7 @@ describe("AgentRouter — unknown runtime → session.error", () => {
await fire({
type: "agent:wake",
agentId: "a1",
- config: { version: 1, runtime: "gemini", model: { kind: "default" }, mode: { kind: "default" } },
+ config: { version: 1, runtime: "unknown-runtime", model: { kind: "default" }, mode: { kind: "default" } },
launchId: "l1",
unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },
});
@@ -540,7 +540,7 @@ describe("AgentRouter — unknown runtime → session.error", () => {
type: "session.error",
code: "runtime_not_available",
agentId: "a1",
- payload: { requested: "gemini", available: ["claude", "codex"] },
+ payload: { requested: "unknown-runtime", available: ["claude", "codex"] },
});
});
});
@@ -721,10 +721,10 @@ describe("AgentRouter — runtime health map", () => {
const router = new AgentRouter({
manager: mgr,
channel: ch,
- runtimeReport: [{ id: "codex" }, { id: "claude" }, { id: "gemini" }],
+ runtimeReport: [{ id: "codex" }, { id: "claude" }, { id: "cursor" }],
scheduleReadyResend: (fn) => fn(),
});
- router.markRuntimeUnhealthy("gemini", "ENOENT");
+ router.markRuntimeUnhealthy("cursor", "ENOENT");
expect(router.healthyRuntimeIds()).toEqual(["codex", "claude"]);
// buildReady MUST include all three so the DO/canonical-diff sees the
// unhealthy transition. A future "clean up the wire" refactor that strips
@@ -733,12 +733,12 @@ describe("AgentRouter — runtime health map", () => {
expect(ready.runtimeReport.map((r) => r.id)).toEqual([
"codex",
"claude",
- "gemini",
+ "cursor",
]);
- const gemini = ready.runtimeReport.find((r) => r.id === "gemini");
- expect(gemini?.status).toBe("unhealthy");
- expect(gemini?.lastError).toBe("ENOENT");
- expect(typeof gemini?.lastErrorAt).toBe("string");
+ const cursor = ready.runtimeReport.find((r) => r.id === "cursor");
+ expect(cursor?.status).toBe("unhealthy");
+ expect(cursor?.lastError).toBe("ENOENT");
+ expect(typeof cursor?.lastErrorAt).toBe("string");
});
it("survives a disconnected channel — health mutations don't throw when sendReady is absent", () => {
@@ -786,7 +786,7 @@ describe("AgentRouter — logging", () => {
});
it("logs info for the ack with error status when the wake fails", async () => {
- const throwing: UnknownRuntimeError = new UnknownRuntimeError("gemini", ["claude"]);
+ const throwing: UnknownRuntimeError = new UnknownRuntimeError("unknown-runtime", ["claude"]);
const mgr = {
register() {
throw throwing;
@@ -803,7 +803,7 @@ describe("AgentRouter — logging", () => {
await fire({
type: "agent:wake",
agentId: "a1",
- config: { version: 1, runtime: "gemini", model: { kind: "default" }, mode: { kind: "default" } },
+ config: { version: 1, runtime: "unknown-runtime", model: { kind: "default" }, mode: { kind: "default" } },
launchId: "l1",
unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },
});
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index 1af2e3237..f34d88880 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -91,10 +91,11 @@ export interface AgentRouterOpts {
onBeforeAgent?: (agentId: string) => Promise<void>;
/**
* Format the bodiless `UnreadNotice` into the prompt text the agent
- * actually sees. The default is a fixed "you have unread messages in
- * channel X" line. Deliberately does NOT include the inbox-pull
- * instruction — that's `wakePromptFooter` on `ManagerRuntimeOpts`, appended
- * once after coalescing/dedup so a burst of notices doesn't repeat it.
+ * actually sees. The default is a generic unread-message line because one
+ * admission may cover more channels than the selected wake command names.
+ * Deliberately does NOT include the inbox-pull instruction — that's
+ * `wakePromptFooter` on `ManagerRuntimeOpts`, appended once after
+ * coalescing/dedup so a burst of notices doesn't repeat it.
*/
formatUnreadNoticeText?: (notice: UnreadNotice) => string;
/**
@@ -114,8 +115,8 @@ export interface AgentRouterOpts {
logger?: Logger;
}
-function defaultFormatUnreadNoticeText(notice: UnreadNotice): string {
- return `You have unread messages in channel ${notice.channel}.`;
+function defaultFormatUnreadNoticeText(): string {
+ return "You have unread messages.";
}
/**
@@ -427,6 +428,7 @@ export class AgentRouter {
// The manager (not this router) decides spawn vs. in-process notify
// vs. coalesce — see managerPolicy's `onWake`.
const producedEffect = this.opts.manager.deliver(cmd.agentId, {
+ id: `${cmd.agentId}:wake:${cmd.unreadNotice.channel}:${cmd.unreadNotice.latestSeq}`,
seq: cmd.unreadNotice.latestSeq,
text,
});
diff --git a/src/daemon/src/manager/hostContext.ts b/src/daemon/src/manager/hostContext.ts
new file mode 100644
index 000000000..992c68bdd
--- /dev/null
+++ b/src/daemon/src/manager/hostContext.ts
@@ -0,0 +1,46 @@
+import type { CredentialBroker } from "../credentials/index.js";
+import type { RuntimeConfig } from "../runtimeConfig.js";
+
+export interface CredentialProxyHandoff {
+ broker: CredentialBroker;
+ proxyUrl: string;
+ runnerKey: string;
+ capabilities: string[];
+}
+
+export interface RuntimeContext {
+ agentId: string;
+ serverId: string;
+ computerId: string;
+ computerName: string;
+ hostname: string;
+ os: string;
+ daemonVersion: string;
+ workspacePath: string;
+}
+
+export interface HostLaunchConfig {
+ sessionId?: string;
+ authToken?: string;
+ serverUrl?: string;
+ runtimeConfig?: RuntimeConfig;
+ description?: string;
+ runtimeContext?: RuntimeContext;
+ agentName?: string;
+ agentDiscriminator?: string;
+ agentHandle?: string;
+ ownerHandle?: string;
+}
+
+export interface HostLaunchContext {
+ agentId: string;
+ launchId?: string;
+ workingDirectory: string;
+ standingPrompt: string;
+ prompt: string;
+ agentCliPath?: string;
+ daemonApiKey?: string;
+ cliTransportTraceDir?: string;
+ credentialProxy?: CredentialProxyHandoff;
+ config: HostLaunchConfig;
+}
diff --git a/src/daemon/src/manager/managerCapabilityContract.test.ts b/src/daemon/src/manager/managerCapabilityContract.test.ts
index 5fedb9d02..bdb0669cf 100644
--- a/src/daemon/src/manager/managerCapabilityContract.test.ts
+++ b/src/daemon/src/manager/managerCapabilityContract.test.ts
@@ -1,348 +1,90 @@
-/**
- * Driver-agnostic contract tests for `AgentProcessManager`'s busy/idle
- * delivery orchestration — see plans/manager-persistent-direct-contract-test.md.
- *
- * These tests don't target one driver file; they group the REAL drivers from
- * `drivers/index.ts` by their declared `AgentRuntimeCaps`-relevant profile
- * (`lifecycle.kind`/`stdin`/`inFlightWake`, `supportsStdinNotification`,
- * `busyDeliveryMode`) and drive `AgentProcessManager` itself (via a
- * `sessionFactory`, bypassing real process/SDK spawning) to assert the
- * orchestration contract each profile is supposed to get.
- *
- * Why this exists: `PiDriver` and `KimiDriver` both declare
- * `{kind: "persistent", stdin: "direct", inFlightWake: "steer"}` +
- * `busyDeliveryMode: "direct"`. A real production bug shipped because
- * `SdkManagedSession.start()` (Pi's session adapter) used to await the
- * ENTIRE first turn before resolving, which delayed `AgentProcessManager`
- * dispatching `{type: "spawned"}` (the thing that makes it treat the agent
- * as busy) until the turn was already over — so a wake that arrived mid-turn
- * was queued instead of steered, then misrouted as an `idle` send right
- * after `turn_end`, racing the vendor SDK's own "already processing" guard.
- * That fix lives in `sdkManagedSession.ts`/`pi.ts` and is regression-tested
- * in `sdkManagedSession.test.ts` — but that only protects Pi. This file
- * protects the *manager's* half of the contract for EVERY driver sharing
- * that capability profile today (Pi and Kimi declare direct/steer; Codex
- * joins Claude in the gated/queue bucket — see
- * plans/wire-gated-busy-steering-daemon.md) and any future one, without
- * needing driver-specific test plumbing.
- */
-import { describe, it, expect } from "vitest";
-import { AgentProcessManager, type ManagedSession, type SessionFactory } from "./managerRuntime.js";
-import { listRuntimeIds, getDriver } from "../drivers/index.js";
-import type { Driver, LaunchContext } from "../types.js";
-import { busyDeliveryModeOf, supportsStdinNotificationOf } from "../types.js";
-import type { Logger } from "../logger.js";
-
-interface CapabilityProfile {
- lifecycleKind: "persistent" | "per_turn";
- stdin?: "direct" | "gated";
- inFlightWake: string;
- supportsStdinNotification: boolean;
- busyDeliveryMode: "direct" | "gated" | "none";
-}
-
-function profileOf(driver: Driver): CapabilityProfile {
- const lifecycle = driver.lifecycle;
+import { describe, expect, it, vi } from "vitest";
+import * as fs from "node:fs";
+import * as path from "node:path";
+import { fileURLToPath } from "node:url";
+import { BUILTIN_BACKEND_IDS, type AgentSessionResult } from "@alook/agent-driver";
+import { AgentProcessManager, type DaemonAgentSession } from "./managerRuntime.js";
+
+function fakeSession(): DaemonAgentSession {
return {
- lifecycleKind: lifecycle.kind,
- stdin: lifecycle.kind === "persistent" ? lifecycle.stdin : undefined,
- inFlightWake: lifecycle.inFlightWake,
- // Derived from lifecycle (single source of truth) since #4 — the two fields
- // are no longer declared on Driver.
- supportsStdinNotification: supportsStdinNotificationOf(lifecycle),
- busyDeliveryMode: busyDeliveryModeOf(lifecycle),
- };
-}
-
-/** Group every registered driver by its capability profile (dedup key). */
-function capabilityBuckets(): Array<{ profile: CapabilityProfile; driverIds: string[]; sample: Driver }> {
- const buckets = new Map<string, { profile: CapabilityProfile; driverIds: string[]; sample: Driver }>();
- for (const id of listRuntimeIds()) {
- const driver = getDriver(id);
- const profile = profileOf(driver);
- const key = JSON.stringify(profile);
- const existing = buckets.get(key);
- if (existing) existing.driverIds.push(id);
- else buckets.set(key, { profile, driverIds: [id], sample: driver });
- }
- return [...buckets.values()];
-}
-
-function isDirectSteerProfile(p: CapabilityProfile): boolean {
- return (
- p.lifecycleKind === "persistent" &&
- p.stdin === "direct" &&
- p.inFlightWake === "steer" &&
- p.supportsStdinNotification &&
- p.busyDeliveryMode === "direct"
- );
-}
-
-function isGatedQueueProfile(p: CapabilityProfile): boolean {
- return (
- p.lifecycleKind === "persistent" &&
- p.stdin === "gated" &&
- p.inFlightWake === "queue" &&
- p.supportsStdinNotification &&
- p.busyDeliveryMode === "gated"
- );
-}
-
-/** Controllable fake `ManagedSession` — records every `send()` call and lets
- * the test decide exactly when `.start()` resolves, independent of whether
- * any "turn_end" has fired. This is what lets these tests exercise the
- * manager's contract without a real child process or SDK. */
-interface FakeSession extends ManagedSession {
- fire(evt: string, ...args: unknown[]): void;
- startResolver?: () => void;
- sendCalls: Array<{ text: string; mode: "busy" | "idle" }>;
-}
-
-function fakeSession(): FakeSession {
- const listeners = new Map<string, Array<(...args: unknown[]) => void>>();
- const s: FakeSession = {
- sendCalls: [],
- on(event, cb) {
- const arr = listeners.get(event) ?? [];
- arr.push(cb);
- listeners.set(event, arr);
+ backend: "codex",
+ capabilities: {} as never,
+ sessionInstanceId: "capability-test",
+ events: {
+ maxBufferedBytes: 4_194_304,
+ async *[Symbol.asyncIterator]() { await new Promise(() => {}); },
},
- start() {
- return new Promise<void>((resolve) => {
- s.startResolver = resolve;
- });
+ closed: new Promise<AgentSessionResult>(() => {}),
+ async start(message) {
+ return { status: "accepted", delivery: "prompt", commandId: message.id, turnId: "capability-turn" };
},
- send(input) {
- s.sendCalls.push(input);
+ async send(message) {
+ return { status: "accepted", delivery: "steer", commandId: message.id, turnId: "capability-turn" };
},
- stop() { },
- get currentSessionId() {
- return "sess_1";
+ async interrupt() { return { status: "not_running" }; },
+ async stop() { return { status: "accepted", requestId: "capability-stop" }; },
+ snapshot() {
+ return { sessionInstanceId: "capability-test", state: "working", queuedCommands: [], lastEventSequence: 0 };
},
- fire(evt, ...args) {
- for (const cb of listeners.get(evt) ?? []) cb(...args);
+ async invokeExtension() {
+ return { ok: false, error: { category: "internal", code: "unsupported", message: "unsupported", retryable: false } };
},
};
- return s;
}
-/** Stub logger — records calls per level for assertions (copied from
- * `managerRuntime.test.ts`; kept local so these two test files don't need to
- * import from each other). */
-function stubLogger(): Logger & { calls: Record<"debug" | "info" | "warn" | "error", Array<[string, unknown[]]>> } {
- const calls: Record<"debug" | "info" | "warn" | "error", Array<[string, unknown[]]>> = {
- debug: [],
- info: [],
- warn: [],
- error: [],
- };
- const logger = {
- calls,
- debug: (m: string, ...d: unknown[]) => calls.debug.push([m, d]),
- info: (m: string, ...d: unknown[]) => calls.info.push([m, d]),
- warn: (m: string, ...d: unknown[]) => calls.warn.push([m, d]),
- error: (m: string, ...d: unknown[]) => calls.error.push([m, d]),
- child: () => logger,
- };
- return logger;
-}
-
-function makeManager(driver: Driver, session: FakeSession, logger?: Logger) {
- const factory: SessionFactory = () => session;
- const mgr = new AgentProcessManager({
- driverFor: () => driver,
- baseContextFor: () => ({
- workingDirectory: "/tmp/agent_1",
- agentId: "a1",
- standingPrompt: "",
- config: {} as LaunchContext["config"],
- }),
- sessionFactory: factory,
- logger,
- });
- mgr.register("a1");
- return mgr;
-}
-
-const buckets = capabilityBuckets();
-const directSteerBuckets = buckets.filter((b) => isDirectSteerProfile(b.profile));
-const gatedQueueBuckets = buckets.filter((b) => isGatedQueueProfile(b.profile));
-
-describe("AgentProcessManager capability contract — persistent/direct/steer runtimes", () => {
- if (directSteerBuckets.length === 0) {
- it.skip("no driver currently declares this profile", () => { });
- }
-
- for (const bucket of directSteerBuckets) {
- const label = bucket.driverIds.join(", ");
-
- it(`[${label}] a wake delivered after the session is running (start() resolved, no turn_end yet) is steered immediately as mode:"busy" — not queued until turn_end`, async () => {
- const session = fakeSession();
- const mgr = makeManager(bucket.sample, session);
-
- mgr.deliver("a1", { seq: 1, text: "first" });
- // Simulate the FIXED contract: start() resolves once the turn is
- // accepted, well before the underlying turn (whatever it does) is
- // actually done. No "turn_end" runtime_event fires in this test.
- session.startResolver?.();
- await Promise.resolve();
-
- mgr.deliver("a1", { seq: 2, text: "mid-turn wake" });
-
- expect(session.sendCalls).toEqual([{ text: "mid-turn wake", mode: "busy" }]);
- });
-
- it(`[${label}] a wake delivered before start() resolves is queued (not sent early) and is coalesced into exactly one delivery once running`, async () => {
- const session = fakeSession();
- const mgr = makeManager(bucket.sample, session);
-
- mgr.deliver("a1", { seq: 1, text: "first" }); // triggers spawn; status -> "starting"
- mgr.deliver("a1", { seq: 2, text: "queued while starting" }); // status still "starting" -> queued, no send yet
- expect(session.sendCalls).toEqual([]);
-
- session.startResolver?.();
- await Promise.resolve();
- // Now running. A further wake should coalesce with the queued one into
- // a single busy send, not one send per queued message.
- mgr.deliver("a1", { seq: 3, text: "after running" });
-
- expect(session.sendCalls).toEqual([
- { text: "queued while starting\nafter running", mode: "busy" },
- ]);
+describe("daemon/package capability boundary", () => {
+ it("fails clearly when the daemon omits the required public session factory", () => {
+ const manager = new AgentProcessManager({
+ driverFor: () => ({ id: "pi", capabilities: {} as never, probe: async () => ({} as never) }),
+ baseContextFor: (agentId) => ({ agentId, workingDirectory: "/tmp" }),
});
- }
-});
-
-describe("AgentProcessManager capability contract — persistent/gated/queue runtimes", () => {
- if (gatedQueueBuckets.length === 0) {
- it.skip("no driver currently declares this profile", () => { });
- }
-
- for (const bucket of gatedQueueBuckets) {
- const label = bucket.driverIds.join(", ");
-
- /**
- * FIXED (see plans/wire-gated-busy-steering-daemon.md) — a mid-turn wake
- * on a gated driver is HELD, not sent immediately. `managerPolicy.ts`'s
- * `onWake` running branch now checks `busyDeliveryMode === "gated" &&
- * turnActive` and emits `gated_hold` instead of draining the inbox. The
- * message flows to stdin only once a safe boundary is reached — here, a
- * `tool_call`→`tool_output` pair closing the last outstanding tool use —
- * and only once a `session_init` runtime event has landed (`hasSession`
- * is a `reduceApmGatedFlushReadiness` prerequisite). This test drives
- * that whole path through the public `AgentProcessManager` + a fake
- * session (not just the pure reducer), proving the executor's
- * `runtime_signal` forwarding AND the `gated_hold` logging path (via an
- * injected logger spy) both work end to end.
- */
- it(`[${label}] holds a mid-turn wake until a safe boundary (session_init, then tool_call/tool_output) instead of sending immediately`, async () => {
- const session = fakeSession();
- const logger = stubLogger();
- const mgr = makeManager(bucket.sample, session, logger);
-
- mgr.deliver("a1", { seq: 1, text: "first" });
- session.startResolver?.();
- await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "sess_1" });
-
- mgr.deliver("a1", { seq: 2, text: "mid-turn wake" });
-
- // Held, not sent — and a gated_hold was logged for the mid-turn wake.
- expect(session.sendCalls).toEqual([]);
- expect(
- logger.calls.info.some(
- ([m, d]) => m === "gated busy message held" && (d[0] as any).reason === "mid_turn_wake",
- ),
- ).toBe(true);
-
- // A tool_call/tool_output pair is the next safe boundary — the
- // single outstanding tool closes, readiness passes, the held message
- // flushes as mode:"busy".
- session.fire("runtime_event", { kind: "tool_call", name: "shell", input: {} });
- session.fire("runtime_event", { kind: "tool_output", name: "shell" });
+ manager.register("agent");
+ expect(() => manager.deliver("agent", { text: "hello" }))
+ .toThrow("a public AgentSession factory is required");
+ });
- expect(session.sendCalls).toEqual([{ text: "mid-turn wake", mode: "busy" }]);
+ it.each(BUILTIN_BACKEND_IDS)("%s registers and delivers without a lifecycle descriptor", (id) => {
+ const manager = new AgentProcessManager({
+ driverFor: () => ({
+ id,
+ capabilities: {} as never,
+ probe: async () => ({ status: "unhealthy" as const, error: {} as never, capabilities: {} as never }),
+ }),
+ baseContextFor: (agentId) => ({ agentId, workingDirectory: "/tmp" }),
+ sessionFactory: () => fakeSession(),
});
- }
-});
-
-describe("AgentProcessManager capability contract — Codex fileChange tool_call/tool_output fix (§9c)", () => {
- /**
- * Proves 9c's fix end to end, not just its `ParsedEvent` shape (that part
- * is covered by `codexEventNormalizer.test.ts`): before the fix,
- * `handleItemCompleted` had no `fileChange` case, so a `fileChange`
- * `tool_call` would open `outstandingToolUses` and it would never close —
- * permanently blocking mid-turn flushes for the rest of that turn. Uses
- * the real `CodexDriver` capability profile via the same fake-session
- * harness as the gated/queue bucket tests above.
- */
- it("a fileChange tool_call immediately followed by its tool_output closes outstandingToolUses back to 0 and unblocks a held message", async () => {
- const codexDriver = getDriver("codex");
- const session = fakeSession();
- const mgr = makeManager(codexDriver, session);
-
- mgr.deliver("a1", { seq: 1, text: "first" });
- session.startResolver?.();
- await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "sess_1" });
-
- mgr.deliver("a1", { seq: 2, text: "mid-turn wake" });
- expect(session.sendCalls).toEqual([]); // held — gated mid-turn wake
-
- session.fire("runtime_event", { kind: "tool_call", name: "file_change", input: {} });
- session.fire("runtime_event", { kind: "tool_output", name: "file_change" });
-
- expect(session.sendCalls).toEqual([{ text: "mid-turn wake", mode: "busy" }]);
+ manager.register("agent");
+ expect(manager.deliver("agent", { text: "hello" })).toBe(true);
});
-});
-describe("AgentProcessManager capability contract — bucket sanity", () => {
- it("the registered drivers still contain at least one direct/steer profile and one gated/queue profile (catches an accidental capability drift silently disabling the contracts above)", () => {
- expect(directSteerBuckets.length).toBeGreaterThan(0);
- expect(gatedQueueBuckets.length).toBeGreaterThan(0);
- });
+ it.each(BUILTIN_BACKEND_IDS)("%s sends a working wake through the shared session boundary", async (id) => {
+ const session = fakeSession();
+ const send = vi.spyOn(session, "send");
+ const manager = new AgentProcessManager({
+ driverFor: () => ({
+ id,
+ capabilities: {} as never,
+ probe: async () => ({ status: "unhealthy" as const, error: {} as never, capabilities: {} as never }),
+ }),
+ baseContextFor: (agentId) => ({ agentId, workingDirectory: "/tmp" }),
+ sessionFactory: () => session,
+ });
- it("the gated/queue bucket contains BOTH claude and codex, sharing one identical profile (see plans/wire-gated-busy-steering-daemon.md §9a) — catches a future capability drift between the two silently splitting the bucket", () => {
- expect(gatedQueueBuckets).toHaveLength(1);
- expect(gatedQueueBuckets[0]!.driverIds.slice().sort()).toEqual(["claude", "codex"]);
- });
+ manager.register("agent");
+ expect(manager.deliver("agent", { id: "initial", text: "initial" })).toBe(true);
+ await vi.waitFor(() => expect(manager.snapshot().agents.agent?.status).toBe("running"));
- it("the direct/steer bucket contains exactly pi and kimi — codex moved to gated/queue, NOT just pi alone", () => {
- expect(directSteerBuckets.flatMap((b) => b.driverIds).sort()).toEqual(["kimi", "pi"]);
+ expect(manager.deliver("agent", { id: "working", text: "working" })).toBe(true);
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(send).toHaveBeenCalledWith(expect.objectContaining({ id: "working", text: expect.stringContaining("working") }));
});
-});
-// #4 capability-unify equivalence table (executable). `busyDeliveryMode` and
-// `supportsStdinNotification` are no longer declared on Driver — they derive
-// from `lifecycle`. This pins that the DERIVED values equal the pre-unify
-// literal declarations for EVERY registered driver, byte-for-byte. If a driver
-// is added/changed such that the derivation would differ from its intended
-// mode, this fails — which is the point: the derivation IS the contract now.
-describe("AgentProcessManager capability contract — #4 lifecycle-derived equivalence", () => {
- // The authoritative pre-unify values (from daemon-capability-unify.md's table).
- const EXPECTED: Record<string, { busyDeliveryMode: "direct" | "gated" | "none"; supportsStdinNotification: boolean }> = {
- claude: { busyDeliveryMode: "gated", supportsStdinNotification: true },
- codex: { busyDeliveryMode: "gated", supportsStdinNotification: true },
- kimi: { busyDeliveryMode: "direct", supportsStdinNotification: true },
- pi: { busyDeliveryMode: "direct", supportsStdinNotification: true },
- gemini: { busyDeliveryMode: "none", supportsStdinNotification: false },
- copilot: { busyDeliveryMode: "none", supportsStdinNotification: false },
- cursor: { busyDeliveryMode: "none", supportsStdinNotification: false },
- opencode: { busyDeliveryMode: "none", supportsStdinNotification: false },
- antigravity: { busyDeliveryMode: "none", supportsStdinNotification: false },
- };
-
- it("every registered driver is in the equivalence table (guards against an unlisted new driver)", () => {
- expect(listRuntimeIds().slice().sort()).toEqual(Object.keys(EXPECTED).sort());
+ it("manager and createDaemon contain no backend lifecycle or transport branch", () => {
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ const managerSource = fs.readFileSync(path.join(here, "managerRuntime.ts"), "utf8");
+ const daemonSource = fs.readFileSync(path.join(here, "..", "daemon", "createDaemon.ts"), "utf8");
+ for (const source of [managerSource, daemonSource]) {
+ expect(source).not.toMatch(/driver\.lifecycle|busyDeliveryMode|supportsStdinNotification|createSession\s*\(/);
+ }
});
-
- for (const id of listRuntimeIds()) {
- it(`${id}: derived busyDeliveryMode + supportsStdinNotification equal the pre-unify values`, () => {
- const lifecycle = getDriver(id).lifecycle;
- const expected = EXPECTED[id];
- expect(expected, `driver ${id} missing from EXPECTED table`).toBeDefined();
- expect(busyDeliveryModeOf(lifecycle)).toBe(expected!.busyDeliveryMode);
- expect(supportsStdinNotificationOf(lifecycle)).toBe(expected!.supportsStdinNotification);
- });
- }
});
diff --git a/src/daemon/src/manager/managerPolicy.test.ts b/src/daemon/src/manager/managerPolicy.test.ts
index cc80b27f6..c2d47a2aa 100644
--- a/src/daemon/src/manager/managerPolicy.test.ts
+++ b/src/daemon/src/manager/managerPolicy.test.ts
@@ -6,38 +6,111 @@ import {
type ManagerState,
type AgentState,
type AgentStatus,
- type AgentRuntimeCaps,
-} from "./managerPolicy";
-import { createInitialApmGatedSteeringState } from "../runtime/apmStateMachine";
+} from "./managerPolicy.js";
-const PERSISTENT_GATED: AgentRuntimeCaps = {
+interface LegacyCaps {
+ lifecycleKind: "persistent" | "per_turn";
+ supportsStdinNotification: boolean;
+ busyDeliveryMode: "gated" | "direct" | "none";
+}
+const PERSISTENT_GATED: LegacyCaps = {
lifecycleKind: "persistent",
supportsStdinNotification: true,
busyDeliveryMode: "gated",
};
-/** Matches Pi/Kimi — NOT Codex, which this plan moves to "gated". */
-const PERSISTENT_DIRECT: AgentRuntimeCaps = {
+/** Matches Pi — NOT Codex, which this plan moves to "gated". */
+const PERSISTENT_DIRECT: LegacyCaps = {
lifecycleKind: "persistent",
supportsStdinNotification: true,
busyDeliveryMode: "direct",
};
-const PER_TURN: AgentRuntimeCaps = {
+const PER_TURN: LegacyCaps = {
lifecycleKind: "per_turn",
supportsStdinNotification: false,
busyDeliveryMode: "none",
};
-function register(state: ManagerState, agentId: string, caps: AgentRuntimeCaps): ManagerState {
- return reduceManager(state, { type: "register", agentId, caps }).state;
+function register(state: ManagerState, agentId: string, _caps: LegacyCaps): ManagerState {
+ return reduceManager(state, { type: "register", agentId }).state;
+}
+
+const SESSION_INSTANCE = "session-instance-a";
+
+function spawnRoot(state: ManagerState, nowMs: number, turnId = "turn-a"): ManagerState {
+ let next = reduceManager(state, {
+ type: "attach_session",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ nowMs,
+ }).state;
+ next = reduceManager(next, {
+ type: "turn_started",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId,
+ commandIds: [],
+ nowMs,
+ }).state;
+ return reduceManager(next, { type: "spawned", agentId: "a", nowMs }).state;
+}
+
+function completeRoot(state: ManagerState, turnId: string, nowMs: number) {
+ return reduceManager(state, {
+ type: "turn_completed",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId,
+ nowMs,
+ });
+}
+
+function workRoot(state: ManagerState, turnId: string, nowMs: number): ManagerState {
+ return reduceManager(state, {
+ type: "turn_work",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId,
+ nowMs,
+ }).state;
+}
+
+function startAdmission(
+ state: ManagerState,
+ commandId: string,
+ nowMs: number,
+ sessionInstanceId = SESSION_INSTANCE,
+): ManagerState {
+ return reduceManager(state, {
+ type: "admission_started",
+ agentId: "a",
+ sessionInstanceId,
+ commandId,
+ exactAgentMsg: { id: commandId, text: commandId },
+ mode: "idle",
+ requeueOnFailure: true,
+ nowMs,
+ }).state;
}
describe("reduceManager — single-flight spawn", () => {
+ it("ignores a stale session close", () => {
+ let state = register(createInitialManagerState(), "a", PERSISTENT_GATED);
+ state = spawnRoot(state, 1);
+ const result = reduceManager(state, {
+ type: "session_closed",
+ agentId: "a",
+ sessionInstanceId: "stale-session",
+ nowMs: 2,
+ });
+ expect(result).toEqual({ state, effects: [] });
+ });
+
it("first wake from idle spawns; second wake while starting does NOT spawn again", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_GATED);
const r1 = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 });
- expect(r1.effects).toEqual([{ type: "spawn", agentId: "a", prompt: "m1", resumeSessionId: null }]);
+ expect(r1.effects).toEqual([{ type: "spawn", agentId: "a", messages: [{ text: "m1" }], resumeSessionId: null }]);
expect(r1.state.agents.a.status).toBe("starting");
// Mid-start second wake: queue only, no second spawn (single-flight).
@@ -55,28 +128,14 @@ describe("reduceManager — single-flight spawn", () => {
});
describe("reduceManager — steering a running persistent agent", () => {
- it("gated: wake while running+turnActive is HELD, not steered — message stays in inbox", () => {
- let s = createInitialManagerState();
- s = register(s, "a", PERSISTENT_GATED);
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state; // running, turnActive
-
- const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 3 });
- expect(r.effects).toEqual([
- { type: "gated_hold", agentId: "a", reason: "mid_turn_wake", blockedReason: "idle", recentEvents: [] },
- ]);
- // Held, not dropped.
- expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["m2"]);
- });
-
- it("direct (Pi/Kimi profile): wake while running+turnActive still steers as busy immediately — regression guard, gating must not affect non-gated drivers", () => {
+ it("direct (Pi profile): wake while running+turnActive still steers as busy immediately — regression guard, gating must not affect non-gated drivers", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_DIRECT);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state; // running, turnActive
+ s = spawnRoot(s, 2); // running, turnActive
const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 3 });
- expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "m2", mode: "busy" }]);
+ expect(r.effects).toEqual([{ type: "send", agentId: "a", message: { text: "m2" }, mode: "busy" }]);
// Never held for a direct driver.
expect(r.effects.some((e) => e.type === "gated_hold")).toBe(false);
});
@@ -85,158 +144,62 @@ describe("reduceManager — steering a running persistent agent", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
- s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 3 }).state; // running, turnActive=false, idle
+ s = spawnRoot(s, 2);
+ s = completeRoot(s, "turn-a", 3).state; // running, turnActive=false, idle
const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 4 });
- expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "m2", mode: "idle" }]);
+ expect(r.effects).toEqual([{ type: "send", agentId: "a", message: { text: "m2" }, mode: "idle" }]);
});
it("re-waking a hibernating-but-alive persistent agent (running, turnActive=false) sets turnActive=true on commit — mirrors onTurnEnd's redeliver branch", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
- s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 3 }).state; // running, turnActive=false, idle
+ s = spawnRoot(s, 2);
+ s = completeRoot(s, "turn-a", 3).state; // running, turnActive=false, idle
expect(s.agents.a.turnActive).toBe(false);
const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 4 });
- expect(r.state.agents.a.turnActive).toBe(true);
- });
-});
-
-describe("reduceManager — none-driver (per-turn) mid-turn wake — regression", () => {
- it("wake while running (per-turn, mid-turn) stays queued for the next spawn; no send", () => {
- let s = createInitialManagerState();
- s = register(s, "a", PER_TURN);
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state; // running, turnActive
-
- const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 3 });
- expect(r.effects).toEqual([]);
- expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["m2"]);
+ expect(r.state.agents.a.turnActive).toBe(false);
+ s = startAdmission(r.state, "m2", 4);
+ expect(s.agents.a.turnActive).toBe(true);
});
-});
-
-describe("reduceManager — onRuntimeSignal (gated tool/compaction/review boundaries)", () => {
- /** Register + wake + spawn + session_init — a running, turnActive, gated agent with a known session. */
- function gatedRunningWithSession(): ManagerState {
- let s = createInitialManagerState();
- s = register(s, "a", PERSISTENT_GATED);
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
- s = reduceManager(s, { type: "session", agentId: "a", sessionId: "sess_1" }).state;
- return s;
- }
- /** Same, but WITHOUT a session_init — for the missing_session test. */
- function gatedRunningNoSession(): ManagerState {
+ it("restores an idle delivery to the inbox when the session rejects admission", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_GATED);
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
- return s;
- }
-
- it("tool_call then tool_output (single outstanding tool) flushes a held message as busy, draining the inbox", () => {
- let s = gatedRunningWithSession();
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state; // held (gated_hold)
-
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 4 }).state;
- const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 5 });
-
- expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "busy" }]);
- expect(r.state.agents.a.inbox).toEqual([]);
- });
-
- it("tool_call/tool_output boundary WITHOUT a prior session_init is held with blockedReason: missing_session", () => {
- let s = gatedRunningNoSession();
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;
-
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 4 }).state;
- const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 5 });
-
- expect(r.effects).toEqual([
- { type: "gated_hold", agentId: "a", reason: "tool_batch_complete", blockedReason: "missing_session", recentEvents: expect.any(Array) },
- ]);
- expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["held"]);
- });
-
- it("two nested tool_calls, only one tool_output closes (outstandingToolUses stays > 0) — flush is attempted but blocked with outstanding_tool_uses, not missing_session", () => {
- let s = gatedRunningWithSession();
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;
-
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 4 }).state;
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 5 }).state; // outstandingToolUses = 2
- const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 6 }); // -> 1, still > 0
-
- expect(r.effects).toEqual([
- { type: "gated_hold", agentId: "a", reason: "tool_batch_complete", blockedReason: "outstanding_tool_uses", recentEvents: expect.any(Array) },
- ]);
- expect(r.state.agents.a.apm.outstandingToolUses).toBe(1);
- });
-
- it("compaction_started then compaction_finished flushes a held message on compaction_finished", () => {
- let s = gatedRunningWithSession();
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;
-
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "compaction_started", nowMs: 4 }).state;
- expect(s.agents.a.apm.compacting).toBe(true);
- const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "compaction_finished", nowMs: 5 });
-
- expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "busy" }]);
- });
-
- it("review_started then review_finished flushes a held message on review_finished", () => {
- let s = gatedRunningWithSession();
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;
-
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "review_started", nowMs: 4 }).state;
- expect(s.agents.a.apm.reviewing).toBe(true);
- const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "review_finished", nowMs: 5 });
-
- expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "busy" }]);
- });
-
- it("an error disables tool-boundary flushing until the next turn_end — a later tool_output boundary is held with blockedReason: tool_boundary_flush_disabled, not missing_session", () => {
- let s = gatedRunningWithSession();
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "error", nowMs: 3 }).state;
- expect(s.agents.a.apm.toolBoundaryFlushDisabled).toBe(true);
-
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 4 }).state;
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 5 }).state;
- const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 6 });
-
- expect(r.effects).toEqual([
- { type: "gated_hold", agentId: "a", reason: "tool_batch_complete", blockedReason: "tool_boundary_flush_disabled", recentEvents: expect.any(Array) },
- ]);
- });
-
- it("turn_end while a message is still held flushes it as mode:idle — unchanged, independent of hasSession/phase", () => {
- let s = gatedRunningNoSession(); // no session_init at all
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;
-
- const r = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 4 });
- expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "idle" }]);
- });
-
- it("turn_end resets the gated phase — a stale compacting flag from the PRIOR turn does not block a flush in the NEXT turn", () => {
- let s = gatedRunningWithSession();
-
- // Turn 1: enter compacting, never finish it.
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "compaction_started", nowMs: 3 }).state;
- expect(s.agents.a.apm.compacting).toBe(true);
- s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 4 }).state;
-
- // Turn 2: session_id persists across turn_end; re-spawn for the new turn.
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 5 }).state;
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 6 }).state;
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 7 }).state;
- const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 8 });
-
- // If `compacting` had leaked across turn_end, this would be blocked with
- // blockedReason: "compacting" instead of flushing.
- expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "busy" }]);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { id: "one", text: "first" }, nowMs: 1 }).state;
+ s = spawnRoot(s, 2);
+ s = completeRoot(s, "turn-a", 3).state;
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { id: "two", text: "retry me" }, nowMs: 4 }).state;
+ s = startAdmission(s, "two", 4);
+ expect(s.agents.a).toMatchObject({ turnActive: true, inbox: [] });
+
+ const failed = reduceManager(s, {
+ type: "admission_settled",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ commandId: "two",
+ outcome: "failed",
+ });
+ expect(failed.effects).toEqual([{
+ type: "requeue_delivery",
+ agentId: "a",
+ message: { id: "two", text: "two" },
+ mode: "idle",
+ }]);
+ const rejected = reduceManager(failed.state, {
+ type: "delivery_rejected",
+ agentId: "a",
+ message: { id: "two", text: "two" },
+ mode: "idle",
+ });
+ expect(rejected.effects).toEqual([]);
+ expect(rejected.state.agents.a).toMatchObject({
+ turnActive: false,
+ lastDeliverAt: null,
+ inbox: [{ id: "two", text: "two" }],
+ });
});
});
@@ -245,70 +208,35 @@ describe("reduceManager — turn_end behavior", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ s = spawnRoot(s, 2);
// queue while running but pretend not steered: directly push via wake after turn?
// Simulate a message arriving then the turn ending with it still queued:
s = { ...s, agents: { ...s.agents, a: { ...s.agents.a, inbox: [{ text: "queued" }] } } };
- const r = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 5 });
- expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "queued", mode: "idle" }]);
- expect(r.state.agents.a.turnActive).toBe(true);
+ const r = completeRoot(s, "turn-a", 5);
+ expect(r.effects).toEqual([{ type: "send", agentId: "a", message: { text: "queued" }, mode: "idle" }]);
+ expect(r.state.agents.a.turnActive).toBe(false);
});
it("persistent with empty inbox goes idle and starts the idle clock", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ s = spawnRoot(s, 2);
- const r = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 5 });
+ const r = completeRoot(s, "turn-a", 5);
expect(r.effects).toEqual([]);
expect(r.state.agents.a.turnActive).toBe(false);
expect(r.state.agents.a.idleSince).toBe(5);
});
});
-describe("reduceManager — per-turn respawn", () => {
- it("exit with queued messages respawns; exit with empty inbox goes idle", () => {
- let s = createInitialManagerState();
- s = register(s, "a", PER_TURN);
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
- // A new message arrives mid-run: per-turn keeps it queued (no steer).
- const queued = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 3 });
- expect(queued.effects).toEqual([]);
-
- const onExit = reduceManager(queued.state, { type: "exit", agentId: "a" });
- expect(onExit.effects).toEqual([{ type: "spawn", agentId: "a", prompt: "m2", resumeSessionId: null }]);
-
- // Now exit again with nothing queued → idle.
- const spawned = reduceManager(onExit.state, { type: "spawned", agentId: "a", nowMs: 4 }).state;
- const idle = reduceManager(spawned, { type: "exit", agentId: "a" });
- expect(idle.effects).toEqual([]);
- expect(idle.state.agents.a.status).toBe("idle");
- });
-});
-
-describe("reduceManager — coalesce", () => {
- it("multiple queued messages drain into one joined prompt", () => {
- let s = createInitialManagerState();
- s = register(s, "a", PER_TURN);
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 3 }).state;
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m3" }, nowMs: 4 }).state;
-
- const r = reduceManager(s, { type: "exit", agentId: "a" });
- expect(r.effects).toEqual([{ type: "spawn", agentId: "a", prompt: "m2\nm3", resumeSessionId: null }]);
- });
-});
-
describe("reduceManager — tick: stall + idle hibernation", () => {
it("terminates a stalled per-turn agent past the stale threshold", () => {
let s = createInitialManagerState(100); // staleThresholdMs = 100
s = register(s, "a", PER_TURN);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state; // lastProgressAt=0, turnActive
+ s = spawnRoot(s, 0); // lastProgressAt=0, turnActive
const r = reduceManager(s, { type: "tick", nowMs: 200 });
expect(r.effects).toEqual([{ type: "terminate_stalled", agentId: "a" }]);
@@ -319,59 +247,182 @@ describe("reduceManager — tick: stall + idle hibernation", () => {
let s = createInitialManagerState(100);
s = register(s, "a", PER_TURN);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
+ s = spawnRoot(s, 0);
expect(reduceManager(s, { type: "tick", nowMs: 50 }).effects).toEqual([]);
});
+ it("fences tool blockers to the current root, clears them on reset, and restores a full stale window", () => {
+ let s = createInitialManagerState(100);
+ s = register(s, "a", PERSISTENT_GATED);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "root" }, nowMs: 0 }).state;
+ s = spawnRoot(s, 0, "root-turn");
+ s = reduceManager(s, {
+ type: "turn_tool_started",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId: "root-turn",
+ nowMs: 10,
+ }).state;
+ expect(s.agents.a.execution.lease).toMatchObject({
+ state: "active",
+ lastWorkAt: 10,
+ outstandingToolUses: 1,
+ });
+
+ const blocked = s;
+ s = reduceManager(s, {
+ type: "turn_tool_finished",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId: "child-turn",
+ nowMs: 20,
+ }).state;
+ expect(s).toBe(blocked);
+ s = reduceManager(s, {
+ type: "turn_tool_finished",
+ agentId: "a",
+ sessionInstanceId: "stale-session",
+ turnId: "root-turn",
+ nowMs: 30,
+ }).state;
+ expect(s).toBe(blocked);
+ expect(reduceManager(s, { type: "tick", nowMs: 200 }).effects).toEqual([]);
+
+ s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 210 }).state;
+ expect(s.agents.a.execution.lease).toEqual({
+ state: "active",
+ identity: { sessionInstanceId: SESSION_INSTANCE, turnId: "root-turn" },
+ lastWorkAt: 10,
+ });
+ const resetting = s;
+ s = reduceManager(s, {
+ type: "turn_tool_started",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId: "root-turn",
+ nowMs: 220,
+ }).state;
+ expect(s).toBe(resetting);
+
+ let finished = createInitialManagerState(100);
+ finished = register(finished, "a", PERSISTENT_GATED);
+ finished = reduceManager(finished, {
+ type: "wake",
+ agentId: "a",
+ message: { text: "root" },
+ nowMs: 0,
+ }).state;
+ finished = spawnRoot(finished, 0, "root-turn");
+ finished = reduceManager(finished, {
+ type: "turn_tool_started",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId: "root-turn",
+ nowMs: 10,
+ }).state;
+ finished = reduceManager(finished, {
+ type: "turn_tool_finished",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId: "root-turn",
+ nowMs: 60,
+ }).state;
+ expect(finished.agents.a.execution.lease).toEqual({
+ state: "active",
+ identity: { sessionInstanceId: SESSION_INSTANCE, turnId: "root-turn" },
+ lastWorkAt: 60,
+ });
+ expect(reduceManager(finished, { type: "tick", nowMs: 159 }).effects).toEqual([]);
+ expect(reduceManager(finished, { type: "tick", nowMs: 160 }).effects).toEqual([
+ { type: "terminate_stalled", agentId: "a" },
+ ]);
+ });
+
it("stops a persistent agent that sat idle past the idle timeout (sessionId preserved)", () => {
let s = createInitialManagerState(100_000, 100); // idleTimeoutMs = 100
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
- s = reduceManager(s, { type: "session", agentId: "a", sessionId: "sess-1" }).state;
- s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 0 }).state; // idleSince=0
+ s = spawnRoot(s, 0);
+ s = reduceManager(s, { type: "backend_session", agentId: "a", sessionId: "sess-1" }).state;
+ s = completeRoot(s, "turn-a", 0).state; // idleSince=0
const r = reduceManager(s, { type: "tick", nowMs: 200 });
expect(r.effects).toEqual([{ type: "stop", agentId: "a", reason: "idle_timeout" }]);
expect(r.state.agents.a.sessionId).toBe("sess-1"); // preserved for resume
});
- it("terminates a stalled gated agent when inbox has queued work", () => {
- let s = createInitialManagerState(100);
+ it("root progress after a stale turn_end restores active work and cancels idle hibernation", () => {
+ let s = createInitialManagerState(10_000, 100);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
- s = reduceManager(s, { type: "session", agentId: "a", sessionId: "sess-1" }).state;
- // A second wake mid-turn is held (gated) and lands in the inbox.
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 10 }).state;
- expect(s.agents.a.inbox.length).toBe(1);
- expect(s.agents.a.turnActive).toBe(true);
-
- const r = reduceManager(s, { type: "tick", nowMs: 200 });
- expect(r.effects).toEqual([{ type: "terminate_stalled", agentId: "a" }]);
- expect(r.state.agents.a.status).toBe("stopping");
+ s = spawnRoot(s, 0);
+
+ // Models the pre-fix ownership corruption: a child completion was mistaken
+ // for the root terminal, but the parent keeps emitting real tool/content
+ // progress well past the idle timeout.
+ s = completeRoot(s, "turn-a", 10).state;
+ expect(s.agents.a).toMatchObject({ turnActive: false, idleSince: 10 });
+ s = reduceManager(s, { type: "turn_work", agentId: "a", sessionInstanceId: SESSION_INSTANCE, turnId: "turn-a", nowMs: 50 }).state;
+ expect(s.agents.a).toMatchObject({ turnActive: true, idleSince: null, lastProgressAt: 50 });
+ s = reduceManager(s, { type: "turn_work", agentId: "a", sessionInstanceId: SESSION_INSTANCE, turnId: "turn-a", nowMs: 250 }).state;
+ expect(reduceManager(s, { type: "tick", nowMs: 500 }).effects).toEqual([]);
+
+ // A genuine later root completion still arms and executes normal idle stop.
+ s = completeRoot(s, "turn-a", 501).state;
+ expect(reduceManager(s, { type: "tick", nowMs: 700 }).effects).toEqual([
+ { type: "stop", agentId: "a", reason: "idle_timeout" },
+ ]);
});
- it("does NOT terminate a stalled gated agent whose inbox is empty", () => {
- let s = createInitialManagerState(100);
+ it("rejects stale/child turn terminals and activity outside the canonical execution lease", () => {
+ let s = createInitialManagerState(10_000, 100);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
- // Inbox drained on spawn; no queued work.
- expect(s.agents.a.inbox.length).toBe(0);
- expect(s.agents.a.turnActive).toBe(true);
+ s = spawnRoot(s, 0, "root-turn");
- const r = reduceManager(s, { type: "tick", nowMs: 200 });
- expect(r.effects).toEqual([]);
- expect(r.state.agents.a.status).toBe("running");
+ const beforeChildTerminal = s;
+ s = completeRoot(s, "child-turn", 10).state;
+ expect(s).toBe(beforeChildTerminal);
+ expect(s.agents.a).toMatchObject({ turnActive: true, turnId: "root-turn", idleSince: null });
+
+ s = completeRoot(s, "root-turn", 20).state;
+ s = reduceManager(s, { type: "turn_work", agentId: "a", sessionInstanceId: SESSION_INSTANCE, turnId: "child-turn", nowMs: 30 }).state;
+ expect(s.agents.a).toMatchObject({ turnActive: false, turnId: "root-turn", idleSince: 20 });
+
+ s = reduceManager(s, { type: "turn_work", agentId: "a", sessionInstanceId: SESSION_INSTANCE, turnId: "root-turn", nowMs: 40 }).state;
+ expect(s.agents.a).toMatchObject({ turnActive: true, turnId: "root-turn", idleSince: null });
+ });
+
+ it("does not let a duplicate previous terminal end a newly delivered turn before its identity is established", () => {
+ let s = createInitialManagerState(10_000, 100);
+ s = register(s, "a", PERSISTENT_GATED);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "first" }, nowMs: 0 }).state;
+ s = spawnRoot(s, 0, "turn-1");
+ s = completeRoot(s, "turn-1", 2).state;
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "second" }, nowMs: 3 }).state;
+ s = startAdmission(s, "second", 3);
+ expect(s.agents.a).toMatchObject({ turnActive: true, turnId: "turn-1", lastDeliverAt: 3 });
+
+ const beforeDuplicate = s;
+ s = completeRoot(s, "turn-1", 4).state;
+ expect(s).toBe(beforeDuplicate);
+ s = reduceManager(s, {
+ type: "turn_started",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId: "turn-2",
+ commandIds: ["second"],
+ nowMs: 5,
+ }).state;
+ expect(s.agents.a).toMatchObject({ turnActive: true, turnId: "turn-2" });
});
it("idle timeout of 0 disables hibernation", () => {
let s = createInitialManagerState(100_000, 0);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
- s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 0 }).state;
+ s = spawnRoot(s, 0);
+ s = completeRoot(s, "turn-a", 0).state;
expect(reduceManager(s, { type: "tick", nowMs: 10_000 }).effects).toEqual([]);
});
});
@@ -381,20 +432,21 @@ describe("reduceManager — tick: stall + idle hibernation", () => {
// predicates. Reproduces Olivia's wedge: a gated agent turn-ends idle, a later
// wake drain-sends (stamping lastDeliverAt, re-arming turnActive), then the
// process goes deaf — no progress, no turn_end, no exit ever follows.
-describe("reduceManager — tick: suspected-deaf detection (batch A)", () => {
+describe("reduceManager — admission timeout", () => {
// Build the exact orphan tuple: running, turnActive (from the drain-send),
// inbox empty (drained), lastDeliverAt > lastProgressAt, past the threshold.
function toDeafOrphan(staleMs = 100) {
let s = createInitialManagerState(staleMs);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
- s = reduceManager(s, { type: "session", agentId: "a", sessionId: "sess-1" }).state;
+ s = spawnRoot(s, 0);
+ s = reduceManager(s, { type: "backend_session", agentId: "a", sessionId: "sess-1" }).state;
// Turn ends → turnActive false, idleSince armed, lastProgressAt=10.
- s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 10 }).state;
+ s = completeRoot(s, "turn-a", 10).state;
// A later wake on the now-idle turn drain-sends into the (about-to-go-deaf)
// process: stamps lastDeliverAt=20, re-arms turnActive, drains the inbox.
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 20 }).state;
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { id: "m2", text: "m2" }, nowMs: 20 }).state;
+ s = startAdmission(s, "m2", 20);
return s;
}
@@ -406,7 +458,15 @@ describe("reduceManager — tick: suspected-deaf detection (batch A)", () => {
expect(s.agents.a.lastProgressAt).toBe(10); // deliver newer than last progress
const r = reduceManager(s, { type: "tick", nowMs: 200 });
- expect(r.effects).toEqual([{ type: "terminate_stalled", agentId: "a" }]);
+ expect(r.effects).toEqual([
+ { type: "requeue_delivery", agentId: "a", message: { id: "m2", text: "m2" }, mode: "idle" },
+ {
+ type: "expire_admission",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ commandIds: ["m2"],
+ },
+ ]);
expect(r.state.agents.a.status).toBe("stopping");
});
@@ -417,9 +477,13 @@ describe("reduceManager — tick: suspected-deaf detection (batch A)", () => {
it("does NOT flag a healthy agent whose process reported progress after the delivery", () => {
let s = toDeafOrphan();
- // Process answers: a progress event lands after the deliver → lastProgressAt
- // (30) overtakes lastDeliverAt (20), so the suspicion clears on its own.
- s = reduceManager(s, { type: "progress", agentId: "a", nowMs: 30 }).state;
+ s = reduceManager(s, {
+ type: "admission_settled",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ commandId: "m2",
+ outcome: "failed",
+ }).state;
expect(reduceManager(s, { type: "tick", nowMs: 200 }).effects).toEqual([]);
});
@@ -427,8 +491,9 @@ describe("reduceManager — tick: suspected-deaf detection (batch A)", () => {
let s = createInitialManagerState(100);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
+ s = spawnRoot(s, 0);
expect(s.agents.a.lastDeliverAt).toBeNull();
+ s = completeRoot(s, "turn-a", 1).state;
expect(reduceManager(s, { type: "tick", nowMs: 200 }).effects).toEqual([]);
});
@@ -456,7 +521,7 @@ describe("reduceManager — tick: reset-stuck reconcile (batch D)", () => {
let s = createInitialManagerState(100_000, 100_000, resetStuckMs);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state; // running
+ s = spawnRoot(s, 0); // running
s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 10 }).state; // resetting, resettingSince=10
s = reduceManager(s, { type: "rewake_after_reset", agentId: "a", message: { text: "rewake" } }).state;
s = reduceManager(s, { type: "exit", agentId: "a" }).state; // onExit → respawn, status=starting, resetting stays
@@ -494,7 +559,7 @@ describe("reduceManager — tick: reset-stuck reconcile (batch D)", () => {
let s = toResetStuckOrphan();
// The respawn finally reaches running → spawned → enterStable clears the
// reset window. The reconcile must go quiet.
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 150 }).state;
+ s = spawnRoot(s, 150);
expect(s.agents.a.resetting).toBe(false);
expect(s.agents.a.resettingSince).toBeNull();
expect(reduceManager(s, { type: "tick", nowMs: 10_000 }).effects).toEqual([]);
@@ -522,7 +587,7 @@ describe("reduceManager — tick: reset-stuck reconcile (batch D)", () => {
let s = createInitialManagerState(100_000, 100_000, 100);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state; // running, resetting=false
+ s = spawnRoot(s, 0); // running, resetting=false
expect(reduceManager(s, { type: "tick", nowMs: 10_000 }).effects).toEqual([]);
});
});
@@ -541,8 +606,8 @@ describe("reduceManager — tick: stopping-stuck escalation (batch L3)", () => {
let s = createInitialManagerState(1_000_000, 50, 1_000_000, stoppingStuckMs);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
- s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 0 }).state; // idleSince=0
+ s = spawnRoot(s, 0);
+ s = completeRoot(s, "turn-a", 0).state; // idleSince=0
// Idle-timeout tick (past idleTimeout=50) → status=stopping, stoppingSince stamped.
s = reduceManager(s, { type: "tick", nowMs: 100 }).state;
return s;
@@ -552,8 +617,8 @@ describe("reduceManager — tick: stopping-stuck escalation (batch L3)", () => {
let s = createInitialManagerState(1_000_000, 50, 1_000_000, 100);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
- s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 0 }).state;
+ s = spawnRoot(s, 0);
+ s = completeRoot(s, "turn-a", 0).state;
const r = reduceManager(s, { type: "tick", nowMs: 100 });
expect(r.effects).toEqual([{ type: "stop", agentId: "a", reason: "idle_timeout" }]);
expect(r.state.agents.a.status).toBe("stopping");
@@ -600,8 +665,8 @@ describe("reduceManager — tick: stopping-stuck escalation (batch L3)", () => {
// idle-timeout path isn't reachable in starting; instead drive it via a
// fresh stopping through the reset-stuck-like route is out of scope here).
// Minimal: confirm a NEW stopping stamps a fresh clock.
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 300 }).state; // running
- s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 300 }).state; // idle
+ s = spawnRoot(s, 300); // running
+ s = completeRoot(s, "turn-a", 300).state; // idle
s = reduceManager(s, { type: "tick", nowMs: 400 }).state; // idle-timeout → stopping again
expect(s.agents.a.status).toBe("stopping");
expect(s.agents.a.stoppingSince).toBe(400); // fresh clock, not the old 100
@@ -613,7 +678,7 @@ describe("reduceManager — tick: stopping-stuck escalation (batch L3)", () => {
let s = createInitialManagerState(1_000_000, 1_000_000, 1_000_000, 100);
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
+ s = spawnRoot(s, 0);
expect(s.agents.a.stoppingSince).toBeNull();
expect(reduceManager(s, { type: "tick", nowMs: 10_000 }).effects).toEqual([]);
});
@@ -624,8 +689,8 @@ describe("reduceManager — reset_session", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;
- s = reduceManager(s, { type: "session", agentId: "a", sessionId: "sess-1" }).state;
+ s = spawnRoot(s, 0);
+ s = reduceManager(s, { type: "backend_session", agentId: "a", sessionId: "sess-1" }).state;
expect(s.agents.a.sessionId).toBe("sess-1");
const prevStatus = s.agents.a.status;
const prevTurnActive = s.agents.a.turnActive;
@@ -678,7 +743,7 @@ describe("reduceManager — onWake `resetting` gate", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_DIRECT);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ s = spawnRoot(s, 2);
// Set resetting via the FSM event (bypassing onSpawned's auto-clear
// which fires before this event).
s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
@@ -694,7 +759,7 @@ describe("reduceManager — onWake `resetting` gate", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ s = spawnRoot(s, 2);
s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "unread" }, nowMs: 3 });
@@ -722,7 +787,7 @@ describe("reduceManager — onWake `resetting` gate", () => {
expect(s.agents.a.status).toBe("idle");
const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "rewake" }, nowMs: 1 });
- expect(r.effects).toEqual([{ type: "spawn", agentId: "a", prompt: "rewake", resumeSessionId: null }]);
+ expect(r.effects).toEqual([{ type: "spawn", agentId: "a", messages: [{ text: "rewake" }], resumeSessionId: null }]);
expect(r.state.agents.a.status).toBe("starting");
});
});
@@ -733,7 +798,7 @@ describe("reduceManager — onExit / onSpawned clear resetting", () => {
s = register(s, "a", PERSISTENT_DIRECT);
// Simulate live agent
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ s = spawnRoot(s, 2);
// Begin reset: mark + enqueue rewake
s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
s = reduceManager(s, { type: "rewake_after_reset", agentId: "a", message: { text: "REWAKE" } }).state;
@@ -743,7 +808,12 @@ describe("reduceManager — onExit / onSpawned clear resetting", () => {
// Kill lands → exit → drains rewake+unread into ONE respawn.
const r = reduceManager(s, { type: "exit", agentId: "a" });
- expect(r.effects).toEqual([{ type: "spawn", agentId: "a", prompt: "REWAKE\nunread", resumeSessionId: null }]);
+ expect(r.effects).toEqual([{
+ type: "spawn",
+ agentId: "a",
+ messages: [{ text: "REWAKE" }, { text: "unread" }],
+ resumeSessionId: null,
+ }]);
// Batch C semantic change (intentional): the reset window stays OPEN across
// the respawn's transient `starting` state — it closes only when the fresh
// process reaches `running` via `spawned`/`enterStable`, i.e. when context
@@ -751,7 +821,7 @@ describe("reduceManager — onExit / onSpawned clear resetting", () => {
expect(r.state.agents.a.status).toBe("starting");
expect(r.state.agents.a.resetting).toBe(true);
// ...and closes on the respawn's `spawned`.
- const r2 = reduceManager(r.state, { type: "spawned", agentId: "a", nowMs: 5 });
+ const r2 = { state: spawnRoot(r.state, 5), effects: [] };
expect(r2.state.agents.a.status).toBe("running");
expect(r2.state.agents.a.resetting).toBe(false);
expect(r2.state.agents.a.resettingSince).toBeNull();
@@ -761,7 +831,7 @@ describe("reduceManager — onExit / onSpawned clear resetting", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_DIRECT);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ s = spawnRoot(s, 2);
s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 3 }).state;
s = reduceManager(s, { type: "rewake_after_reset", agentId: "a", message: { text: "REWAKE" } }).state;
// Kill → exit → respawn emitted, status goes to the transient `starting`.
@@ -784,7 +854,7 @@ describe("reduceManager — onExit / onSpawned clear resetting", () => {
// Idle-branch deliver emits spawn (idle exempt).
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "REWAKE" }, nowMs: 1 }).state;
expect(s.agents.a.resetting).toBe(true);
- const r = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 });
+ const r = { state: spawnRoot(s, 2), effects: [] };
expect(r.state.agents.a.resetting).toBe(false);
});
@@ -802,25 +872,6 @@ describe("reduceManager — onExit / onSpawned clear resetting", () => {
expect(r.state.agents.a.resetting).toBe(false);
});
- it("onExit resets apm — a dead process's `compacting` flag doesn't leak into the respawn", () => {
- let s = createInitialManagerState();
- s = register(s, "a", PERSISTENT_GATED);
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
- s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
- // Enter compaction, then queue mid-turn work.
- s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "compaction_started", nowMs: 3 }).state;
- s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 4 }).state;
- expect(s.agents.a.apm.compacting).toBe(true);
- expect(s.agents.a.apm.phase).toBe("compacting");
- expect(s.agents.a.inbox.length).toBe(1);
-
- // Stall-recovery kill → exit. Respawn should start with a fresh apm.
- const r = reduceManager(s, { type: "exit", agentId: "a" });
- expect(r.effects[0]).toMatchObject({ type: "spawn", agentId: "a" });
- expect(r.state.agents.a.apm.compacting).toBe(false);
- expect(r.state.agents.a.apm.phase).toBe("idle");
- expect(r.state.agents.a.apm.outstandingToolUses).toBe(0);
- });
});
describe("isActivelyWorking — single source of truth for the profile pill", () => {
@@ -828,14 +879,27 @@ describe("isActivelyWorking — single source of truth for the profile pill", ()
return {
agentId: "a",
status: fields.status,
- caps: PERSISTENT_GATED,
inbox: Array.from({ length: fields.inbox }, (_, i) => ({ seq: i, text: "m" })),
sessionId: null,
+ execution: fields.turnActive
+ ? {
+ sessionInstanceId: SESSION_INSTANCE,
+ lease: {
+ state: "active",
+ identity: { sessionInstanceId: SESSION_INSTANCE, turnId: "turn-a" },
+ lastWorkAt: 0,
+ },
+ }
+ : { sessionInstanceId: SESSION_INSTANCE, lease: { state: "none", lastTerminal: null } },
+ pendingAdmissions: [],
+ turnId: fields.turnActive ? "turn-a" : null,
turnActive: fields.turnActive,
lastProgressAt: 0,
+ lastDeliverAt: null,
idleSince: null,
+ stoppingSince: null,
resetting: false,
- apm: createInitialApmGatedSteeringState(),
+ resettingSince: null,
};
}
@@ -857,3 +921,123 @@ describe("isActivelyWorking — single source of truth for the profile pill", ()
}
});
});
+
+describe("root execution lease — session epoch fences", () => {
+ it("rotates the admission ledger atomically and makes late old-session settlement/timeout inert", () => {
+ let s = createInitialManagerState(100);
+ s = register(s, "a", PERSISTENT_GATED);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { id: "old", text: "old exact text" }, nowMs: 0 }).state;
+ s = reduceManager(s, {
+ type: "attach_session",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ nowMs: 1,
+ }).state;
+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 1 }).state;
+ s = reduceManager(s, {
+ type: "admission_started",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ commandId: "reused-command",
+ exactAgentMsg: { id: "reused-command", seq: 7, text: "old exact text" },
+ mode: "busy",
+ requeueOnFailure: true,
+ nowMs: 2,
+ }).state;
+
+ const replacementSession = "session-instance-b";
+ const rotated = reduceManager(s, {
+ type: "attach_session",
+ agentId: "a",
+ sessionInstanceId: replacementSession,
+ nowMs: 3,
+ });
+ expect(rotated.state.agents.a).toMatchObject({
+ execution: { sessionInstanceId: replacementSession, lease: { state: "none", lastTerminal: null } },
+ pendingAdmissions: [],
+ });
+ expect(rotated.effects).toEqual([{
+ type: "requeue_delivery",
+ agentId: "a",
+ message: { id: "reused-command", seq: 7, text: "old exact text" },
+ mode: "busy",
+ }]);
+
+ s = startAdmission(rotated.state, "reused-command", 90, replacementSession);
+ const replacement = s.agents.a;
+ for (const outcome of ["accepted", "failed"] as const) {
+ const late = reduceManager(s, {
+ type: "admission_settled",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ commandId: "reused-command",
+ outcome,
+ });
+ expect(late.state).toBe(s);
+ expect(late.effects).toEqual([]);
+ expect(late.state.agents.a).toEqual(replacement);
+ }
+ const beforeOldTimeout = reduceManager(s, { type: "tick", nowMs: 150 });
+ expect(beforeOldTimeout.state.agents.a).toEqual(replacement);
+ expect(beforeOldTimeout.effects).toEqual([]);
+ });
+
+ it("ignores old-session admission, work, and terminal callbacks even when local turn ids are reused", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_GATED);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { id: "first", text: "first" }, nowMs: 0 }).state;
+ s = spawnRoot(s, 1, "reused-turn");
+ s = completeRoot(s, "reused-turn", 2).state;
+ s = startAdmission(s, "old-pending", 3);
+
+ const replacementSession = "session-instance-b";
+ s = reduceManager(s, {
+ type: "attach_session",
+ agentId: "a",
+ sessionInstanceId: replacementSession,
+ nowMs: 4,
+ }).state;
+ s = startAdmission(s, "new-pending", 5, replacementSession);
+ s = reduceManager(s, {
+ type: "turn_started",
+ agentId: "a",
+ sessionInstanceId: replacementSession,
+ turnId: "reused-turn",
+ commandIds: ["new-pending"],
+ nowMs: 6,
+ }).state;
+ const replacement = s.agents.a.execution;
+
+ for (const late of [
+ { type: "admission_settled", agentId: "a", sessionInstanceId: SESSION_INSTANCE, commandId: "old-pending", outcome: "accepted" },
+ { type: "turn_work", agentId: "a", sessionInstanceId: SESSION_INSTANCE, turnId: "reused-turn", nowMs: 7 },
+ { type: "turn_completed", agentId: "a", sessionInstanceId: SESSION_INSTANCE, turnId: "reused-turn", nowMs: 8 },
+ ] as const) {
+ const before = s;
+ s = reduceManager(s, late).state;
+ expect(s).toBe(before);
+ expect(s.agents.a.execution).toEqual(replacement);
+ }
+ });
+
+ it("does not overwrite an active lease with a different turn identity", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_GATED);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "first" }, nowMs: 0 }).state;
+ s = spawnRoot(s, 1, "root-turn");
+ const before = s;
+ s = reduceManager(s, {
+ type: "turn_started",
+ agentId: "a",
+ sessionInstanceId: SESSION_INSTANCE,
+ turnId: "unexpected-turn",
+ commandIds: [],
+ nowMs: 2,
+ }).state;
+ expect(s).toBe(before);
+ expect(s.agents.a.execution.lease).toMatchObject({
+ state: "active",
+ identity: { sessionInstanceId: SESSION_INSTANCE, turnId: "root-turn" },
+ });
+ });
+});
diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.ts
index 0f0229f9a..159eaa5bf 100644
--- a/src/daemon/src/manager/managerPolicy.ts
+++ b/src/daemon/src/manager/managerPolicy.ts
@@ -1,310 +1,162 @@
-/**
- * Agent process manager — pure policy core.
- *
- * This is the portable, side-effect-free brain of the manager. It decides, for
- * each agent, WHAT should happen (spawn / steer / deliver / stop / terminate)
- * given the events flowing in — but it never touches a process, timer, or
- * socket itself. The thin executor (`managerRuntime.ts`) applies the emitted
- * effects against real runtime sessions.
- *
- * It models the orchestration the daemon's `agentProcessManager` does, distilled
- * to its decisions:
- * - **single-flight**: at most one live process per agent; concurrent wakes
- * queue, never spawn a second process.
- * - **wake/sleep**: spawn when work arrives and idle; go idle (sleepable) when
- * a turn ends with an empty inbox.
- * - **queue + coalesce**: messages arriving mid-turn are buffered and either
- * steered into a persistent process or delivered to the next per-turn spawn.
- * - **stalled recovery**: if a running process makes no progress past a
- * threshold, terminate it for restart.
- *
- * Per-runtime delivery nuance (gated steering, etc.) is delegated to the
- * existing `apmStateMachine` reducers (read-only; see `onRuntimeSignal` below)
- * — this layer is the higher-level lifecycle/queue orchestrator above them.
- * See plans/wire-gated-busy-steering-daemon.md for how gating is wired up.
- */
-import type { BusyDeliveryMode, DriverLifecycle } from "../types.js";
-import {
- type ApmGatedSteeringState,
- createInitialApmGatedSteeringState,
- reduceApmGatedToolUse,
- reduceApmGatedCompaction,
- reduceApmGatedReview,
- reduceApmGatedError,
- reduceApmGatedFlushReadiness,
- reduceApmGatedRecentEvent,
-} from "../runtime/apmStateMachine.js";
export type AgentStatus = "idle" | "starting" | "running" | "stopping";
export interface AgentMsg {
- /** Monotonic sequence (for ordering / dedup); optional. */
+ id?: string;
seq?: number;
text: string;
}
-/** Static per-agent capabilities the policy needs (from the driver). */
-export interface AgentRuntimeCaps {
- lifecycleKind: DriverLifecycle["kind"];
- supportsStdinNotification: boolean;
- busyDeliveryMode: BusyDeliveryMode;
+export interface TurnIdentity {
+ sessionInstanceId: string;
+ turnId: string;
}
+export interface RootTerminal {
+ identity: TurnIdentity;
+ at: number;
+}
+
+export interface PendingAdmission {
+ sessionInstanceId: string;
+ commandId: string;
+ exactAgentMsg: AgentMsg;
+ admittedAt: number;
+ driverAcknowledged: boolean;
+ mode: "busy" | "idle";
+ requeueOnFailure: boolean;
+}
+
+export type RootLease =
+ | { state: "detached" }
+ | { state: "none"; lastTerminal: RootTerminal | null }
+ | { state: "active"; identity: TurnIdentity; lastWorkAt: number; outstandingToolUses?: number }
+ | {
+ state: "suspect_active";
+ identity: TurnIdentity;
+ lastWorkAt: number;
+ outstandingToolUses?: number;
+ reason: "work_after_terminal";
+ };
+
+export type ExecutionEpoch =
+ | { sessionInstanceId: null; lease: { state: "detached" } }
+ | { sessionInstanceId: string; lease: Exclude<RootLease, { state: "detached" }> };
+
export interface AgentState {
agentId: string;
status: AgentStatus;
- caps: AgentRuntimeCaps;
inbox: AgentMsg[];
sessionId: string | null;
- /** Whether a turn is currently in flight (between spawn/turn_start and turn_end). */
+ execution: ExecutionEpoch;
+ pendingAdmissions: PendingAdmission[];
+ turnId: string | null;
turnActive: boolean;
- /** ms timestamp of the last observed progress (event), for stall detection. */
lastProgressAt: number;
- /**
- * ms timestamp of the last `send` effect emitted toward the live process
- * (drain-send / onTurnEnd drain / gated flush); null if none this lifecycle.
- * Paired with `lastProgressAt` to detect a deaf process: a `send` was
- * dispatched (`lastDeliverAt > lastProgressAt`) yet no process-reported
- * event followed within the stale window — the message went into a stdin
- * nothing is reading. This is the ONLY signal that catches the
- * gated-no-turn_end permanent orphan, which slips both existing onTick
- * predicates. See plans/daemon-fsm-desync.md batch A.
- */
lastDeliverAt: number | null;
- /** ms timestamp since which the agent has been idle (running, no turn, empty inbox); null if not idle. */
idleSince: number | null;
- /**
- * ms timestamp at which the agent entered `stopping`; null whenever it is not
- * `stopping`. A `stop`/`terminate_stalled` effect expects the process to emit
- * `exit` shortly after, which drives `onExit` → respawn/idle. If that `exit`
- * never arrives (the stop was a no-op because the session handle was already
- * gone, or the kill didn't take), the agent is wedged in `stopping` FOREVER:
- * no onTick predicate keys on `stopping` (stalled/suspectedDeaf/idle need
- * `running`, resetStuck needs `resetting` and even guards `!== "stopping"`),
- * and `onWake` only queues in `stopping`. This clock is the ONLY escape: a
- * tick that finds `stopping` older than `stoppingStuckThresholdMs` forces the
- * agent out (see `onTick`'s stopping-stuck branch). SET at every transition
- * into `stopping`; CLEARED by `enterStable` (→ running/idle) and `onExit`.
- * See plans/daemon-fsm-desync.md batch L3 (stopping-wedge black hole).
- */
stoppingSince: number | null;
- /**
- * True during an owner-triggered reset window. Gates every inbound wake to
- * inbox-only (no `spawn`, no `send`, no `gated_hold`) EXCEPT when the
- * agent is currently `idle` — the orchestrator's idle branch relies on
- * `deliver` still emitting a spawn to kick a fresh session; if the gate
- * blocked idle too, the reset would silently reset-lock the agent. SET at
- * `begin_reset`; CLEARED exclusively by `enterStable` (the single owner of
- * every transition into a stable `running`/`idle` state — see its doc). See
- * plans/bot-reset-session-v2.md and plans/daemon-fsm-desync.md batch C.
- */
resetting: boolean;
- /**
- * ms timestamp at which the current reset window began (`begin_reset`); null
- * when not resetting. Owned by this (recovery) layer alongside `resetting`
- * itself — SET at `begin_reset`, cleared by `enterStable`. Batch D's
- * reconcile READS it to detect a reset that never converged (`resetting`
- * still true, `resettingSince` older than the stale window ⇒ the clearing
- * event never arrived), then escalates through `enterStable` — state
- * ownership here, detection ownership there. See plans/daemon-fsm-desync.md
- * batch C/D.
- */
resettingSince: number | null;
- /**
- * Coarse gated-steering phase (tool/compaction/review boundaries). Only
- * meaningfully consulted when `caps.busyDeliveryMode === "gated"`; kept on
- * every agent (harmless/unused otherwise) so the reducer set never needs a
- * null-check.
- */
- apm: ApmGatedSteeringState;
}
-/**
- * An agent counts as actively working iff its process is `running` AND it has
- * work in hand — a turn in flight, or queued inbox not yet drained into a turn.
- * `running` alone is not enough: a persistent agent stays `running` for up to
- * `idleTimeoutMs` after a turn ends with an empty inbox, which is genuinely
- * idle. Single source of truth for both the activity derivation and the
- * durability re-assert, so they can never disagree.
- */
export function isActivelyWorking(agent: AgentState): boolean {
- return agent.status === "running" && (agent.turnActive || agent.inbox.length > 0);
+ return agent.status === "running"
+ && (leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length > 0);
}
export interface ManagerState {
agents: Record<string, AgentState>;
- /** Stall threshold: no progress for this long while running ⇒ terminate. */
staleThresholdMs: number;
- /**
- * Idle hibernation threshold: a persistent keep-alive process that has sat
- * idle (turn ended, inbox empty) for this long is stopped to free resources.
- * Its sessionId is preserved so the next wake resumes. 0/∞ disables.
- */
idleTimeoutMs: number;
- /**
- * Reset-window convergence threshold: `resetting` stuck true past this long
- * (measured from `resettingSince`) ⇒ the reconcile watchdog escalates. See
- * `DEFAULT_RESET_STUCK_THRESHOLD_MS`.
- */
resetStuckThresholdMs: number;
- /**
- * Stopping-stuck escalation threshold: `status === "stopping"` for longer than
- * this (from `stoppingSince`) ⇒ the process's `exit` never arrived, so force
- * the agent out of the black hole. See `DEFAULT_STOPPING_STUCK_THRESHOLD_MS`.
- */
stoppingStuckThresholdMs: number;
}
-/* ------------------------------------------------------------------ */
-/* Events (inputs) and Effects (outputs) */
-/* ------------------------------------------------------------------ */
-
export type ManagerEvent =
- | { type: "register"; agentId: string; caps: AgentRuntimeCaps }
+ | { type: "register"; agentId: string }
| { type: "wake"; agentId: string; message: AgentMsg; nowMs: number }
| { type: "spawned"; agentId: string; nowMs: number }
- | { type: "session"; agentId: string; sessionId: string }
- | { type: "progress"; agentId: string; nowMs: number }
- /**
- * `endReason:"errored"` is set when a turn ended NON-cleanly — either a
- * mid-turn runtime `error` OR a `terminate_stalled` kill (managerRuntime
- * buffers the cause, stamps it here on the trailing turn_end). Absent = clean
- * turn-end. STRICTLY BINARY (single literal, not a union) so the rewake gate
- * keyed on `=== "errored"` can't be silently widened — red line 1. The CAUSE
- * rides on the separate `terminationCause` field (for B2 policy branching:
- * `killed_stalled` gets a tighter rewake bound than `runtime_error` since an
- * input-caused hang recurs deterministically); `errorDetail` is free-text.
- * B1 only RECORDS these (trace); the rewake policy that consumes them is B2.
- * See plans/daemon-runtime-error-rewake.md.
- */
+ | { type: "backend_session"; agentId: string; sessionId: string }
+ | { type: "attach_session"; agentId: string; sessionInstanceId: string; nowMs: number }
| {
- type: "turn_end";
+ type: "admission_started";
agentId: string;
+ sessionInstanceId: string;
+ commandId: string;
+ exactAgentMsg: AgentMsg;
+ mode: "busy" | "idle";
+ requeueOnFailure: boolean;
+ nowMs: number;
+ }
+ | {
+ type: "admission_settled";
+ agentId: string;
+ sessionInstanceId: string;
+ commandId: string;
+ outcome: "accepted" | "failed";
+ }
+ | {
+ type: "admission_acknowledged";
+ agentId: string;
+ sessionInstanceId: string;
+ commandId: string;
+ }
+ | {
+ type: "turn_started";
+ agentId: string;
+ sessionInstanceId: string;
+ turnId: string;
+ commandIds: readonly string[];
+ nowMs: number;
+ }
+ | { type: "turn_work"; agentId: string; sessionInstanceId: string; turnId: string; nowMs: number }
+ | { type: "turn_tool_started"; agentId: string; sessionInstanceId: string; turnId: string; nowMs: number }
+ | { type: "turn_tool_finished"; agentId: string; sessionInstanceId: string; turnId: string; nowMs: number }
+ | {
+ type: "turn_completed";
+ agentId: string;
+ sessionInstanceId: string;
nowMs: number;
endReason?: "errored";
+ turnId: string;
terminationCause?: "runtime_error" | "killed_stalled";
errorDetail?: string;
}
- /**
- * `exitCode`/`exitSignal`/`abnormal` are the RAW PHYSICAL termination fact of
- * the process, recorded for fsm-trace forensics (T1,
- * plans/daemon-trace-completeness-charter.md) — how the process died, for
- * EVERY exit path, so a hard exit (segfault/OOM/external SIGKILL, which
- * bypasses the normalizer and emits no turn_end) is distinguishable from a
- * clean exit in the trace. OBSERVABILITY ONLY: `onExit` must NOT branch its
- * respawn-vs-idle decision on these (red line — kept read-only). What the exit
- * MEANS in FSM terms (deliberate kill vs crash) is a separate semantic layer
- * left to T3, which may only LAYER fields on top, never overwrite these.
- */
+ | { type: "session_closed"; agentId: string; sessionInstanceId: string }
| {
type: "exit";
agentId: string;
exitCode?: number | null;
exitSignal?: string | null;
abnormal?: boolean;
- /**
- * Present when this exit followed a LAUNCH failure (never established):
- * the reason string reportSpawnFailure recorded — the SAME value the web
- * audit gets (ENOENT / handshake_timeout / pre_handshake_exit /
- * spawn_threw / a Node error code). T2 (audit↔trace two-skins closure,
- * plans/daemon-trace-completeness-charter.md): without it, a
- * failed-to-start exit is a bare exit in the trace, indistinguishable from
- * a clean one. Orthogonal to exitCode/exitSignal (a launch failure often
- * has no real code/signal) — consumers detect "was it a launch failure" by
- * this field's presence, not by guessing code/signal combos. Observability
- * only; `onExit` must not branch on it.
- */
spawnFailureReason?: string | null;
- /**
- * The FSM-level SEMANTIC of this exit, LAYERED on the physical fact above
- * (T3, plans/daemon-trace-completeness-charter.md): `killed_stalled` (stall
- * watchdog SIGKILL — same word as B1's turn_end-path `terminationCause`,
- * one concept one token), `idle_stop` (voluntary idle-timeout hibernation),
- * `force_exit` (stopping-stuck black-hole escape). Distinguishes a
- * stall-kill-via-exit from a clean idle-stop (physically identical:
- * reason=requested, signal set, abnormal=false) and labels the synthetic
- * force_exit. FORENSICS ONLY: DELIBERATELY SEPARATE from `terminationCause`
- * (which is turn_end-only and read by B2's rewake gate) so NO policy ever
- * reads this — it can never leak into a rewake decision. Never overwrites
- * the physical exit fields.
- */
terminationSemantics?: string | null;
}
| { type: "tick"; nowMs: number }
- /**
- * Owner-triggered "reset session". Nulls `AgentState.sessionId` so the next
- * `doSpawn`'s resume chain resolves to null. Does NOT change `phase` — a
- * live process keeps running; the reset only affects the NEXT spawn.
- */
| { type: "reset_session"; agentId: string }
- /**
- * Owner-triggered reset window began. Sets `agent.resetting = true`. No
- * effects — the orchestrator dispatches `deliver` (idle branch) or
- * `enqueueRewake` immediately after, and `stop()` follows on live branch.
- */
| { type: "begin_reset"; agentId: string; nowMs: number }
- /**
- * Enqueue a synthetic rewake message into the agent's inbox WITHOUT
- * emitting any effect. Used by the reset orchestrator's live/starting/
- * stopping branch — a `send` toward the ManagedSession that `stop()` is
- * about to delete would be silently dropped; the queued message rides the
- * `onExit` drain-then-spawn path instead.
- */
| { type: "rewake_after_reset"; agentId: string; message: AgentMsg }
- /**
- * Generic passthrough of a `ParsedEvent`'s `kind` string, forwarded for
- * EVERY runtime event (not just the ones the reducer acts on) so the
- * gated-steering diagnostics ring buffer (`reduceApmGatedRecentEvent`) sees
- * a complete history. See `onRuntimeSignal`.
- */
- | { type: "runtime_signal"; agentId: string; kind: string; nowMs: number };
+ | { type: "runtime_signal"; agentId: string; kind: string; nowMs: number }
+ | {
+ type: "delivery_rejected";
+ agentId: string;
+ message: AgentMsg;
+ mode: "busy" | "idle";
+ };
export type ManagerEffect =
- | { type: "spawn"; agentId: string; prompt: string; resumeSessionId: string | null }
- | { type: "send"; agentId: string; text: string; mode: "busy" | "idle" }
+ | { type: "spawn"; agentId: string; messages: AgentMsg[]; resumeSessionId: string | null }
+ | { type: "send"; agentId: string; message: AgentMsg; mode: "busy" | "idle" }
| { type: "stop"; agentId: string; reason: string }
| { type: "terminate_stalled"; agentId: string }
- /**
- * Stopping-stuck escalation (batch L3): the agent has sat in `stopping` past
- * `stoppingStuckThresholdMs` — the `exit` a prior stop/terminate expected never
- * arrived, so the agent is wedged in the one state no other watchdog can reach.
- * The runtime handler force-kills any still-tracked process (best effort; warns
- * if none is available — a possible orphan) and dispatches a SYNTHETIC `exit`
- * so the FSM traverses the normal `onExit` → respawn/idle recovery. Universal
- * backstop: covers both a no-op stop (session handle already gone) and a stop
- * that ran but produced no exit. See plans/daemon-fsm-desync.md batch L3.
- */
- | { type: "force_exit"; agentId: string; reason: string }
- /**
- * Pure observability: a gated agent has a non-empty inbox but nothing was
- * actually sent — either a mid-turn wake was held, or a boundary flush
- * attempt was still blocked. Never emitted for `direct`/`none` drivers.
- */
- | { type: "gated_hold"; agentId: string; reason: string; blockedReason: string | null; recentEvents: string[] };
-
-/** Default thresholds (ms). */
+ | { type: "expire_admission"; agentId: string; sessionInstanceId: string; commandIds: string[] }
+ | { type: "requeue_delivery"; agentId: string; message: AgentMsg; mode: "busy" | "idle" }
+ | { type: "force_exit"; agentId: string; reason: string };
+
export const DEFAULT_STALE_THRESHOLD_MS = 120_000;
export const DEFAULT_IDLE_TIMEOUT_MS = 300_000;
-/**
- * Reset-window convergence threshold: how long after a reset was initiated
- * (`begin_reset` stamps `resettingSince`) the agent may stay non-stable
- * (`resetting` still true, never reached `running`/`idle` via `enterStable`)
- * before the reconcile watchdog forces it out. Deliberately a SEPARATE constant
- * from `staleThresholdMs` — that one measures "a running turn made no progress",
- * this one measures "a restart never converged". Different physical processes,
- * independently tunable; sharing a constant would couple two unrelated timeouts.
- * See plans/daemon-fsm-desync.md batch D.
- */
export const DEFAULT_RESET_STUCK_THRESHOLD_MS = 120_000;
-/**
- * Stopping-stuck escalation threshold (ms): how long an agent may sit in
- * `stopping` — waiting for a `stop`/`terminate_stalled`'s expected `exit` — before
- * the tick concludes the exit will never come and forces the agent out (force-kill
- * the orphaned process if any + a synthetic `exit` to drive onExit→respawn). MUST
- * be comfortably larger than `SESSION_STOP_GRACE_MS` (the legitimate SIGTERM→SIGKILL
- * grace, 2s) so it never races an in-flight stop that's about to succeed — this is
- * a black-hole safety net, not a fast path. See plans/daemon-fsm-desync.md batch L3.
- */
export const DEFAULT_STOPPING_STUCK_THRESHOLD_MS = 30_000;
export interface ReduceResult {
@@ -321,46 +173,94 @@ export function createInitialManagerState(
return { agents: {}, staleThresholdMs, idleTimeoutMs, resetStuckThresholdMs, stoppingStuckThresholdMs };
}
-/* ------------------------------------------------------------------ */
-/* The reducer */
-/* ------------------------------------------------------------------ */
-
export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceResult {
switch (event.type) {
case "register":
- return withAgent(state, event.agentId, (a) => a ?? freshAgent(event.agentId, event.caps), []);
+ return withAgent(state, event.agentId, (a) => a ?? freshAgent(event.agentId), []);
case "wake":
- return onWake(state, event.agentId, event.message, event.nowMs);
+ return onWake(state, event.agentId, event.message);
case "spawned":
return mutate(state, event.agentId, (a) => {
- // Single owner of the stable-state transition: `enterStable` sets
- // status="running" AND clears the reset window (resetting/
- // resettingSince) atomically — covering the idle-branch reset path
- // (deliver → spawn directly, no `exit` fires) without a separate clear.
enterStable(a, "running");
- a.turnActive = true;
+ syncExecutionProjection(a);
+ });
+
+ case "backend_session":
+ return mutate(state, event.agentId, (a) => {
+ a.sessionId = event.sessionId;
+ });
+
+ case "attach_session": {
+ const existing = state.agents[event.agentId];
+ if (!existing) return { state, effects: [] };
+ const agent = clone(existing);
+ const effects = recoveryEffects(agent, agent.pendingAdmissions);
+ agent.pendingAdmissions = [];
+ {
+ const a = agent;
+ a.execution = { sessionInstanceId: event.sessionInstanceId, lease: { state: "none", lastTerminal: null } };
a.lastProgressAt = event.nowMs;
- // Fresh process ⇒ no outstanding unanswered delivery yet. Clearing keeps
- // the suspected-deaf detector (onTick) from carrying a prior lifecycle's
- // `lastDeliverAt` across a respawn. Redundant with `lastProgressAt` being
- // bumped here (a stale deliver would already be < progress), but explicit
- // so the fresh-lifecycle invariant doesn't rely on that coincidence.
- a.lastDeliverAt = null;
a.idleSince = null;
+ syncExecutionProjection(a);
+ }
+ return commit(state, agent, effects);
+ }
+
+ case "admission_started": {
+ const existing = state.agents[event.agentId];
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId) return { state, effects: [] };
+ return mutate(state, event.agentId, (a) => {
+ if (!matchesSession(a, event.sessionInstanceId)) return;
+ if (a.pendingAdmissions.some((entry) => entry.commandId === event.commandId)) return;
+ a.pendingAdmissions = [...a.pendingAdmissions, {
+ sessionInstanceId: event.sessionInstanceId,
+ commandId: event.commandId,
+ exactAgentMsg: event.exactAgentMsg,
+ admittedAt: event.nowMs,
+ driverAcknowledged: false,
+ mode: event.mode,
+ requeueOnFailure: event.requeueOnFailure,
+ }];
+ a.idleSince = null;
+ syncExecutionProjection(a);
});
+ }
+
+ case "admission_settled": {
+ const existing = state.agents[event.agentId];
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId) return { state, effects: [] };
+ const record = existing.pendingAdmissions.find((entry) =>
+ entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId);
+ if (!record) return { state, effects: [] };
+ const agent = clone(existing);
+ agent.pendingAdmissions = agent.pendingAdmissions.filter((entry) =>
+ entry.sessionInstanceId !== event.sessionInstanceId || entry.commandId !== event.commandId);
+ syncExecutionProjection(agent);
+ return commit(
+ state,
+ agent,
+ event.outcome === "failed" ? recoveryEffects(agent, [record]) : [],
+ );
+ }
- case "session":
+ case "admission_acknowledged": {
+ const existing = state.agents[event.agentId];
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId) return { state, effects: [] };
+ if (!existing.pendingAdmissions.some((entry) =>
+ entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId)) {
+ return { state, effects: [] };
+ }
return mutate(state, event.agentId, (a) => {
- a.sessionId = event.sessionId;
+ a.pendingAdmissions = a.pendingAdmissions.map((entry) =>
+ entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId
+ ? { ...entry, driverAcknowledged: true }
+ : entry);
});
+ }
case "reset_session":
- // No-op on an unknown agent — matches AgentProcessManager.forgetSession's
- // "safe on unknown id" contract. On a known agent, just null the
- // sessionId; phase/status/turnActive are unchanged so a live process
- // keeps running through its current turn.
if (!state.agents[event.agentId]) return { state, effects: [] };
return mutate(state, event.agentId, (a) => {
a.sessionId = null;
@@ -370,10 +270,13 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceR
if (!state.agents[event.agentId]) return { state, effects: [] };
return mutate(state, event.agentId, (a) => {
a.resetting = true;
- // Stamp the window's start so batch D's reconcile can detect a reset
- // that never converged (still resetting, `resettingSince` older than
- // the stale window ⇒ the clearing event never arrived).
a.resettingSince = event.nowMs;
+ const lease = a.execution.lease;
+ if ((lease.state === "active" || lease.state === "suspect_active") && lease.outstandingToolUses !== undefined) {
+ const unblockedLease = { ...lease };
+ delete unblockedLease.outstandingToolUses;
+ a.execution.lease = unblockedLease;
+ }
});
case "rewake_after_reset":
@@ -383,13 +286,84 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceR
a.idleSince = null;
});
- case "progress":
+ case "turn_started": {
+ const existing = state.agents[event.agentId];
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId) return { state, effects: [] };
+ const current = existing.execution.lease;
+ const nextIdentity = identityOf(event);
+ if (
+ (current.state === "active" || current.state === "suspect_active")
+ && !sameIdentity(current.identity, nextIdentity)
+ ) return { state, effects: [] };
return mutate(state, event.agentId, (a) => {
+ if (!matchesSession(a, event.sessionInstanceId)) return;
+ const lease = a.execution.lease;
+ const identity = identityOf(event);
+ if ((lease.state === "active" || lease.state === "suspect_active") && !sameIdentity(lease.identity, identity)) return;
+ const startedCommands = new Set(event.commandIds);
+ a.pendingAdmissions = a.pendingAdmissions.filter((entry) => !startedCommands.has(entry.commandId));
+ a.execution.lease = { state: "active", identity, lastWorkAt: event.nowMs };
a.lastProgressAt = event.nowMs;
+ a.idleSince = null;
+ syncExecutionProjection(a);
+ });
+ }
+
+ case "turn_work": {
+ const existing = state.agents[event.agentId];
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId) return { state, effects: [] };
+ const current = existing.execution.lease;
+ const nextIdentity = identityOf(event);
+ const matchesActive = (current.state === "active" || current.state === "suspect_active")
+ && sameIdentity(current.identity, nextIdentity);
+ const matchesTerminal = current.state === "none"
+ && current.lastTerminal !== null
+ && sameIdentity(current.lastTerminal.identity, nextIdentity);
+ if (!matchesActive && !matchesTerminal) return { state, effects: [] };
+ return mutate(state, event.agentId, (a) => {
+ if (!matchesSession(a, event.sessionInstanceId)) return;
+ const lease = a.execution.lease;
+ const identity = identityOf(event);
+ if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity)) {
+ a.execution.lease = { ...lease, lastWorkAt: event.nowMs };
+ } else {
+ const terminal = lease.state === "none" ? lease.lastTerminal : null;
+ if (!terminal || !sameIdentity(terminal.identity, identity)) return;
+ a.execution.lease = {
+ state: "suspect_active",
+ identity,
+ lastWorkAt: event.nowMs,
+ reason: "work_after_terminal",
+ };
+ }
+ a.lastProgressAt = event.nowMs;
+ a.idleSince = null;
+ syncExecutionProjection(a);
});
+ }
+
+ case "turn_tool_started":
+ return onTurnToolLifecycle(state, event, "started");
- case "turn_end":
- return onTurnEnd(state, event.agentId, event.nowMs);
+ case "turn_tool_finished":
+ return onTurnToolLifecycle(state, event, "finished");
+
+ case "turn_completed":
+ return onTurnCompleted(state, event.agentId, event.sessionInstanceId, event.nowMs, event.turnId);
+
+ case "session_closed":
+ if (state.agents[event.agentId]?.execution.sessionInstanceId !== event.sessionInstanceId) {
+ return { state, effects: [] };
+ }
+ {
+ const agent = clone(state.agents[event.agentId]!);
+ const closing = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId === event.sessionInstanceId);
+ agent.pendingAdmissions = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId);
+ agent.execution = { sessionInstanceId: null, lease: { state: "detached" } };
+ agent.idleSince = null;
+ syncExecutionProjection(agent);
+ return commit(state, agent, recoveryEffects(agent, closing));
+ }
case "exit":
return onExit(state, event.agentId);
@@ -398,250 +372,152 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceR
return onTick(state, event.nowMs);
case "runtime_signal":
- return onRuntimeSignal(state, event.agentId, event.kind, event.nowMs);
+ return { state, effects: [] };
+
+ case "delivery_rejected":
+ return mutate(state, event.agentId, (a) => {
+ if (!a.inbox.some((message) => message.id === event.message.id)) {
+ a.inbox = [event.message, ...a.inbox];
+ }
+ syncExecutionProjection(a);
+ a.idleSince = null;
+ });
}
}
-/* ------------------------------------------------------------------ */
-/* Event handlers */
-/* ------------------------------------------------------------------ */
-
-function onWake(state: ManagerState, agentId: string, message: AgentMsg, nowMs: number): ReduceResult {
+function onWake(state: ManagerState, agentId: string, message: AgentMsg): ReduceResult {
const existing = state.agents[agentId];
const agent = existing ? clone(existing) : null;
if (!agent) {
- // Unknown agent — must be registered first. Drop with no effect.
return { state, effects: [] };
}
- // Reset window: gate every non-idle wake to inbox-only. Idle is exempted
- // deliberately — the orchestrator's idle branch calls `deliver` right
- // after `markResetting`, and if the gate blocked idle too the spawn would
- // never fire, so `resetting` would stay stuck forever. Idle safety is
- // fine: no live session to steer against, and the moment `deliver`'s
- // spawn effect flips status to `starting`, subsequent wakes hit the
- // regular gate branch. See plans/bot-reset-session-v2.md.
if (agent.resetting && agent.status !== "idle") {
agent.inbox = [...agent.inbox, message];
agent.idleSince = null;
return commit(state, agent, []);
}
- // Always enqueue the message first; any wake clears the idle timer.
agent.inbox = [...agent.inbox, message];
agent.idleSince = null;
- // Idle ⇒ spawn (single-flight: only from idle). Starting/stopping ⇒ just queue.
if (agent.status === "idle") {
agent.status = "starting";
- const prompt = drainInboxToPrompt(agent);
+ const messages = drainInbox(agent);
return commit(state, agent, [
- { type: "spawn", agentId, prompt, resumeSessionId: agent.sessionId },
+ { type: "spawn", agentId, messages, resumeSessionId: agent.sessionId },
]);
}
- // Running:
if (agent.status === "running") {
- // Persistent + can take stdin ⇒ steer/deliver into the live process.
- if (agent.caps.lifecycleKind === "persistent" && agent.caps.supportsStdinNotification) {
- // Gated + mid-turn: a raw stdin write right now could collide with an
- // in-flight tool call / signed thinking block / compaction / review.
- // The message is already enqueued above — hold instead of draining it;
- // `onRuntimeSignal` flushes it at the next safe boundary.
- const isGatedMidTurn = agent.caps.busyDeliveryMode === "gated" && agent.turnActive;
- if (isGatedMidTurn) {
- return commit(state, agent, [
- {
- type: "gated_hold",
- agentId,
- reason: "mid_turn_wake",
- blockedReason: agent.apm.phase,
- recentEvents: agent.apm.recentEvents,
- },
- ]);
- }
- const text = drainInboxToPrompt(agent);
- const mode = agent.turnActive ? "busy" : "idle";
- if (mode === "idle") agent.turnActive = true;
- agent.lastDeliverAt = nowMs;
- return commit(state, agent, [{ type: "send", agentId, text, mode }]);
- }
- // Per-turn or no stdin ⇒ keep queued; delivered after exit / next spawn.
- return commit(state, agent, []);
+ const messages = drainInbox(agent);
+ const mode = leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 ? "busy" : "idle";
+ return commit(state, agent, messages.map((queued) => ({ type: "send", agentId, message: queued, mode })));
}
- // starting / stopping ⇒ queue only (coalesce); handled on spawned/exit.
return commit(state, agent, []);
}
-function onTurnEnd(state: ManagerState, agentId: string, nowMs: number): ReduceResult {
+function onTurnCompleted(
+ state: ManagerState,
+ agentId: string,
+ sessionInstanceId: string,
+ nowMs: number,
+ turnId: string,
+): ReduceResult {
const existing = state.agents[agentId];
if (!existing) return { state, effects: [] };
const agent = clone(existing);
- agent.turnActive = false;
+ if (!matchesSession(agent, sessionInstanceId)) return { state, effects: [] };
+ const lease = agent.execution.lease;
+ if (lease.state !== "active" && lease.state !== "suspect_active") return { state, effects: [] };
+ const identity = { sessionInstanceId, turnId };
+ if (!sameIdentity(lease.identity, identity)) return { state, effects: [] };
+ const lastTerminal = { identity, at: nowMs };
+ agent.execution.lease = { state: "none", lastTerminal };
agent.lastProgressAt = nowMs;
- // Fresh turn ⇒ fresh gated phase; prevents a stale compacting/reviewing/
- // outstandingToolUses flag from one turn silently blocking a flush in the
- // next turn.
- agent.apm = createInitialApmGatedSteeringState();
-
- // Per-turn runtimes exit on their own; the process will emit "exit".
- if (agent.caps.lifecycleKind === "per_turn") {
- return commit(state, agent, []);
- }
-
- // Persistent: if queued messages exist, deliver them as a fresh (idle) turn.
- if (agent.inbox.length > 0 && agent.caps.supportsStdinNotification) {
- const text = drainInboxToPrompt(agent);
- agent.turnActive = true;
- agent.lastDeliverAt = nowMs;
- return commit(state, agent, [{ type: "send", agentId, text, mode: "idle" }]);
+ syncExecutionProjection(agent);
+ if (agent.inbox.length > 0) {
+ const messages = drainInbox(agent);
+ return commit(state, agent, messages.map((queued) => ({ type: "send", agentId, message: queued, mode: "idle" })));
}
- // Nothing pending ⇒ idle; start the idle-hibernation clock.
agent.idleSince = nowMs;
return commit(state, agent, []);
}
-/**
- * Handles one forwarded `ParsedEvent.kind` for gated-steering phase tracking
- * and boundary flush attempts. Only meaningfully acts when the agent is
- * `running`, `turnActive`, and declares `busyDeliveryMode: "gated"` —
- * otherwise it's a no-op (still records `recentEvents` for diagnostics via
- * `reduceApmGatedRecentEvent`, cheap and harmless).
- *
- * Pinned execution order per branch (deliberately different from
- * `session-runner.ts`, which calls `reduceApmGatedRecentEvent` first — here
- * it runs last so the ring buffer reflects the phase actually reached, not
- * the incoming phase):
- * 1. Run the kind-specific reducer and assign its `nextState`.
- * 2. Run `reduceApmGatedRecentEvent` and assign its `nextState` again.
- * 3. If the branch calls for it, attempt a flush via
- * `reduceApmGatedFlushReadiness`, reading the now-fully-updated `apm`.
- */
-function onRuntimeSignal(state: ManagerState, agentId: string, kind: string, nowMs: number): ReduceResult {
- const existing = state.agents[agentId];
- if (!existing) return { state, effects: [] };
- const agent = clone(existing);
-
- // Reset window: never emit a `send` toward the dying session, even for gated
- // drivers whose boundary flush would otherwise fire on a mid-shutdown
- // tool_output. Doing so would drain REWAKE from the inbox into a doomed
- // session and lose it before `onExit`'s drain-and-spawn runs. Still update
- // the diagnostics ring buffer so recentEvents reflects the reset window.
- const isGatedActive =
- !agent.resetting &&
- agent.status === "running" &&
- agent.turnActive &&
- agent.caps.busyDeliveryMode === "gated";
- if (!isGatedActive) {
- // Still record the event for diagnostics — cheap and harmless even when
- // not gated (the ring buffer is unused unless busyDeliveryMode is gated).
- agent.apm = reduceApmGatedRecentEvent(agent.apm, { event: kind }).nextState;
- return commit(state, agent, []);
- }
-
- let attemptFlushReason: string | null = null;
- switch (kind) {
- case "tool_call":
- agent.apm = reduceApmGatedToolUse(agent.apm, { kind }).nextState;
- break;
- case "tool_output":
- agent.apm = reduceApmGatedToolUse(agent.apm, { kind }).nextState;
- attemptFlushReason = "tool_batch_complete";
- break;
- case "compaction_started":
- case "compaction_finished":
- agent.apm = reduceApmGatedCompaction(agent.apm, { kind }).nextState;
- if (kind === "compaction_finished") attemptFlushReason = "compaction_finished";
- break;
- case "review_started":
- case "review_finished":
- agent.apm = reduceApmGatedReview(agent.apm, { kind }).nextState;
- if (kind === "review_finished") attemptFlushReason = "review_finished";
- break;
- case "error":
- agent.apm = reduceApmGatedError(agent.apm, { disableToolBoundaryFlush: true }).nextState;
- break;
- default:
- // "text" / "thinking" / "internal_progress" / "runtime_diagnostic" /
- // "telemetry" / "session_init" / "turn_end" — no phase change here;
- // "turn_end" is already handled by onTurnEnd via its own event.
- break;
+function onTurnToolLifecycle(
+ state: ManagerState,
+ event: Extract<ManagerEvent, { type: "turn_tool_started" | "turn_tool_finished" }>,
+ lifecycle: "started" | "finished",
+): ReduceResult {
+ const existing = state.agents[event.agentId];
+ if (
+ !existing
+ || existing.resetting
+ || existing.execution.sessionInstanceId !== event.sessionInstanceId
+ ) return { state, effects: [] };
+ const current = existing.execution.lease;
+ const identity = identityOf(event);
+ const matchesActive = (current.state === "active" || current.state === "suspect_active")
+ && sameIdentity(current.identity, identity);
+ const matchesTerminal = lifecycle === "started"
+ && current.state === "none"
+ && current.lastTerminal !== null
+ && sameIdentity(current.lastTerminal.identity, identity);
+ if (!matchesActive && !matchesTerminal) return { state, effects: [] };
+ if (lifecycle === "finished" && matchesActive && (current.outstandingToolUses ?? 0) === 0) {
+ return { state, effects: [] };
}
-
- agent.apm = reduceApmGatedRecentEvent(agent.apm, { event: kind }).nextState;
-
- if (attemptFlushReason === null) return commit(state, agent, []);
- // Attempting a flush on every tool_output is intentional (not just when
- // the last outstanding tool just closed): it lets `reduceApmGatedFlushReadiness`
- // be the single source of truth for "is it safe", and surfaces a
- // `gated_hold` for "one of several nested tool calls just closed" too.
- if (agent.inbox.length === 0) return commit(state, agent, []);
-
- const readiness = reduceApmGatedFlushReadiness(agent.apm, {
- isGated: true,
- hasSession: agent.sessionId != null,
- inboxLength: agent.inbox.length,
- reason: attemptFlushReason,
+ return mutate(state, event.agentId, (agent) => {
+ if (!matchesSession(agent, event.sessionInstanceId)) return;
+ const lease = agent.execution.lease;
+ if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity)) {
+ const outstandingToolUses = (lease.outstandingToolUses ?? 0) + (lifecycle === "started" ? 1 : -1);
+ if (outstandingToolUses > 0) {
+ agent.execution.lease = { ...lease, lastWorkAt: event.nowMs, outstandingToolUses };
+ } else {
+ const unblockedLease = { ...lease };
+ delete unblockedLease.outstandingToolUses;
+ agent.execution.lease = { ...unblockedLease, lastWorkAt: event.nowMs };
+ }
+ } else {
+ const terminal = lease.state === "none" ? lease.lastTerminal : null;
+ if (lifecycle !== "started" || !terminal || !sameIdentity(terminal.identity, identity)) return;
+ agent.execution.lease = {
+ state: "suspect_active",
+ identity,
+ lastWorkAt: event.nowMs,
+ outstandingToolUses: 1,
+ reason: "work_after_terminal",
+ };
+ }
+ agent.lastProgressAt = event.nowMs;
+ agent.idleSince = null;
+ syncExecutionProjection(agent);
});
- if (readiness.shouldNotify) {
- const text = drainInboxToPrompt(agent);
- agent.lastDeliverAt = nowMs;
- return commit(state, agent, [{ type: "send", agentId, text, mode: "busy" }]);
- }
- return commit(state, agent, [
- {
- type: "gated_hold",
- agentId,
- reason: attemptFlushReason,
- blockedReason: readiness.blockedReason,
- recentEvents: agent.apm.recentEvents,
- },
- ]);
}
function onExit(state: ManagerState, agentId: string): ReduceResult {
const existing = state.agents[agentId];
if (!existing) return { state, effects: [] };
const agent = clone(existing);
- agent.turnActive = false;
- // The process is gone, so `stopping` no longer applies — clear the
- // stopping-stuck clock here (covers BOTH onExit branches: the respawn path
- // sets status="starting" directly, not via enterStable, so it wouldn't be
- // cleared otherwise; the settle-idle path goes through enterStable which also
- // clears it, harmless to do twice).
+ const effects = recoveryEffects(agent, agent.pendingAdmissions);
+ agent.pendingAdmissions = [];
+ agent.execution = { sessionInstanceId: null, lease: { state: "detached" } };
agent.stoppingSince = null;
- // Fresh process ⇒ fresh gated-steering horizon. Symmetric with `onTurnEnd`;
- // prevents a dead process's `compacting` / outstanding-tool-use flags from
- // silently carrying into the next spawn and re-blocking `onWake`.
- agent.apm = createInitialApmGatedSteeringState();
- // The dead process can't answer any prior delivery — drop the outstanding
- // deliver marker so the suspected-deaf detector starts clean for the respawn.
- agent.lastDeliverAt = null;
-
- // Per-turn / reset-respawn: if messages are queued (drained rewake + unreads),
- // respawn for the next batch. `status = "starting"` is TRANSIENT — the reset
- // window (`resetting`) deliberately stays OPEN across it and closes only when
- // the fresh process reaches `running` via `spawned` → `enterStable`. This is
- // the batch-C semantic: a reset ends at "context re-established", not at "old
- // process died". If the respawn itself wedges (new process never emits
- // `spawned`), `resetting` stays true with an aging `resettingSince`, so
- // batch D's reconcile catches the stuck-in-`starting` orphan — which the old
- // "clear at onExit" behavior left invisible to every running-gated detector.
+ syncExecutionProjection(agent);
+
if (agent.inbox.length > 0) {
agent.status = "starting";
- const prompt = drainInboxToPrompt(agent);
+ const messages = drainInbox(agent);
return commit(state, agent, [
- { type: "spawn", agentId, prompt, resumeSessionId: agent.sessionId },
+ ...effects,
+ { type: "spawn", agentId, messages, resumeSessionId: agent.sessionId },
]);
}
- // No respawn (incl. the spawn-failure path: `doSpawn` dispatched an immediate
- // `exit` after draining the inbox into the failed spawn's prompt) ⇒ the agent
- // settles idle. `enterStable` closes the reset window here — the single owner
- // of clearing `resetting`, so a failed reset can never leave it stuck.
enterStable(agent, "idle");
- return commit(state, agent, []);
+ return commit(state, agent, effects);
}
function onTick(state: ManagerState, nowMs: number): ReduceResult {
@@ -650,75 +526,38 @@ function onTick(state: ManagerState, nowMs: number): ReduceResult {
for (const id of Object.keys(agents)) {
const a = agents[id];
- // Stalled recovery: running, turn in flight, no progress past threshold.
- // Gated runtimes are normally excluded from restart (their tool-batch/
- // compaction/review boundaries do the flushing), BUT a silent gated turn
- // with queued inbox has no other exit — every wake hits `gated_hold` and
- // nothing frees it. Include gated when work is backing up so `onExit`'s
- // drain-and-respawn can rescue it.
- const stalled =
- a.status === "running" &&
- a.turnActive &&
- nowMs - a.lastProgressAt >= state.staleThresholdMs &&
- (a.caps.lifecycleKind === "per_turn" ||
- (a.caps.supportsStdinNotification && a.caps.busyDeliveryMode === "direct") ||
- (a.caps.supportsStdinNotification &&
- a.caps.busyDeliveryMode === "gated" &&
- a.inbox.length > 0));
- // Suspected-deaf (plans/daemon-fsm-desync.md batch A): a `send` was
- // dispatched (`lastDeliverAt` set, and NEWER than the last process-reported
- // progress) yet the stale window elapsed with no event following it — the
- // message went into a stdin nothing is reading. This is the ONE trigger
- // that catches the `gated`-no-`turn_end` permanent orphan, which slips BOTH
- // existing predicates: `stalled`'s gated sub-clause needs `inbox.length > 0`
- // but the inbox was drained empty by the very send that stamped
- // `lastDeliverAt`, and `idleEligible` needs `!turnActive` but the drain-send
- // set `turnActive = true`. Reuses the existing `terminate_stalled` recovery
- // (SIGKILL → exit → onExit drain-respawn) — batch A adds a trigger, not a
- // new recovery path. Batch D upgrades this same suspicion to a confirmed
- // diagnosis via a liveness probe before any destructive action on the
- // runtime kinds that lack the SIGKILL backstop (SDK); here it only fires for
- // a stdin-capable persistent agent whose recovery is physically reliable.
- const suspectedDeaf =
- a.status === "running" &&
- a.caps.lifecycleKind === "persistent" &&
- a.caps.supportsStdinNotification &&
- a.lastDeliverAt !== null &&
- a.lastDeliverAt > a.lastProgressAt &&
- nowMs - a.lastDeliverAt >= state.staleThresholdMs;
- if (stalled || suspectedDeaf) {
+ const lease = a.execution.lease;
+ const stalled = a.status === "running"
+ && (lease.state === "active" || lease.state === "suspect_active")
+ && (lease.outstandingToolUses ?? 0) === 0
+ && nowMs - lease.lastWorkAt >= state.staleThresholdMs;
+ if (stalled) {
agents[id] = { ...a, status: "stopping", idleSince: null, stoppingSince: nowMs };
effects.push({ type: "terminate_stalled", agentId: id });
continue;
}
- // Reset-stuck reconcile (plans/daemon-fsm-desync.md batch D): the reset
- // window (`resetting`) is closed exclusively by `enterStable` when the agent
- // reaches a stable `running`/`idle` state. If the converging event never
- // arrives — an idle-branch spawn whose process never emits `spawned`, or an
- // onExit-respawn that wedges in `starting` — `resetting` stays true forever
- // with an aging `resettingSince`, and every wake gets gated to the inbox
- // (onWake's reset gate) and never delivered = a permanent orphan. The three
- // predicates above can't catch it: they all require `status === "running"`,
- // but a reset-stuck agent is stuck in `starting`/`stopping` (never reached
- // running, so `enterStable` never ran, so `resetting` is still true). This
- // is the ONE belief-vs-reality gap the running-keyed detectors leave open.
- // Escalate by forcing an `exit`: `onExit` drains any queued rewake and
- // respawns (or settles idle), and its `enterStable` atomically closes the
- // window — recovery REUSES C's single-owner clear, no second clear path.
- // The `status !== "stopping"` guard is what makes this NOT fire-and-assume
- // AND storm-free: the escalate flips status to `stopping`, so it can't
- // re-issue a `terminate_stalled` every tick while the (guaranteed) exit is
- // in flight — the running-keyed predicates get this for free by leaving
- // `running`, but `resetStuck` keys on `resetting` (which `enterStable`, not
- // this branch, clears) so it needs the explicit guard. Re-escalation still
- // happens correctly when it's warranted: if the forced exit's respawn wedges
- // AGAIN, onExit puts the agent back in `starting` (not `stopping`) with
- // `resetting` still true and `resettingSince` still aging, so a later tick
- // fires this anew — the recovery keeps trying until the reset converges to a
- // stable state (`enterStable` clears `resetting` → this stops firing).
- // Mutually exclusive with stalled/suspectedDeaf by the disjoint `status`
- // precondition (they need `running`; a reset-stuck orphan is in `starting`).
+ const expiredAdmission = a.status === "running"
+ && a.pendingAdmissions.filter((entry) =>
+ !entry.driverAcknowledged && nowMs - entry.admittedAt >= state.staleThresholdMs);
+ if (expiredAdmission && expiredAdmission.length > 0 && a.execution.sessionInstanceId !== null) {
+ agents[id] = {
+ ...a,
+ pendingAdmissions: a.pendingAdmissions.filter((entry) => !expiredAdmission.includes(entry)),
+ status: "stopping",
+ idleSince: null,
+ stoppingSince: nowMs,
+ };
+ effects.push(...recoveryEffects(a, expiredAdmission));
+ effects.push({
+ type: "expire_admission",
+ agentId: id,
+ sessionInstanceId: a.execution.sessionInstanceId,
+ commandIds: expiredAdmission.map((entry) => entry.commandId),
+ });
+ continue;
+ }
+
const resetStuck =
a.resetting &&
a.status !== "stopping" &&
@@ -730,43 +569,21 @@ function onTick(state: ManagerState, nowMs: number): ReduceResult {
continue;
}
- // Stopping-stuck escalation (plans/daemon-fsm-desync.md batch L3): the black
- // hole. A `stop`/`terminate_stalled` set status=`stopping` expecting the
- // process to emit `exit` (→ onExit → respawn/idle). If that `exit` never
- // comes — the stop was a no-op (session handle already gone), or the kill
- // didn't take — the agent is wedged in `stopping` PERMANENTLY: no predicate
- // above keys on `stopping` (stalled/suspectedDeaf/idle need `running`;
- // resetStuck needs `resetting` AND guards `!== "stopping"`), and `onWake`
- // only queues in `stopping` (inbox grows unboundedly, never delivered —
- // observed live: Olivia 2026-07-31 stuck 12min, inbox climbing, process
- // still alive). This is the ONE escape. Force the agent out via `force_exit`
- // (runtime handler best-effort-kills any tracked process, then dispatches a
- // SYNTHETIC `exit` so the FSM runs the normal onExit recovery). Threshold ≫
- // SESSION_STOP_GRACE_MS so it never races a legitimate in-flight stop.
- // Storm-free: `force_exit` → onExit → enterStable clears `stoppingSince`, so
- // it can't re-fire for the same stopping episode; if the respawn wedges in
- // `stopping` again, a fresh `stoppingSince` restarts the clock and it re-
- // escalates — converging until a respawn sticks.
const stoppingStuck =
a.status === "stopping" &&
a.stoppingSince !== null &&
nowMs - a.stoppingSince >= state.stoppingStuckThresholdMs;
if (stoppingStuck) {
- // Leave stoppingSince set until the synthetic exit's onExit clears it —
- // status stays `stopping` this tick, so the `!== "stopping"` shape holds
- // and nothing else touches it; the effect drives the transition out.
effects.push({ type: "force_exit", agentId: id, reason: "stopping_stuck" });
continue;
}
- // Idle hibernation: a persistent keep-alive process that has sat idle (turn
- // ended, inbox empty) past the timeout is stopped to free resources. Its
- // sessionId is preserved, so the next wake resumes it.
const idleEligible =
a.status === "running" &&
- !a.turnActive &&
+ lease.state === "none" &&
+ a.pendingAdmissions.length === 0 &&
+ lease.lastTerminal !== null &&
a.inbox.length === 0 &&
- a.caps.lifecycleKind === "persistent" &&
state.idleTimeoutMs > 0 &&
Number.isFinite(state.idleTimeoutMs);
if (idleEligible && a.idleSince !== null && nowMs - a.idleSince >= state.idleTimeoutMs) {
@@ -777,17 +594,15 @@ function onTick(state: ManagerState, nowMs: number): ReduceResult {
return { state: { ...state, agents }, effects };
}
-/* ------------------------------------------------------------------ */
-/* Helpers */
-/* ------------------------------------------------------------------ */
-
-function freshAgent(agentId: string, caps: AgentRuntimeCaps): AgentState {
+function freshAgent(agentId: string): AgentState {
return {
agentId,
status: "idle",
- caps,
inbox: [],
sessionId: null,
+ execution: { sessionInstanceId: null, lease: { state: "detached" } },
+ pendingAdmissions: [],
+ turnId: null,
turnActive: false,
lastProgressAt: 0,
lastDeliverAt: null,
@@ -795,61 +610,85 @@ function freshAgent(agentId: string, caps: AgentRuntimeCaps): AgentState {
stoppingSince: null,
resetting: false,
resettingSince: null,
- apm: createInitialApmGatedSteeringState(),
};
}
-/**
- * Move an agent into a STABLE lifecycle state (`running` or `idle`) — the
- * SINGLE owner of clearing the reset window. Every transition into a stable
- * state MUST go through here, never a bare `agent.status = "running"/"idle"`
- * assignment: that is what makes "the reset window ends exactly when the agent
- * reaches a stable state" a structural invariant instead of two hand-maintained
- * clear sites (`onSpawned` and `onExit`) that a deaf/hung process can both miss.
- *
- * Batch C (plans/daemon-fsm-desync.md): the old design cleared `resetting` in
- * `onSpawned` (idle-branch) and `onExit` (kill-branch) — both event-driven, so
- * an event that never arrives (SDK start wedged → no `spawned`; process won't
- * emit `exit`) left `resetting` stuck true forever, reset-locking every future
- * wake. Folding the clear into the stable-state transition means: whatever path
- * reaches `running`/`idle`, the window closes atomically with it. Batch D's
- * reconcile, on detecting a reset that never converged (`resettingSince` stale),
- * escalates through this same helper — recovery reuses the primitive.
- *
- * `starting`/`stopping` are TRANSIENT (still mid-reset) and deliberately do NOT
- * go through here — they don't clear the window.
- */
function enterStable(agent: AgentState, status: "running" | "idle"): void {
agent.status = status;
agent.resetting = false;
agent.resettingSince = null;
- // Left `stopping` (reached a stable state) ⇒ the stopping-stuck clock is moot.
agent.stoppingSince = null;
}
-/** Coalesce all queued messages into one prompt, deduplicating identical lines. */
-function drainInboxToPrompt(agent: AgentState): string {
- const seen = new Set<string>();
- const unique: string[] = [];
+function drainInbox(agent: AgentState): AgentMsg[] {
+ const seenIds = new Set<string>();
+ const unique: AgentMsg[] = [];
for (const m of agent.inbox) {
- if (!seen.has(m.text)) {
- seen.add(m.text);
- unique.push(m.text);
- }
+ if (m.id && seenIds.has(m.id)) continue;
+ if (m.id) seenIds.add(m.id);
+ unique.push(m);
}
agent.inbox = [];
- return unique.join("\n");
+ return unique;
}
function clone(a: AgentState): AgentState {
return {
...a,
inbox: [...a.inbox],
- caps: { ...a.caps },
- apm: { ...a.apm, recentEvents: [...a.apm.recentEvents] },
+ pendingAdmissions: a.pendingAdmissions.map((entry) => ({ ...entry, exactAgentMsg: { ...entry.exactAgentMsg } })),
+ execution: cloneExecution(a.execution),
};
}
+function cloneExecution(execution: ExecutionEpoch): ExecutionEpoch {
+ if (execution.sessionInstanceId === null) return { sessionInstanceId: null, lease: { state: "detached" } };
+ const lease = execution.lease;
+ return { sessionInstanceId: execution.sessionInstanceId, lease: { ...lease } };
+}
+
+function matchesSession(agent: AgentState, sessionInstanceId: string): agent is AgentState & {
+ execution: { sessionInstanceId: string; lease: Exclude<RootLease, { state: "detached" }> };
+} {
+ return agent.execution.sessionInstanceId === sessionInstanceId;
+}
+
+function identityOf(event: { sessionInstanceId: string; turnId: string }): TurnIdentity {
+ return { sessionInstanceId: event.sessionInstanceId, turnId: event.turnId };
+}
+
+function sameIdentity(left: TurnIdentity, right: TurnIdentity): boolean {
+ return left.sessionInstanceId === right.sessionInstanceId && left.turnId === right.turnId;
+}
+
+function leaseIsWorking(lease: RootLease): boolean {
+ return lease.state === "active" || lease.state === "suspect_active";
+}
+
+function syncExecutionProjection(agent: AgentState): void {
+ const lease = agent.execution.lease;
+ agent.turnActive = leaseIsWorking(lease) || agent.pendingAdmissions.length > 0;
+ agent.turnId = lease.state === "active" || lease.state === "suspect_active"
+ ? lease.identity.turnId
+ : lease.state === "none"
+ ? lease.lastTerminal?.identity.turnId ?? null
+ : null;
+ agent.lastDeliverAt = agent.pendingAdmissions.length > 0
+ ? Math.max(...agent.pendingAdmissions.map((entry) => entry.admittedAt))
+ : null;
+}
+
+function recoveryEffects(agent: AgentState, records: readonly PendingAdmission[]): ManagerEffect[] {
+ return records
+ .filter((record) => record.requeueOnFailure)
+ .map((record) => ({
+ type: "requeue_delivery" as const,
+ agentId: agent.agentId,
+ message: record.exactAgentMsg,
+ mode: record.mode,
+ }));
+}
+
function commit(state: ManagerState, agent: AgentState, effects: ManagerEffect[]): ReduceResult {
return { state: { ...state, agents: { ...state.agents, [agent.agentId]: agent } }, effects };
}
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index c6941b1bc..af3b2cb4c 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -9,11 +9,19 @@ import {
extractToolAudit,
isAlookShellInvocation,
truncateTargetToCodeUnits,
- type ManagedSession,
type SessionFactory,
} from "./managerRuntime.js";
-import { SdkRuntimeSession, type SdkSessionHandle } from "../runtime/sdkRuntimeSession.js";
-import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
+import type {
+ AgentEvent,
+ AgentSession,
+ AgentSessionResult,
+ BuiltinBackendSpecs,
+ DeliveryReceipt,
+} from "@alook/agent-driver";
+import type { AdapterEvent } from "@alook/agent-driver/adapter-author";
+import { createBuiltinAgentDriverRegistry } from "@alook/agent-driver/adapter-author";
+import type { AgentBackend as Driver } from "../drivers/index.js";
+import type { HostLaunchContext as LaunchContext } from "./hostContext.js";
import type { RuntimeConfig } from "../runtimeConfig.js";
import type { Logger } from "../logger.js";
@@ -75,41 +83,201 @@ function controllableChildDriver(id: string): { driver: Driver; stdout: PassThro
}
// Fake session with manual EE that we can emit into from tests.
-interface FakeSession extends ManagedSession {
- fire(evt: string, ...args: unknown[]): void;
+type TestAgentSession = AgentSession<BuiltinBackendSpecs, "codex">;
+interface FakeSession extends TestAgentSession {
+ fire(evt: string, ...args: unknown[]): Promise<void>;
+ pushAgentEvent(event: Omit<AgentEvent<BuiltinBackendSpecs, "codex">, "sequence" | "sessionInstanceId" | "at">): Promise<void>;
startResolver?: () => void;
startRejector?: (err: unknown) => void;
}
-function fakeSession(): FakeSession {
- const listeners = new Map<string, Array<(...args: unknown[]) => void>>();
- const s: FakeSession = {
- on(event, cb) {
- const arr = listeners.get(event) ?? [];
- arr.push(cb);
- listeners.set(event, arr);
+function fakeSession(sessionInstanceId = "test-instance"): FakeSession {
+ type Event = AgentEvent<BuiltinBackendSpecs, "codex">;
+ const queued: Event[] = [];
+ const waiters: Array<(value: IteratorResult<Event>) => void> = [];
+ let sequence = 0;
+ let resolveClosed!: (result: AgentSessionResult) => void;
+ const closed = new Promise<AgentSessionResult>((resolve) => { resolveClosed = resolve; });
+ const push = (payload: Omit<Event, "sequence" | "sessionInstanceId" | "at">) => {
+ const event = {
+ ...payload,
+ sequence: ++sequence,
+ sessionInstanceId,
+ at: Date.now(),
+ } as Event;
+ const waiter = waiters.shift();
+ if (waiter) waiter({ done: false, value: event });
+ else queued.push(event);
+ };
+ const s = {
+ backend: "codex",
+ capabilities: {} as TestAgentSession["capabilities"],
+ sessionInstanceId,
+ events: {
+ maxBufferedBytes: 4_194_304 as const,
+ [Symbol.asyncIterator]() {
+ return {
+ next: () => queued.length > 0
+ ? Promise.resolve({ done: false as const, value: queued.shift()! })
+ : new Promise<IteratorResult<Event>>((resolve) => waiters.push(resolve)),
+ };
+ },
},
- start() {
- return new Promise<void>((resolve, reject) => {
- s.startResolver = resolve;
+ closed,
+ start(message: { id: string }) {
+ return new Promise((resolve, reject) => {
+ s.startResolver = () => {
+ push({ type: "command_accepted", commandId: message.id, turnId: "test-turn", delivery: "prompt" } as never);
+ push({ type: "turn_started", turnId: "test-turn", commandIds: [message.id] } as never);
+ resolve({
+ status: "accepted",
+ delivery: "prompt",
+ commandId: message.id,
+ turnId: "test-turn",
+ });
+ };
s.startRejector = reject;
});
},
- send() { },
- stop() { },
- get currentSessionId() {
- return null;
+ async send(message: { id: string }) {
+ push({ type: "command_accepted", commandId: message.id, turnId: "test-turn", delivery: "steer" } as never);
+ push({ type: "turn_started", turnId: "test-turn", commandIds: [message.id] } as never);
+ return {
+ status: "accepted" as const,
+ delivery: "steer" as const,
+ commandId: message.id,
+ turnId: "test-turn",
+ };
},
- fire(evt, ...args) {
- for (const cb of listeners.get(evt) ?? []) cb(...args);
+ async interrupt() { return { status: "not_running" as const }; },
+ async stop() { return { status: "accepted" as const, requestId: "test-stop" }; },
+ snapshot() {
+ return {
+ sessionInstanceId,
+ state: "working" as const,
+ queuedCommands: [],
+ lastEventSequence: sequence,
+ };
},
- };
+ async invokeExtension() {
+ return { ok: false as const, error: { category: "internal" as const, code: "unsupported", message: "unsupported", retryable: false } };
+ },
+ async pushAgentEvent(event) {
+ push(event as never);
+ await Promise.resolve();
+ await Promise.resolve();
+ },
+ async fire(evt: string, ...args: unknown[]) {
+ if (evt === "runtime_event") {
+ const event = args[0] as { kind: string; sessionId?: string; text?: string; name?: string; input?: unknown; message?: string; source?: string; itemType?: string; payloadBytes?: number };
+ const turnId = "test-turn";
+ switch (event.kind) {
+ case "session_init":
+ push({ type: "session_started", backendSessionId: event.sessionId ?? "test-session" } as never);
+ break;
+ case "thinking": push({ type: "thinking_delta", turnId, text: event.text ?? "" } as never); break;
+ case "text": push({ type: "text_delta", turnId, text: event.text ?? "" } as never); break;
+ case "tool_call": push({ type: "tool_started", turnId, name: event.name ?? "unknown", input: (event.input ?? null) as never } as never); break;
+ case "tool_output": push({ type: "tool_finished", turnId, name: event.name ?? "unknown" } as never); break;
+ case "compaction_started":
+ case "compaction_finished":
+ case "review_started":
+ case "review_finished": push({ type: event.kind, turnId } as never); break;
+ case "internal_progress": push({ type: "internal_progress", turnId, source: event.source, itemType: event.itemType, payloadBytes: event.payloadBytes } as never); break;
+ case "error": push({ type: "session_failed", error: { category: "process", code: "runtime_error", message: event.message ?? "Runtime error", retryable: true } } as never); break;
+ case "turn_end": push({ type: "turn_completed", turnId, commandIds: ["test-start"], result: { outcome: "success", backendSessionId: event.sessionId ?? "test-session" } } as never); break;
+ default: push({ type: "internal_progress", turnId, source: "test", itemType: event.kind } as never);
+ }
+ } else if (evt === "error") {
+ const error = args[0] as { code?: string; message?: string } | undefined;
+ push({ type: "session_failed", error: { category: "process", code: error?.code ?? "spawn_error", message: error?.message ?? error?.code ?? "spawn error", retryable: true } } as never);
+ } else if (evt === "stderr") {
+ push({ type: "diagnostic", severity: "warning", source: "codex", message: String(args[0] ?? "") } as never);
+ } else if (evt === "exit") {
+ const info = args[0] as { code?: number | null; signal?: string | null; reason?: string } | undefined;
+ const result: AgentSessionResult = info?.reason === "requested"
+ ? { outcome: "stopped", requested: true, exitCode: info.code ?? null, signal: info.signal ?? null, cleanup: { status: "released" } }
+ : (info?.code ?? null) === 0 && (info?.signal ?? null) === null
+ ? { outcome: "crashed", requested: false, exitCode: 0, signal: null, cleanup: { status: "released" } }
+ : { outcome: "crashed", requested: false, exitCode: info?.code ?? null, signal: info?.signal ?? null, cleanup: { status: "released" } };
+ resolveClosed(result);
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ },
+ } as unknown as FakeSession;
return s;
}
+function sessionFactoryFor(session: FakeSession): SessionFactory {
+ return () => session;
+}
+
+function fireManagedError(
+ mgr: AgentProcessManager,
+ message: string,
+ superseded: boolean,
+): void {
+ const internal = mgr as unknown as {
+ activeSpawnState: Map<string, { superseded: boolean }>;
+ onAgentEvent(
+ agentId: string,
+ event: AgentEvent<BuiltinBackendSpecs, "codex">,
+ runtimeId: "codex",
+ owner: { superseded: boolean },
+ ): void;
+ };
+ if (!internal.activeSpawnState.has("a1")) mgr.deliver("a1", { seq: 1, text: "hello" });
+ const owner = internal.activeSpawnState.get("a1")!;
+ owner.superseded = superseded;
+ internal.onAgentEvent("a1", {
+ type: "session_failed",
+ error: { category: "process", code: "runtime_error", message, retryable: true },
+ sequence: 1,
+ sessionInstanceId: "test-instance",
+ at: Date.now(),
+ }, "codex", owner);
+}
+
+function fireManagedTurnFailure(
+ mgr: AgentProcessManager,
+ message: string,
+): void {
+ const internal = mgr as unknown as {
+ activeSpawnState: Map<string, { superseded: boolean }>;
+ onAgentEvent(
+ agentId: string,
+ event: AgentEvent<BuiltinBackendSpecs, "codex">,
+ runtimeId: "codex",
+ owner: { superseded: boolean },
+ ): void;
+ };
+ if (!internal.activeSpawnState.has("a1")) mgr.deliver("a1", { seq: 1, text: "hello" });
+ const owner = internal.activeSpawnState.get("a1")!;
+ internal.onAgentEvent("a1", {
+ type: "turn_completed",
+ turnId: "test-turn",
+ commandIds: ["test-start"],
+ result: {
+ outcome: "failed",
+ error: { category: "process", code: "runtime_error", message, retryable: true },
+ },
+ sequence: 1,
+ sessionInstanceId: "test-instance",
+ at: Date.now(),
+ }, "codex", owner);
+}
+
+function bindFactorySession(
+ _args: Parameters<SessionFactory>[0],
+ session: FakeSession,
+): FakeSession {
+ return session;
+}
+
function makeManager(opts: { logger?: Logger; tickIntervalMs?: number; idleTimeoutMs?: number; staleThresholdMs?: number; resetStuckThresholdMs?: number; handshakeTimeoutMs?: number; now?: () => number; onBotAuditEvent?: (agentId: string, event: unknown, context: { sessionId: string | null; launchId: string | null }) => void } = {}) {
const session = fakeSession();
- const factory: SessionFactory = () => session;
+ const factory = sessionFactoryFor(session);
const onRuntimeSpawnFailed = vi.fn();
const onRuntimeSessionEstablished = vi.fn();
const mgr = new AgentProcessManager({
@@ -132,13 +300,13 @@ function makeManager(opts: { logger?: Logger; tickIntervalMs?: number; idleTimeo
}
describe("AgentProcessManager — runtime health callbacks", () => {
- it("ENOENT `error` followed by `exit` reports the failure ONCE with the specific code", () => {
+ it("ENOENT `error` followed by `exit` reports the failure ONCE with the specific code", async () => {
const { mgr, session, onRuntimeSpawnFailed } = makeManager();
mgr.deliver("a1", { seq: 1, text: "hello" });
// child_process emits `error` first (with ENOENT), then `exit`.
- session.fire("error", { code: "ENOENT" });
- session.fire("exit");
+ await session.fire("error", { code: "ENOENT" });
+ await session.fire("exit");
expect(onRuntimeSpawnFailed).toHaveBeenCalledTimes(1);
expect(onRuntimeSpawnFailed).toHaveBeenCalledWith("codex", "ENOENT");
@@ -148,7 +316,7 @@ describe("AgentProcessManager — runtime health callbacks", () => {
const { mgr, session, onRuntimeSpawnFailed } = makeManager();
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("error", { code: "ENOENT" });
+ await session.fire("error", { code: "ENOENT" });
session.startRejector?.({ code: "spawn_threw" });
// Let the .catch microtask drain.
await new Promise((r) => setTimeout(r, 0));
@@ -157,44 +325,47 @@ describe("AgentProcessManager — runtime health callbacks", () => {
expect(onRuntimeSpawnFailed).toHaveBeenCalledWith("codex", "ENOENT");
});
- it("`exit` alone (no `error`) reports as pre_handshake_exit", () => {
+ it("`exit` alone (no `error`) reports as pre_handshake_exit", async () => {
const { mgr, session, onRuntimeSpawnFailed } = makeManager();
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("exit");
+ await session.fire("exit");
expect(onRuntimeSpawnFailed).toHaveBeenCalledTimes(1);
expect(onRuntimeSpawnFailed).toHaveBeenCalledWith("codex", "pre_handshake_exit");
});
- it("runtime_event marks the session established AND heals the runtime; subsequent error is session-level (no spawn-failed)", () => {
+ it("runtime_event marks the session established AND heals the runtime; subsequent error is session-level (no spawn-failed)", async () => {
const { mgr, session, onRuntimeSpawnFailed, onRuntimeSessionEstablished } = makeManager();
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "text", text: "hi" });
- session.fire("error", { code: "EPIPE" });
- session.fire("exit");
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "text", text: "hi" });
+ await session.fire("error", { code: "EPIPE" });
+ await session.fire("exit");
expect(onRuntimeSessionEstablished).toHaveBeenCalledWith("codex");
expect(onRuntimeSpawnFailed).not.toHaveBeenCalled();
});
- it("fires onRuntimeSessionEstablished on EVERY runtime_event so a parallel session can heal the map", () => {
+ it("heals runtime health only from the typed session_started event", async () => {
const { mgr, session, onRuntimeSessionEstablished } = makeManager();
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "text", text: "one" });
- session.fire("runtime_event", { kind: "text", text: "two" });
- session.fire("runtime_event", { kind: "text", text: "three" });
+ await session.fire("runtime_event", { kind: "text", text: "one" });
+ await session.fire("runtime_event", { kind: "text", text: "two" });
+ await session.fire("runtime_event", { kind: "text", text: "three" });
- // Called on every event — router idempotence collapses to one wire frame.
- expect(onRuntimeSessionEstablished).toHaveBeenCalledTimes(3);
+ expect(onRuntimeSessionEstablished).not.toHaveBeenCalled();
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ expect(onRuntimeSessionEstablished).toHaveBeenCalledTimes(1);
});
});
describe("AgentProcessManager — raw runtime line tap (P0-1)", () => {
- it("adds agent identity before the default child-process session parses the line", async () => {
+ it("keeps raw child-process parsing behind the injected logical-session boundary", async () => {
const { driver, stdout, parseLine } = controllableChildDriver("codex");
+ const session = fakeSession();
const onRuntimeRawLine = vi.fn();
const mgr = new AgentProcessManager({
driverFor: () => driver,
@@ -205,6 +376,7 @@ describe("AgentProcessManager — raw runtime line tap (P0-1)", () => {
config: {} as LaunchContext["config"],
credentialProxy: {} as LaunchContext["credentialProxy"],
}),
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
onRuntimeRawLine,
});
mgr.register("agent_a");
@@ -213,11 +385,11 @@ describe("AgentProcessManager — raw runtime line tap (P0-1)", () => {
stdout.write('{"vendor":"field"}\n');
- expect(onRuntimeRawLine).toHaveBeenCalledWith("agent_a", '{"vendor":"field"}');
- expect(parseLine).toHaveBeenCalledWith('{"vendor":"field"}');
+ expect(onRuntimeRawLine).not.toHaveBeenCalled();
+ expect(parseLine).not.toHaveBeenCalled();
});
- it("does not attach the child stdout tap to a custom session factory", () => {
+ it("does not attach the child stdout tap to a custom session factory", async () => {
const session = fakeSession();
const sessionFactory = vi.fn(() => session);
const onRuntimeRawLine = vi.fn();
@@ -242,7 +414,7 @@ describe("AgentProcessManager — raw runtime line tap (P0-1)", () => {
});
describe("AgentProcessManager — logging", () => {
- it("logs info on spawn start with agentId + runtime", () => {
+ it("logs info on spawn start with agentId + runtime", async () => {
const logger = stubLogger();
const { mgr } = makeManager({ logger });
mgr.deliver("a1", { seq: 1, text: "hello" });
@@ -254,12 +426,12 @@ describe("AgentProcessManager — logging", () => {
).toBe(true);
});
- it("logs info on session established (session_init) with agentId/sessionId/runtime", () => {
+ it("logs info on session established (session_init) with agentId/sessionId/runtime", async () => {
const logger = stubLogger();
const { mgr, session } = makeManager({ logger });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
expect(
logger.calls.info.some(
@@ -272,13 +444,13 @@ describe("AgentProcessManager — logging", () => {
).toBe(true);
});
- it("logs warn on a pre-handshake spawn failure (ENOENT)", () => {
+ it("logs warn on a pre-handshake spawn failure (ENOENT)", async () => {
const logger = stubLogger();
const { mgr, session } = makeManager({ logger });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("error", { code: "ENOENT" });
- session.fire("exit");
+ await session.fire("error", { code: "ENOENT" });
+ await session.fire("exit");
expect(
logger.calls.warn.some(
@@ -287,13 +459,13 @@ describe("AgentProcessManager — logging", () => {
).toBe(true);
});
- it("logs info on session ended with reason=turn_end", () => {
+ it("logs info on session ended with reason=turn_end", async () => {
const logger = stubLogger();
const { mgr, session } = makeManager({ logger });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
expect(
logger.calls.info.some(
@@ -303,13 +475,13 @@ describe("AgentProcessManager — logging", () => {
).toBe(true);
});
- it("logs info on session ended with reason=exit for an ESTABLISHED session's process exit", () => {
+ it("logs info on session ended with reason=exit for an ESTABLISHED session's process exit", async () => {
const logger = stubLogger();
const { mgr, session } = makeManager({ logger });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("exit");
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("exit");
expect(
logger.calls.info.some(
@@ -318,27 +490,23 @@ describe("AgentProcessManager — logging", () => {
).toBe(true);
});
- it("does NOT log session-ended for a pre-handshake exit (already a spawn-failed warning)", () => {
+ it("does NOT log session-ended for a pre-handshake exit (already a spawn-failed warning)", async () => {
const logger = stubLogger();
const { mgr, session } = makeManager({ logger });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("exit");
+ await session.fire("exit");
expect(logger.calls.info.some(([m]) => m === "agent session ended")).toBe(false);
});
- it("does NOT double-log session-ended when a per_turn runtime's natural post-turn_end exit fires (turn_end already logged)", () => {
+ it("logs one logical turn end without observing a backend's hidden physical exit", async () => {
const logger = stubLogger();
const { mgr, session } = makeManager({ logger }); // fakeDriver's lifecycle.kind is "per_turn"
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
- // The per_turn process exits on its own right after turn_end — this
- // must NOT produce a second, contradictory "session ended" line.
- session.fire("exit");
-
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
const ended = logger.calls.info.filter(([m]) => m === "agent session ended");
expect(ended).toHaveLength(1);
expect((ended[0]![1][0] as any).reason).toBe("turn_end");
@@ -352,11 +520,12 @@ describe("AgentProcessManager — launchId threading", () => {
// it there) instead of the launchId tracked from the latest agent:wake —
// every real spawn's voucher silently collided on cliTransport's "default"
// fallback path (see plans/fix-credential-proxy-connection-leak.md).
- it("passes the latest agent:wake's launchId into the spawned driver's LaunchContext", () => {
+ it("passes the latest agent:wake's launchId into the spawned driver's LaunchContext", async () => {
let capturedCtx: LaunchContext | undefined;
- const factory: SessionFactory = ({ ctx }) => {
+ const factory: SessionFactory = (hooks) => {
+ const { ctx } = hooks;
capturedCtx = ctx;
- return fakeSession();
+ return bindFactorySession(hooks, fakeSession());
};
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
@@ -377,11 +546,12 @@ describe("AgentProcessManager — launchId threading", () => {
expect(capturedCtx?.launchId).toBe("wake-launch-42");
});
- it("falls back to baseContextFor's launchId when no wake launchId is tracked", () => {
+ it("falls back to baseContextFor's launchId when no wake launchId is tracked", async () => {
let capturedCtx: LaunchContext | undefined;
- const factory: SessionFactory = ({ ctx }) => {
+ const factory: SessionFactory = (hooks) => {
+ const { ctx } = hooks;
capturedCtx = ctx;
- return fakeSession();
+ return bindFactorySession(hooks, fakeSession());
};
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
@@ -417,10 +587,10 @@ describe("AgentProcessManager — session race conditions", () => {
it("a stop that races and wins against an in-flight start() does not let start()'s later resolution revive the FSM into 'running'", async () => {
const logger = stubLogger();
const sessions: FakeSession[] = [];
- const factory: SessionFactory = () => {
+ const factory: SessionFactory = (hooks) => {
const s = fakeSession();
sessions.push(s);
- return s;
+ return bindFactorySession(hooks, s);
};
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
@@ -441,7 +611,7 @@ describe("AgentProcessManager — session race conditions", () => {
// The race: exit fires (as it would from a stop()/terminate_stalled
// effect) WHILE start() is still pending.
- session1.fire("exit");
+ await session1.fire("exit");
// Only now does the slow start() finally resolve.
session1.startResolver?.();
await Promise.resolve();
@@ -455,6 +625,78 @@ describe("AgentProcessManager — session race conditions", () => {
expect(spawnLogs).toHaveLength(2);
});
+ it.each(["reset", "model_switch"] as const)(
+ "%s keeps an exit-driven replacement session when the old stop resolves late",
+ async (restartKind) => {
+ let now = 0;
+ const oldSession = fakeSession("restart-race-old");
+ const replacementSession = fakeSession("restart-race-new");
+ const created: FakeSession[] = [];
+ const factory: SessionFactory = () => {
+ const session = created.length === 0 ? oldSession : replacementSession;
+ created.push(session);
+ return session;
+ };
+ let releaseOldStop!: () => void;
+ vi.spyOn(oldSession, "stop").mockImplementation(() => new Promise((resolve) => {
+ releaseOldStop = () => resolve({ status: "accepted", requestId: "restart-race-stop" });
+ }));
+ const mgr = new AgentProcessManager({
+ driverFor: () => fakeDriver("codex"),
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: factory,
+ now: () => now,
+ resetStuckThresholdMs: 100,
+ });
+ const runtimeConfig: RuntimeConfig = {
+ version: 1,
+ runtime: "codex",
+ model: { kind: "default" },
+ mode: { kind: "default" },
+ };
+ const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+ mgr.register("a1", { runtimeConfig, launchId: "wake-launch" });
+ mgr.deliver("a1", { seq: 1, text: "before restart" });
+ oldSession.startResolver?.();
+ await flush();
+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "running", resetting: false });
+
+ const restart = restartKind === "reset"
+ ? mgr.resetSession("a1", { runtimeConfig, launchId: "restart-launch", rewakePrompt: "rewake" })
+ : mgr.switchModel("a1", { runtimeConfig, launchId: "restart-launch", rewakePrompt: "rewake" });
+
+ await oldSession.fire("exit", { reason: "requested", code: 0, signal: null });
+ await flush();
+ expect(created).toEqual([oldSession, replacementSession]);
+
+ releaseOldStop();
+ await restart;
+ replacementSession.startResolver?.();
+ await flush();
+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "running", resetting: false });
+
+ const send = vi.spyOn(replacementSession, "send");
+ mgr.deliver("a1", { seq: 2, text: "after restart" });
+ expect(send).toHaveBeenCalledTimes(1);
+ await replacementSession.fire("runtime_event", { kind: "turn_end" });
+
+ now = 1_000;
+ const effects = (mgr as unknown as {
+ dispatch(event: { type: "tick"; nowMs: number }): Array<{ type: string }>;
+ }).dispatch({ type: "tick", nowMs: now });
+ expect(effects.map((effect) => effect.type)).not.toContain("terminate_stalled");
+ expect(effects.map((effect) => effect.type)).not.toContain("force_exit");
+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "running", resetting: false });
+ },
+ );
+
it("does NOT double-log session-ended when the process exit follows an explicit stop/terminate_stalled", async () => {
vi.useFakeTimers();
try {
@@ -465,13 +707,13 @@ describe("AgentProcessManager — session race conditions", () => {
mgr.deliver("a1", { seq: 1, text: "hello" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
currentTime = 200;
await vi.advanceTimersByTimeAsync(10);
// The stall watchdog issued session.stop() — simulate the underlying
// process actually exiting shortly after.
- session.fire("exit");
+ await session.fire("exit");
const ended = logger.calls.info.filter(([m]) => m === "agent session ended");
expect(ended).toHaveLength(1);
@@ -491,7 +733,7 @@ describe("AgentProcessManager — session race conditions", () => {
mgr.deliver("a1", { seq: 1, text: "hello" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
currentTime = 200;
await vi.advanceTimersByTimeAsync(10);
@@ -509,7 +751,7 @@ describe("AgentProcessManager — session race conditions", () => {
}
});
- it("internal_progress heartbeats do NOT refresh the stall watchdog — a compacting agent that only emits stream_event pings still gets terminated at the threshold", async () => {
+ it("turn-correlated internal progress renews the execution lease after a false terminal", async () => {
vi.useFakeTimers();
try {
let currentTime = 0;
@@ -519,31 +761,21 @@ describe("AgentProcessManager — session race conditions", () => {
mgr.deliver("a1", { seq: 1, text: "hello" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ currentTime = 10;
+ await session.fire("runtime_event", { kind: "turn_end" });
+ expect(mgr.snapshot().agents.a1).toMatchObject({ turnActive: false, idleSince: 10 });
- // Simulate Claude going into compaction and emitting only heartbeats.
- // Without the fix these keep bumping lastProgressAt and the stall never
- // fires; with the fix they're ignored for stall purposes.
currentTime = 50;
- session.fire("runtime_event", { kind: "compaction_started" });
- currentTime = 80;
- session.fire("runtime_event", { kind: "internal_progress", source: "claude_system", itemType: "stream_event" });
+ await session.fire("runtime_event", { kind: "internal_progress", source: "claude_system", itemType: "stream_event" });
currentTime = 150;
- session.fire("runtime_event", { kind: "internal_progress", source: "claude_system", itemType: "stream_event" });
+ await session.fire("runtime_event", { kind: "internal_progress", source: "claude_system", itemType: "stream_event" });
- // 200ms since spawn (t=0), 120ms since compaction_started's real
- // progress event. Threshold is 100ms → watchdog must fire.
currentTime = 200;
await vi.advanceTimersByTimeAsync(10);
- expect(
- logger.calls.info.some(
- ([m, d]) =>
- m === "agent session ended" &&
- (d[0] as any).reason === "terminate_stalled" &&
- (d[0] as any).sessionId === "s1",
- ),
- ).toBe(true);
+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "running", turnActive: true, idleSince: null });
+ expect(logger.calls.info.some(([m, d]) => m === "agent session ended" && (d[0] as any).reason === "terminate_stalled")).toBe(false);
} finally {
vi.useRealTimers();
}
@@ -559,7 +791,7 @@ describe("AgentProcessManager — session race conditions", () => {
lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,
} as Driver;
const session = fakeSession();
- const factory: SessionFactory = () => session;
+ const factory: SessionFactory = (hooks) => bindFactorySession(hooks, session);
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
baseContextFor: () => ({
@@ -579,8 +811,8 @@ describe("AgentProcessManager — session race conditions", () => {
mgr.deliver("a1", { seq: 1, text: "hello" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
mgr.start();
currentTime = 100;
@@ -613,7 +845,7 @@ describe("AgentProcessManager — session race conditions", () => {
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => currentTime,
tickIntervalMs: 5,
idleTimeoutMs: 50,
@@ -623,8 +855,8 @@ describe("AgentProcessManager — session race conditions", () => {
mgr.deliver("a1", { seq: 1, text: "hello" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
mgr.start();
// Idle-timeout tick → status=stopping, issues a stop. Crucially we DO NOT
@@ -646,7 +878,7 @@ describe("AgentProcessManager — session race conditions", () => {
}
});
- it("force_exit reaps the orphan via the recorded pid when the session handle is gone (batch F, Hypothesis A)", async () => {
+ it("force_exit delegates bounded teardown to the logical session without reading a pid", async () => {
vi.useFakeTimers();
try {
let currentTime = 0;
@@ -655,13 +887,12 @@ describe("AgentProcessManager — session race conditions", () => {
lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,
} as Driver;
const session = fakeSession();
- // A dead/never-existed pid: killProcessTree self-guards (isAlive → false),
- // so this exercises the pid-kill BRANCH without signalling a real process.
- (session as unknown as { pid: number }).pid = 2147483646;
+ const stopSpy = vi.fn().mockRejectedValue(new Error("stop rejected"));
+ session.stop = stopSpy;
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => currentTime,
tickIntervalMs: 5,
idleTimeoutMs: 50,
@@ -671,21 +902,16 @@ describe("AgentProcessManager — session race conditions", () => {
mgr.deliver("a1", { seq: 1, text: "hello" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- // pid recorded at spawn.
- expect((mgr as unknown as { activeSpawnState: Map<string, { pid: number | null }> }).activeSpawnState.get("a1")?.pid).toBe(2147483646);
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
mgr.start();
currentTime = 100;
await vi.advanceTimersByTimeAsync(10); // → stopping
- // Simulate Hypothesis A: the session handle is gone from the map (the wedge
- // cause) while force_exit is about to fire. The recorded pid must be the
- // fallback kill target — no crash, and the FSM still escapes stopping.
- (mgr as unknown as { sessions: Map<string, unknown> }).sessions.delete("a1");
currentTime = 300;
- await vi.advanceTimersByTimeAsync(10); // → force_exit (no session, pid present)
+ await vi.advanceTimersByTimeAsync(10); // → force_exit through AgentSession.stop
+ expect(stopSpy).toHaveBeenCalled();
expect(mgr.snapshot().agents["a1"]?.status).not.toBe("stopping"); // escaped via synthetic exit
} finally {
vi.useRealTimers();
@@ -705,7 +931,7 @@ describe("AgentProcessManager — session race conditions", () => {
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
logger,
now: () => currentTime,
tickIntervalMs: 5,
@@ -716,8 +942,8 @@ describe("AgentProcessManager — session race conditions", () => {
mgr.deliver("a1", { seq: 1, text: "hello" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
mgr.start();
currentTime = 100;
await vi.advanceTimersByTimeAsync(10); // → stopping
@@ -726,7 +952,7 @@ describe("AgentProcessManager — session race conditions", () => {
await vi.advanceTimersByTimeAsync(10); // → force_exit: no session, no pid
// Warned about the unkillable orphan, and still escaped stopping (no crash).
- expect(logger.calls.warn.some(([m]) => typeof m === "string" && m.includes("no session handle AND no recorded pid"))).toBe(true);
+ expect(logger.calls.warn.some(([m]) => typeof m === "string" && m.includes("logical session handle is already absent"))).toBe(true);
expect(mgr.snapshot().agents["a1"]?.status).not.toBe("stopping");
} finally {
vi.useRealTimers();
@@ -746,7 +972,7 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
busyDeliveryMode: "direct",
} as Driver;
const session = fakeSession();
- const factory: SessionFactory = () => session;
+ const factory: SessionFactory = (hooks) => bindFactorySession(hooks, session);
const onAgentActivity = vi.fn();
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
@@ -767,8 +993,8 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
mgr.deliver("a1", { seq: 1, text: "hello" }); // idle -> starting
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // spawned -> running
- session.fire("runtime_event", { kind: "turn_end" }); // running,turnActive=false -> derived idle
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // spawned -> running
+ await session.fire("runtime_event", { kind: "turn_end" }); // running,turnActive=false -> derived idle
mgr.start();
currentTime = 100; // past idleTimeoutMs — FSM flips running->stopping via hibernation
@@ -797,7 +1023,7 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
busyDeliveryMode: "direct",
} as Driver;
const session = fakeSession();
- const factory: SessionFactory = () => session;
+ const factory: SessionFactory = (hooks) => bindFactorySession(hooks, session);
const onAgentActivity = vi.fn();
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
@@ -815,11 +1041,11 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
mgr.deliver("a1", { seq: 1, text: "hello" }); // idle -> starting
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // -> running
- session.fire("runtime_event", { kind: "turn_end" }); // -> idle (derived)
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // -> running
+ await session.fire("runtime_event", { kind: "turn_end" }); // -> idle (derived)
mgr.deliver("a1", { seq: 2, text: "second turn" }); // re-wake: running,turnActive=false -> running
- session.fire("runtime_event", { kind: "turn_end" }); // -> idle again
+ await session.fire("runtime_event", { kind: "turn_end" }); // -> idle again
expect(onAgentActivity.mock.calls.map((c) => c[0])).toEqual([
{ agentId: "a1", state: "starting" },
@@ -847,7 +1073,7 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
config: {} as LaunchContext["config"],
credentialProxy: {} as LaunchContext["credentialProxy"],
}),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
});
mgr.register("a1");
// register alone: known but not running ⇒ idle.
@@ -856,11 +1082,11 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
mgr.deliver("a1", { seq: 1, text: "hello" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // -> running, turnActive
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // -> running, turnActive
expect(mgr.agentActivity("a1")).toBe("running");
expect(mgr.liveAgentActivities()).toEqual([{ agentId: "a1", state: "running" }]);
- session.fire("runtime_event", { kind: "turn_end" }); // running, !turnActive, empty inbox -> idle
+ await session.fire("runtime_event", { kind: "turn_end" }); // running, !turnActive, empty inbox -> idle
expect(mgr.agentActivity("a1")).toBe("idle");
expect(mgr.liveAgentActivities()).toEqual([{ agentId: "a1", state: "idle" }]);
@@ -880,7 +1106,10 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
} as Driver;
const sessionA = fakeSession();
const sessionB = fakeSession();
- const factory: SessionFactory = ({ agentId }) => (agentId === "a1" ? sessionA : sessionB);
+ const factory: SessionFactory = (hooks) => bindFactorySession(
+ hooks,
+ hooks.agentId === "a1" ? sessionA : sessionB,
+ );
const onAgentActivity = vi.fn();
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
@@ -904,10 +1133,10 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
sessionA.startResolver?.();
sessionB.startResolver?.();
await Promise.resolve();
- sessionA.fire("runtime_event", { kind: "session_init", sessionId: "sa" });
- sessionA.fire("runtime_event", { kind: "turn_end" });
- sessionB.fire("runtime_event", { kind: "session_init", sessionId: "sb" });
- sessionB.fire("runtime_event", { kind: "turn_end" });
+ await sessionA.fire("runtime_event", { kind: "session_init", sessionId: "sa" });
+ await sessionA.fire("runtime_event", { kind: "turn_end" });
+ await sessionB.fire("runtime_event", { kind: "session_init", sessionId: "sb" });
+ await sessionB.fire("runtime_event", { kind: "turn_end" });
onAgentActivity.mockClear();
mgr.start();
@@ -929,7 +1158,7 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
}
});
- it("register alone (no wake) never fires onAgentActivity", () => {
+ it("register alone (no wake) never fires onAgentActivity", async () => {
const onAgentActivity = vi.fn();
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
@@ -940,7 +1169,7 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
config: {} as LaunchContext["config"],
credentialProxy: {} as LaunchContext["credentialProxy"],
}),
- sessionFactory: () => fakeSession(),
+ sessionFactory: (hooks) => bindFactorySession(hooks, fakeSession()),
onAgentActivity,
});
mgr.register("a1");
@@ -948,105 +1177,15 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
});
});
-// A driver in the shape of PiDriver — declares `createSession` instead of a
-// usable `spawn`, mirroring the real "in-process SDK" contract.
-function fakeSdkDriver(id: string): { driver: Driver & { createSession: NonNullable<Driver["createSession"]> }; createSession: ReturnType<typeof vi.fn> } {
- let session: SdkRuntimeSession;
- const handle: SdkSessionHandle = {
- prompt: (text: string) => {
- session.emitEvents([{ kind: "text", text }]);
- },
- steer: () => { },
- };
- const createSession = vi.fn(async () => {
- session = new SdkRuntimeSession(handle, "sdk-sess-1");
- return session;
- });
- const driver = {
- ...fakeDriver(id),
- spawn: async () => {
- throw new Error("in-process SDK driver — spawn unsupported");
- },
- createSession,
- } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
- return { driver, createSession };
-}
-
-describe("AgentProcessManager — in-process SDK driver dispatch (Driver.createSession)", () => {
- it("throws a clear error when a driver declares createSession but no sessionFactory/sdkDriverDepsFor was configured", () => {
- const { driver } = fakeSdkDriver("pi");
- const mgr = new AgentProcessManager({
- driverFor: () => driver,
- baseContextFor: () => ({
- workingDirectory: "/tmp",
- agentId: "a1",
- standingPrompt: "",
- config: {} as LaunchContext["config"],
- credentialProxy: {} as LaunchContext["credentialProxy"],
- }),
- });
- mgr.register("a1");
- expect(() => mgr.deliver("a1", { seq: 1, text: "hello" })).toThrow(/sdkDriverDepsFor/);
- });
-
- it("dispatches through SdkManagedSession (not a child process) when sdkDriverDepsFor is configured, and streams runtime_events normally", async () => {
- const { driver, createSession } = fakeSdkDriver("pi");
- const onRuntimeSessionEstablished = vi.fn();
- const onRuntimeRawLine = vi.fn();
- const sdkDeps: SdkDriverDeps = {
- buildSpawnEnv: vi.fn().mockResolvedValue({}),
- createAgentSession: vi.fn(),
- };
- const mgr = new AgentProcessManager({
- driverFor: () => driver,
- baseContextFor: () => ({
- workingDirectory: "/tmp",
- agentId: "a1",
- standingPrompt: "",
- config: {} as LaunchContext["config"],
- }),
- sdkDriverDepsFor: () => sdkDeps,
- onRuntimeSessionEstablished,
- onRuntimeRawLine,
- });
- mgr.register("a1");
- mgr.deliver("a1", { seq: 1, text: "hello" });
- // createSession is async — let its microtasks (and the subsequent send()) drain.
- await new Promise((r) => setTimeout(r, 0));
-
- expect(createSession).toHaveBeenCalledTimes(1);
- expect(onRuntimeSessionEstablished).toHaveBeenCalledWith("pi");
- expect(onRuntimeRawLine).not.toHaveBeenCalled();
- });
-
- it("does NOT require a credentialProxy for an in-process SDK driver (that guard is child-process-only)", () => {
- const { driver } = fakeSdkDriver("pi");
- const sdkDeps: SdkDriverDeps = { buildSpawnEnv: vi.fn().mockResolvedValue({}), createAgentSession: vi.fn() };
- const mgr = new AgentProcessManager({
- driverFor: () => driver,
- baseContextFor: () => ({
- workingDirectory: "/tmp",
- agentId: "a1",
- standingPrompt: "",
- config: {} as LaunchContext["config"],
- // no credentialProxy on purpose
- }),
- sdkDriverDepsFor: () => sdkDeps,
- });
- mgr.register("a1");
- expect(() => mgr.deliver("a1", { seq: 1, text: "hello" })).not.toThrow();
- });
-});
-
describe("truncateThinking", () => {
- it("returns text unchanged when under the byte budget", () => {
+ it("returns text unchanged when under the byte budget", async () => {
const { text, truncated, chars } = truncateThinking("short");
expect(text).toBe("short");
expect(truncated).toBe(false);
expect(chars).toBe(5);
});
- it("truncates > 4KB text and reports the original char count", () => {
+ it("truncates > 4KB text and reports the original char count", async () => {
const long = "a".repeat(5000);
const { text, truncated, chars } = truncateThinking(long);
expect(truncated).toBe(true);
@@ -1054,7 +1193,7 @@ describe("truncateThinking", () => {
expect(Buffer.byteLength(text, "utf8")).toBeLessThanOrEqual(4096);
});
- it("never splits a multi-byte UTF-8 sequence", () => {
+ it("never splits a multi-byte UTF-8 sequence", async () => {
// Build a string whose 4096-byte boundary lands inside a 4-byte emoji.
// Each 😀 is 4 bytes. 1023 emojis = 4092 bytes; add "a" to get to 4093;
// then more emojis to push past 4096 mid-glyph.
@@ -1069,14 +1208,14 @@ describe("truncateThinking", () => {
});
describe("AgentProcessManager — bot audit event emission", () => {
- it("emits `thinking` with truncated+chars fields (flushed at the next event)", () => {
+ it("emits `thinking` with truncated+chars fields (flushed at the next event)", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "thinking", text: "think about it" });
+ await session.fire("runtime_event", { kind: "thinking", text: "think about it" });
expect(onBotAuditEvent).not.toHaveBeenCalled();
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "turn_end" });
expect(onBotAuditEvent).toHaveBeenCalledWith(
"a1",
@@ -1092,16 +1231,16 @@ describe("AgentProcessManager — bot audit event emission", () => {
);
});
- it("coalesces delta-streamed thinking into ONE row and drops empty deltas", () => {
+ it("coalesces delta-streamed thinking into ONE row and drops empty deltas", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "thinking", text: "" });
- session.fire("runtime_event", { kind: "thinking", text: "let me " });
- session.fire("runtime_event", { kind: "thinking", text: "count" });
- session.fire("runtime_event", { kind: "thinking", text: "" });
- session.fire("runtime_event", { kind: "tool_call", name: "Read", input: { file_path: "/x" } });
+ await session.fire("runtime_event", { kind: "thinking", text: "" });
+ await session.fire("runtime_event", { kind: "thinking", text: "let me " });
+ await session.fire("runtime_event", { kind: "thinking", text: "count" });
+ await session.fire("runtime_event", { kind: "thinking", text: "" });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Read", input: { file_path: "/x" } });
const thinkingCalls = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "thinking"
@@ -1115,12 +1254,12 @@ describe("AgentProcessManager — bot audit event emission", () => {
);
});
- it("emits `tool_call` with canonical name + resolved target", () => {
+ it("emits `tool_call` with canonical name + resolved target", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "tool_call", name: "Read", input: { file_path: "/etc/passwd" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Read", input: { file_path: "/etc/passwd" } });
expect(onBotAuditEvent).toHaveBeenCalledWith(
"a1",
@@ -1129,13 +1268,13 @@ describe("AgentProcessManager — bot audit event emission", () => {
);
});
- it("carries sessionId (populated after session_init) into the context arg", () => {
+ it("carries sessionId (populated after session_init) into the context arg", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s_abc" });
- session.fire("runtime_event", { kind: "tool_call", name: "Read", input: { file_path: "/x" } });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s_abc" });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Read", input: { file_path: "/x" } });
expect(onBotAuditEvent).toHaveBeenCalledWith(
"a1",
@@ -1144,27 +1283,27 @@ describe("AgentProcessManager — bot audit event emission", () => {
);
});
- it("DROPS bash-family tool_call whose command is `alook <sub>` for BOTH capitalized and lowercase names", () => {
+ it("DROPS bash-family tool_call whose command is `alook <sub>` for BOTH capitalized and lowercase names", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", {
+ await session.fire("runtime_event", {
kind: "tool_call",
name: "Bash",
input: { command: "alook inbox pull --max 5" },
});
- session.fire("runtime_event", {
+ await session.fire("runtime_event", {
kind: "tool_call",
name: "bash",
input: { command: " alook message send @gus hi" },
});
- session.fire("runtime_event", {
+ await session.fire("runtime_event", {
kind: "tool_call",
name: "Bash",
input: { command: "alook" },
});
- session.fire("runtime_event", {
+ await session.fire("runtime_event", {
kind: "tool_call",
name: "shell",
input: { command: "alook inbox pull" },
@@ -1176,14 +1315,14 @@ describe("AgentProcessManager — bot audit event emission", () => {
expect(bashCalls).toHaveLength(0);
});
- it("EMITS bash tool_call for non-alook shell work with canonical `bash` name + target", () => {
+ it("EMITS bash tool_call for non-alook shell work with canonical `bash` name + target", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "rm -rf /tmp/xxx" } });
- session.fire("runtime_event", { kind: "tool_call", name: "bash", input: { command: "sed -i '' '/pattern/d' todo.md" } });
- session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "echo -n > todo.md" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "rm -rf /tmp/xxx" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "bash", input: { command: "sed -i '' '/pattern/d' todo.md" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "echo -n > todo.md" } });
const bashCalls = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "tool_call"
@@ -1197,13 +1336,13 @@ describe("AgentProcessManager — bot audit event emission", () => {
expect((bashCalls[2]![1] as { payload: { target?: string } }).payload.target).toBe("echo -n > todo.md");
});
- it("truncates a long Bash target to <= 200 chars with an ellipsis", () => {
+ it("truncates a long Bash target to <= 200 chars with an ellipsis", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
const long = "echo " + "x".repeat(400);
- session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: long } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: long } });
const [call] = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "tool_call",
@@ -1213,12 +1352,12 @@ describe("AgentProcessManager — bot audit event emission", () => {
expect(target.endsWith("…")).toBe(true);
});
- it("emits bash tool_call without `target` when input has no command string", () => {
+ it("emits bash tool_call without `target` when input has no command string", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: {} });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: {} });
const [call] = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "tool_call",
@@ -1226,16 +1365,16 @@ describe("AgentProcessManager — bot audit event emission", () => {
expect((call![1] as { payload: unknown }).payload).toEqual({ name: "bash" });
});
- it("canonicalizes tool names on tool_calls (Edit → edit, MultiEdit → edit, Grep → grep, Glob → glob) with resolved target", () => {
+ it("canonicalizes tool names on tool_calls (Edit → edit, MultiEdit → edit, Grep → grep, Glob → glob) with resolved target", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "tool_call", name: "Edit", input: { file_path: "/x" } });
- session.fire("runtime_event", { kind: "tool_call", name: "Write", input: { file_path: "/y" } });
- session.fire("runtime_event", { kind: "tool_call", name: "MultiEdit", input: { file_path: "/z" } });
- session.fire("runtime_event", { kind: "tool_call", name: "Grep", input: { pattern: "TODO" } });
- session.fire("runtime_event", { kind: "tool_call", name: "Glob", input: { pattern: "**/*.ts" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Edit", input: { file_path: "/x" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Write", input: { file_path: "/y" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "MultiEdit", input: { file_path: "/z" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Grep", input: { pattern: "TODO" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Glob", input: { pattern: "**/*.ts" } });
const payloads = onBotAuditEvent.mock.calls
.filter(([, ev]) => (ev as { kind?: string })?.kind === "tool_call")
@@ -1249,25 +1388,25 @@ describe("AgentProcessManager — bot audit event emission", () => {
]);
});
- it("does NOT emit for non-audit event kinds (session_init, text, turn_end)", () => {
+ it("does NOT emit for non-audit event kinds (session_init, text, turn_end)", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "text", text: "hi human" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "text", text: "hi human" });
+ await session.fire("runtime_event", { kind: "turn_end" });
expect(onBotAuditEvent).not.toHaveBeenCalled();
});
- it("payload never contains extra fields beyond {name, target?} (T11)", () => {
+ it("payload never contains extra fields beyond {name, target?} (T11)", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "tool_call", name: "Edit", input: { file_path: "/x", oldText: "a", newText: "b", edits: [] } });
- session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "rm x", stdin: "secret" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Edit", input: { file_path: "/x", oldText: "a", newText: "b", edits: [] } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "rm x", stdin: "secret" } });
const payloads = onBotAuditEvent.mock.calls
.filter(([, ev]) => (ev as { kind?: string })?.kind === "tool_call")
@@ -1280,12 +1419,12 @@ describe("AgentProcessManager — bot audit event emission", () => {
});
describe("AgentProcessManager — error audit emission", () => {
- it("emits an `error` row on a pre-handshake exit (spawn scope)", () => {
+ it("emits an `error` row on a pre-handshake exit (spawn scope)", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("exit");
+ await session.fire("exit");
const errCalls = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "error",
@@ -1296,14 +1435,14 @@ describe("AgentProcessManager — error audit emission", () => {
);
});
- it("emits an `error` row for a runtime `{kind:'error'}` event (runtime scope) and does NOT count it as progress", () => {
+ it("emits an `error` row for a runtime `{kind:'error'}` event (runtime scope) and does NOT count it as progress", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
// Establish first so the error is session-level (runtime), not spawn.
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "error", message: "rate limited: 429 Too Many Requests" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "error", message: "rate limited: 429 Too Many Requests" });
const errCalls = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "error",
@@ -1315,7 +1454,20 @@ describe("AgentProcessManager — error audit emission", () => {
expect(payload.message).toContain("429");
});
- it("does NOT emit a `runtime_error` row for the death rattle of a session an intentional kill superseded", () => {
+ it("emits the failed turn result message as a runtime error", () => {
+ const onBotAuditEvent = vi.fn();
+ const { mgr } = makeManager({ onBotAuditEvent });
+ fireManagedTurnFailure(mgr, "turn failed after the provider stopped");
+
+ const errCalls = onBotAuditEvent.mock.calls.filter(
+ ([, ev]) => (ev as { kind?: string })?.kind === "error",
+ );
+ expect(errCalls).toHaveLength(1);
+ expect((errCalls[0]![1] as { payload: { message: string } }).payload.message)
+ .toContain("turn failed after the provider stopped");
+ });
+
+ it("does NOT emit a `runtime_error` row for the death rattle of a session an intentional kill superseded", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
@@ -1325,9 +1477,9 @@ describe("AgentProcessManager — error audit emission", () => {
// marks THIS live session's per-session state `superseded`, so the gate
// suppresses its rattle by session identity (not the agent-level reset
// flag) — the reborn session, a fresh state, would still surface its own.
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
mgr.markResetting("a1");
- session.fire("runtime_event", { kind: "error", message: "turn interrupted" });
+ await session.fire("runtime_event", { kind: "error", message: "turn interrupted" });
const errCalls = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "error",
@@ -1335,7 +1487,7 @@ describe("AgentProcessManager — error audit emission", () => {
expect(errCalls).toHaveLength(0);
});
- it("DOES emit a `runtime_error` for a REBORN (non-superseded) session's error even while the agent's reset window is still open — batch C reader-C fix", () => {
+ it("DOES emit a `runtime_error` for a REBORN (non-superseded) session's error even while the agent's reset window is still open — batch C reader-C fix", async () => {
// Batch C keeps `resetting` open across the respawn until the reborn
// process reaches `running`, so the reborn session is live while the reset
// window is still open. Gating the audit on the agent-level reset window
@@ -1345,7 +1497,7 @@ describe("AgentProcessManager — error audit emission", () => {
// (`superseded=false`), so its real error must SURFACE.
//
// The fake harness reuses one session object; we assert the gate's
- // behavior directly by driving `onRuntimeEvent` with the reborn session's
+ // behavior directly by driving the typed event consumer with the reborn session's
// (non-superseded) identity — mirroring what the real per-session
// subscriber closure passes.
const onBotAuditEvent = vi.fn();
@@ -1353,9 +1505,7 @@ describe("AgentProcessManager — error audit emission", () => {
// Reborn session identity → superseded=false (the subscriber passes its own
// session state's flag). A genuine startup error must be audited.
- (mgr as unknown as {
- onRuntimeEvent: (a: string, e: unknown, r: string, superseded: boolean) => void;
- }).onRuntimeEvent("a1", { kind: "error", message: "reborn hit a rate limit" }, "codex", false);
+ fireManagedError(mgr, "reborn hit a rate limit", false);
const errCalls = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "error",
@@ -1364,14 +1514,12 @@ describe("AgentProcessManager — error audit emission", () => {
expect((errCalls[0]![1] as { payload: { message: string } }).payload.message).toContain("rate limit");
});
- it("does NOT emit for a SUPERSEDED session's death rattle (the outgoing session an intentional kill interrupted) — batch C reader-C fix", () => {
+ it("does NOT emit for a SUPERSEDED session's death rattle (the outgoing session an intentional kill interrupted) — batch C reader-C fix", async () => {
const onBotAuditEvent = vi.fn();
const { mgr } = makeManager({ onBotAuditEvent });
// Superseded session identity → its interrupted-turn error is teardown
// noise, suppressed regardless of the agent's status.
- (mgr as unknown as {
- onRuntimeEvent: (a: string, e: unknown, r: string, superseded: boolean) => void;
- }).onRuntimeEvent("a1", { kind: "error", message: "turn interrupted" }, "codex", true);
+ fireManagedError(mgr, "turn interrupted", true);
const errCalls = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "error",
@@ -1379,7 +1527,7 @@ describe("AgentProcessManager — error audit emission", () => {
expect(errCalls).toHaveLength(0);
});
- it("adds a stuck-reset correlation trace for a reborn error while the reset window is wedged — WITHOUT suppressing the error (batch D)", () => {
+ it("adds a stuck-reset correlation trace for a reborn error while the reset window is wedged — WITHOUT suppressing the error (batch D)", async () => {
// Batch D: the stuck-reset trace is purely additive. A reborn (non-
// superseded) session's genuine error must STILL surface as an audit row
// (batch C's 命门, unchanged); on top of that, if the agent's reset window
@@ -1397,9 +1545,7 @@ describe("AgentProcessManager — error audit emission", () => {
clock = 200; // now - resettingSince = 190 >= 100 → stuck
// Reborn (superseded=false) error fires while the window is wedged.
- (mgr as unknown as {
- onRuntimeEvent: (a: string, e: unknown, r: string, superseded: boolean) => void;
- }).onRuntimeEvent("a1", { kind: "error", message: "reborn hit a rate limit" }, "codex", false);
+ fireManagedError(mgr, "reborn hit a rate limit", false);
// 命门: the error STILL surfaces (additive trace never suppresses).
const errCalls = onBotAuditEvent.mock.calls.filter(
@@ -1410,7 +1556,7 @@ describe("AgentProcessManager — error audit emission", () => {
expect(logger.calls.warn.some(([m]) => m === "runtime error during a stuck reset window")).toBe(true);
});
- it("does NOT add the stuck-reset trace for a reborn error when the reset window is NOT stuck (batch D)", () => {
+ it("does NOT add the stuck-reset trace for a reborn error when the reset window is NOT stuck (batch D)", async () => {
let clock = 0;
const onBotAuditEvent = vi.fn();
const logger = stubLogger();
@@ -1421,28 +1567,29 @@ describe("AgentProcessManager — error audit emission", () => {
mgr.markResetting("a1"); // resettingSince=10
clock = 50; // now - resettingSince = 40 < 100 → NOT stuck
- (mgr as unknown as {
- onRuntimeEvent: (a: string, e: unknown, r: string, superseded: boolean) => void;
- }).onRuntimeEvent("a1", { kind: "error", message: "reborn hit a rate limit" }, "codex", false);
+ fireManagedError(mgr, "reborn hit a rate limit", false);
// Error still surfaces (it's a real reborn error), but no stuck-reset trace.
expect(onBotAuditEvent.mock.calls.filter(([, ev]) => (ev as { kind?: string })?.kind === "error")).toHaveLength(1);
expect(logger.calls.warn.some(([m]) => m === "runtime error during a stuck reset window")).toBe(false);
});
- it("scrubs secrets out of an error message before it becomes an audit row", () => {
+ it("scrubs secrets out of an error message before it becomes an audit row", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "error", message: "auth failed with sk-ant-abc123DEF456 token" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", {
+ kind: "error",
+ message: 'auth failed sk-ant-abc123DEF456 OPENAI_API_KEY=provider-secret {"apiKey":"json-secret"} Authorization: Basic basic-secret at /Users/Alice Smith/private key.json?token=query-secret',
+ });
const errCall = onBotAuditEvent.mock.calls.find(
([, ev]) => (ev as { kind?: string })?.kind === "error",
);
const message = (errCall![1] as { payload: { message: string } }).payload.message;
- expect(message).not.toContain("sk-ant-abc123DEF456");
+ expect(message).not.toMatch(/sk-ant-abc123DEF456|provider-secret|json-secret|basic-secret|Alice Smith|private key|query-secret/);
expect(message).toContain("[redacted-token]");
});
});
@@ -1453,8 +1600,8 @@ describe("AgentProcessManager — handshake watchdog", () => {
it("terminates a session that never handshakes, emits an `error` row, and returns the FSM to idle", async () => {
const onBotAuditEvent = vi.fn();
- const stopSpy = vi.fn();
const session = fakeSession();
+ const stopSpy = vi.fn(() => session.fire("exit", { reason: "requested" }));
session.stop = stopSpy as never;
const onRuntimeSpawnFailed = vi.fn();
const mgr = new AgentProcessManager({
@@ -1466,7 +1613,7 @@ describe("AgentProcessManager — handshake watchdog", () => {
config: {} as LaunchContext["config"],
credentialProxy: {} as LaunchContext["credentialProxy"],
}),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
onRuntimeSpawnFailed,
onBotAuditEvent: onBotAuditEvent as never,
handshakeTimeoutMs: 1000,
@@ -1482,7 +1629,7 @@ describe("AgentProcessManager — handshake watchdog", () => {
expect(mgr.snapshot().agents["a1"]?.status).toBe("running");
// No handshake ever arrives; the deadline elapses.
- vi.advanceTimersByTime(1000);
+ await vi.advanceTimersByTimeAsync(1000);
expect(onRuntimeSpawnFailed).toHaveBeenCalledWith("codex", "handshake_timeout");
expect(stopSpy).toHaveBeenCalledTimes(1);
@@ -1510,7 +1657,7 @@ describe("AgentProcessManager — handshake watchdog", () => {
config: {} as LaunchContext["config"],
credentialProxy: {} as LaunchContext["credentialProxy"],
}),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
onRuntimeSpawnFailed,
onBotAuditEvent: onBotAuditEvent as never,
handshakeTimeoutMs: 1000,
@@ -1522,7 +1669,7 @@ describe("AgentProcessManager — handshake watchdog", () => {
await Promise.resolve();
// Handshake lands well within the window.
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
vi.advanceTimersByTime(1000);
expect(onRuntimeSpawnFailed).not.toHaveBeenCalled();
@@ -1535,13 +1682,13 @@ describe("AgentProcessManager — handshake watchdog", () => {
});
describe("canonicalToolName", () => {
- it("canonicalizes bash/shell to bash (case-insensitive)", () => {
+ it("canonicalizes bash/shell to bash (case-insensitive)", async () => {
expect(canonicalToolName("Bash")).toBe("bash");
expect(canonicalToolName("bash")).toBe("bash");
expect(canonicalToolName("BASH")).toBe("bash");
expect(canonicalToolName("shell")).toBe("bash");
});
- it("canonicalizes file-target tools", () => {
+ it("canonicalizes file-target tools", async () => {
expect(canonicalToolName("Read")).toBe("read");
expect(canonicalToolName("read")).toBe("read");
expect(canonicalToolName("Edit")).toBe("edit");
@@ -1551,18 +1698,18 @@ describe("canonicalToolName", () => {
expect(canonicalToolName("LS")).toBe("ls");
expect(canonicalToolName("NotebookEdit")).toBe("notebook_edit");
});
- it("canonicalizes pattern tools", () => {
+ it("canonicalizes pattern tools", async () => {
expect(canonicalToolName("Grep")).toBe("grep");
expect(canonicalToolName("Glob")).toBe("glob");
expect(canonicalToolName("Find")).toBe("find");
});
- it("canonicalizes web + todo tools", () => {
+ it("canonicalizes web + todo tools", async () => {
expect(canonicalToolName("WebSearch")).toBe("web_search");
expect(canonicalToolName("web_search")).toBe("web_search");
expect(canonicalToolName("WebFetch")).toBe("web_fetch");
expect(canonicalToolName("TodoWrite")).toBe("todo_write");
});
- it("falls through to lowercase for unknown names", () => {
+ it("falls through to lowercase for unknown names", async () => {
expect(canonicalToolName("mcp_search")).toBe("mcp_search");
expect(canonicalToolName("Frobnicate")).toBe("frobnicate");
expect(canonicalToolName("collab_tool_call")).toBe("collab_tool_call");
@@ -1570,44 +1717,44 @@ describe("canonicalToolName", () => {
});
describe("extractToolAudit — shell class", () => {
- it("Anthropic Bash + non-alook command yields {name: 'bash', target, suppressed: false}", () => {
+ it("Anthropic Bash + non-alook command yields {name: 'bash', target, suppressed: false}", async () => {
expect(extractToolAudit("Bash", { command: "rm -rf tmp" })).toEqual({
name: "bash",
target: "rm -rf tmp",
suppressed: false,
});
});
- it("pi lowercase bash + non-alook command yields the same shape", () => {
+ it("pi lowercase bash + non-alook command yields the same shape", async () => {
expect(extractToolAudit("bash", { command: "sed -i '' '/x/d' todo.md" })).toEqual({
name: "bash",
target: "sed -i '' '/x/d' todo.md",
suppressed: false,
});
});
- it("suppresses alook invocations for capitalized Bash", () => {
+ it("suppresses alook invocations for capitalized Bash", async () => {
expect(extractToolAudit("Bash", { command: "alook inbox pull" }).suppressed).toBe(true);
});
- it("suppresses alook invocations for lowercase bash (pi)", () => {
+ it("suppresses alook invocations for lowercase bash (pi)", async () => {
expect(extractToolAudit("bash", { command: "alook" }).suppressed).toBe(true);
});
- it("suppresses even with leading whitespace (raw command trimmed for the check)", () => {
+ it("suppresses even with leading whitespace (raw command trimmed for the check)", async () => {
expect(extractToolAudit("Bash", { command: " alook message send" }).suppressed).toBe(true);
});
- it("codex shell (string command) — driver already unwrapped params.item", () => {
+ it("codex shell (string command) — driver already unwrapped params.item", async () => {
expect(extractToolAudit("shell", { command: "pnpm test" })).toEqual({
name: "bash",
target: "pnpm test",
suppressed: false,
});
});
- it("codex shell (array command) — joined with spaces, noisy-but-honest form", () => {
+ it("codex shell (array command) — joined with spaces, noisy-but-honest form", async () => {
expect(extractToolAudit("shell", { command: ["bash", "-lc", "rm -rf tmp"] })).toEqual({
name: "bash",
target: "bash -lc rm -rf tmp",
suppressed: false,
});
});
- it("codex shell array wrapping `alook …` inside `bash -lc` does NOT suppress — outer shell is real work", () => {
+ it("codex shell array wrapping `alook …` inside `bash -lc` does NOT suppress — outer shell is real work", async () => {
const out = extractToolAudit("shell", { command: ["bash", "-lc", "alook inbox pull"] });
expect(out.suppressed).toBe(false);
expect(out.name).toBe("bash");
@@ -1616,60 +1763,60 @@ describe("extractToolAudit — shell class", () => {
});
describe("extractToolAudit — file-target class", () => {
- it("Anthropic Read → file_path", () => {
+ it("Anthropic Read → file_path", async () => {
expect(extractToolAudit("Read", { file_path: "/etc/passwd" })).toEqual({
name: "read",
target: "/etc/passwd",
suppressed: false,
});
});
- it("pi read → path", () => {
+ it("pi read → path", async () => {
expect(extractToolAudit("read", { path: "AGENTS.md" })).toEqual({
name: "read",
target: "AGENTS.md",
suppressed: false,
});
});
- it("Edit picks file_path, ignoring other keys", () => {
+ it("Edit picks file_path, ignoring other keys", async () => {
expect(extractToolAudit("Edit", { file_path: "src/foo.ts", oldText: "x", newText: "y" })).toEqual({
name: "edit",
target: "src/foo.ts",
suppressed: false,
});
});
- it("pi edit → path", () => {
+ it("pi edit → path", async () => {
expect(extractToolAudit("edit", { path: "plans/x.md", edits: [] })).toEqual({
name: "edit",
target: "plans/x.md",
suppressed: false,
});
});
- it("Write / pi write → file_path / path", () => {
+ it("Write / pi write → file_path / path", async () => {
expect(extractToolAudit("Write", { file_path: "x.md", content: "..." }).target).toBe("x.md");
expect(extractToolAudit("write", { path: "x.md", content: "..." }).target).toBe("x.md");
});
- it("MultiEdit → edit + file_path (semantic collapse)", () => {
+ it("MultiEdit → edit + file_path (semantic collapse)", async () => {
expect(extractToolAudit("MultiEdit", { file_path: "x.ts", edits: [] })).toEqual({
name: "edit",
target: "x.ts",
suppressed: false,
});
});
- it("NotebookEdit → notebook_path", () => {
+ it("NotebookEdit → notebook_path", async () => {
expect(extractToolAudit("NotebookEdit", { notebook_path: "nb.ipynb" })).toEqual({
name: "notebook_edit",
target: "nb.ipynb",
suppressed: false,
});
});
- it("LS → path", () => {
+ it("LS → path", async () => {
expect(extractToolAudit("LS", { path: "src/" })).toEqual({
name: "ls",
target: "src/",
suppressed: false,
});
});
- it("codex file_change → edit + adapter-flattened ordered paths", () => {
+ it("codex file_change → edit + adapter-flattened ordered paths", async () => {
expect(extractToolAudit("file_change", { path: "a.ts, b.ts" })).toEqual({
name: "edit",
target: "a.ts, b.ts",
@@ -1679,55 +1826,55 @@ describe("extractToolAudit — file-target class", () => {
});
describe("extractToolAudit — pattern class", () => {
- it("Grep with pattern + path picks pattern", () => {
+ it("Grep with pattern + path picks pattern", async () => {
expect(extractToolAudit("Grep", { pattern: "TODO", path: "src/" }).target).toBe("TODO");
});
- it("pi grep with pattern only", () => {
+ it("pi grep with pattern only", async () => {
expect(extractToolAudit("grep", { pattern: "TODO" }).target).toBe("TODO");
});
- it("Glob picks pattern", () => {
+ it("Glob picks pattern", async () => {
expect(extractToolAudit("Glob", { pattern: "**/*.tsx" }).target).toBe("**/*.tsx");
});
- it("find picks pattern", () => {
+ it("find picks pattern", async () => {
expect(extractToolAudit("find", { pattern: "*.ts", path: "src" }).target).toBe("*.ts");
});
- it("grep falls back to path when no pattern is set", () => {
+ it("grep falls back to path when no pattern is set", async () => {
expect(extractToolAudit("grep", { path: "src" }).target).toBe("src");
});
});
describe("extractToolAudit — fallthrough / MCP / web", () => {
- it("WebFetch → url", () => {
+ it("WebFetch → url", async () => {
expect(extractToolAudit("WebFetch", { url: "https://example.com" })).toEqual({
name: "web_fetch",
target: "https://example.com",
suppressed: false,
});
});
- it("mcp_search stays as mcp_search + query target", () => {
+ it("mcp_search stays as mcp_search + query target", async () => {
expect(extractToolAudit("mcp_search", { query: "foo" })).toEqual({
name: "mcp_search",
target: "foo",
suppressed: false,
});
});
- it("web_search → query", () => {
+ it("web_search → query", async () => {
expect(extractToolAudit("web_search", { query: "cats" })).toEqual({
name: "web_search",
target: "cats",
suppressed: false,
});
});
- it("collab_tool_call → name (from input.name)", () => {
+ it("collab_tool_call → name (from input.name)", async () => {
expect(extractToolAudit("collab_tool_call", { name: "x" }).target).toBe("x");
});
- it("TodoWrite → no target", () => {
+ it("TodoWrite → no target", async () => {
expect(extractToolAudit("TodoWrite", { todos: [] })).toEqual({
name: "todo_write",
suppressed: false,
});
});
- it("Unknown tool falls through as lowercased name + no target", () => {
+ it("Unknown tool falls through as lowercased name + no target", async () => {
expect(extractToolAudit("Frobnicate", {})).toEqual({
name: "frobnicate",
suppressed: false,
@@ -1736,39 +1883,39 @@ describe("extractToolAudit — fallthrough / MCP / web", () => {
});
describe("extractToolAudit — non-object input guard", () => {
- it("null / undefined / string / number / array — all return no target without throwing", () => {
+ it("null / undefined / string / number / array — all return no target without throwing", async () => {
expect(extractToolAudit("Bash", null)).toEqual({ name: "bash", suppressed: false });
expect(extractToolAudit("Bash", undefined)).toEqual({ name: "bash", suppressed: false });
expect(extractToolAudit("Bash", "raw string")).toEqual({ name: "bash", suppressed: false });
expect(extractToolAudit("Bash", 42)).toEqual({ name: "bash", suppressed: false });
expect(extractToolAudit("Bash", ["a", "b"])).toEqual({ name: "bash", suppressed: false });
});
- it("copilot stringified-JSON recovery: input is a JSON string that decodes to a record", () => {
+ it("stringified-JSON recovery: input is a JSON string that decodes to a record", async () => {
expect(extractToolAudit("Bash", '{"command":"rm -rf tmp"}')).toEqual({
name: "bash",
target: "rm -rf tmp",
suppressed: false,
});
});
- it("invalid JSON string — no throw, returns no target", () => {
+ it("invalid JSON string — no throw, returns no target", async () => {
expect(extractToolAudit("Bash", "not json{")).toEqual({ name: "bash", suppressed: false });
});
- it("JSON string that decodes to a non-object — no throw, returns no target", () => {
+ it("JSON string that decodes to a non-object — no throw, returns no target", async () => {
expect(extractToolAudit("Bash", "42")).toEqual({ name: "bash", suppressed: false });
expect(extractToolAudit("Bash", '["a","b"]')).toEqual({ name: "bash", suppressed: false });
});
});
describe("truncateTargetToCodeUnits", () => {
- it("passes short strings through unchanged", () => {
+ it("passes short strings through unchanged", async () => {
expect(truncateTargetToCodeUnits("hello")).toBe("hello");
});
- it("truncates a 300-unit ASCII string to <=200 units + ellipsis", () => {
+ it("truncates a 300-unit ASCII string to <=200 units + ellipsis", async () => {
const out = truncateTargetToCodeUnits("a".repeat(300));
expect(out.length).toBeLessThanOrEqual(200);
expect(out.endsWith("…")).toBe(true);
});
- it("emoji-heavy: never emits a lone surrogate + round-trips clean UTF-8", () => {
+ it("emoji-heavy: never emits a lone surrogate + round-trips clean UTF-8", async () => {
const emoji = "😀";
const s = emoji.repeat(200);
const out = truncateTargetToCodeUnits(s);
@@ -1779,25 +1926,25 @@ describe("truncateTargetToCodeUnits", () => {
});
describe("isAlookShellInvocation", () => {
- it("matches `alook <sub>` and bare `alook`", () => {
+ it("matches `alook <sub>` and bare `alook`", async () => {
expect(isAlookShellInvocation("alook")).toBe(true);
expect(isAlookShellInvocation("alook inbox pull")).toBe(true);
expect(isAlookShellInvocation(" alook message send")).toBe(true);
});
- it("matches the `$ALOOK_CLI` env-var form the system prompt now teaches", () => {
+ it("matches the `$ALOOK_CLI` env-var form the system prompt now teaches", async () => {
expect(isAlookShellInvocation("$ALOOK_CLI inbox pull")).toBe(true);
expect(isAlookShellInvocation("${ALOOK_CLI} message send")).toBe(true);
expect(isAlookShellInvocation("$ALOOK_CLI")).toBe(true);
expect(isAlookShellInvocation(" $ALOOK_CLI nap")).toBe(true);
});
- it("does NOT match commands that merely mention alook", () => {
+ it("does NOT match commands that merely mention alook", async () => {
expect(isAlookShellInvocation("rm alook.log")).toBe(false);
expect(isAlookShellInvocation("echo alook")).toBe(false);
expect(isAlookShellInvocation("alookalike")).toBe(false);
// A different env var that merely starts with the same prefix must not match.
expect(isAlookShellInvocation("$ALOOK_CLIENT foo")).toBe(false);
});
- it("returns false for missing input", () => {
+ it("returns false for missing input", async () => {
expect(isAlookShellInvocation(undefined)).toBe(false);
expect(isAlookShellInvocation("")).toBe(false);
});
@@ -1835,17 +1982,17 @@ describe("extractToolAudit — driver coverage matrix", () => {
{ driver: "codex", rawName: "mcp_search", rawInput: { query: "foo" }, expected: { name: "mcp_search", target: "foo", suppressed: false } },
{ driver: "codex", rawName: "collab_tool_call", rawInput: { name: "x" }, expected: { name: "collab_tool_call", target: "x", suppressed: false } },
- { driver: "gemini", rawName: "bash", rawInput: { command: "rm tmp" }, expected: { name: "bash", target: "rm tmp", suppressed: false } },
- { driver: "gemini", rawName: "read", rawInput: { path: "/x" }, expected: { name: "read", target: "/x", suppressed: false } },
- { driver: "gemini", rawName: "edit", rawInput: { file_path: "/x" }, expected: { name: "edit", target: "/x", suppressed: false } },
- { driver: "gemini", rawName: "write", rawInput: { path: "/x" }, expected: { name: "write", target: "/x", suppressed: false } },
- { driver: "gemini", rawName: "grep", rawInput: { pattern: "TODO" }, expected: { name: "grep", target: "TODO", suppressed: false } },
+ { driver: "generic-json", rawName: "bash", rawInput: { command: "rm tmp" }, expected: { name: "bash", target: "rm tmp", suppressed: false } },
+ { driver: "generic-json", rawName: "read", rawInput: { path: "/x" }, expected: { name: "read", target: "/x", suppressed: false } },
+ { driver: "generic-json", rawName: "edit", rawInput: { file_path: "/x" }, expected: { name: "edit", target: "/x", suppressed: false } },
+ { driver: "generic-json", rawName: "write", rawInput: { path: "/x" }, expected: { name: "write", target: "/x", suppressed: false } },
+ { driver: "generic-json", rawName: "grep", rawInput: { pattern: "TODO" }, expected: { name: "grep", target: "TODO", suppressed: false } },
- { driver: "kimi", rawName: "bash", rawInput: { command: "rm tmp" }, expected: { name: "bash", target: "rm tmp", suppressed: false } },
- { driver: "kimi", rawName: "read", rawInput: { path: "/x" }, expected: { name: "read", target: "/x", suppressed: false } },
- { driver: "kimi", rawName: "edit", rawInput: { file_path: "/x" }, expected: { name: "edit", target: "/x", suppressed: false } },
- { driver: "kimi", rawName: "write", rawInput: { path: "/x" }, expected: { name: "write", target: "/x", suppressed: false } },
- { driver: "kimi", rawName: "grep", rawInput: { pattern: "TODO" }, expected: { name: "grep", target: "TODO", suppressed: false } },
+ { driver: "generic-lowercase", rawName: "bash", rawInput: { command: "rm tmp" }, expected: { name: "bash", target: "rm tmp", suppressed: false } },
+ { driver: "generic-lowercase", rawName: "read", rawInput: { path: "/x" }, expected: { name: "read", target: "/x", suppressed: false } },
+ { driver: "generic-lowercase", rawName: "edit", rawInput: { file_path: "/x" }, expected: { name: "edit", target: "/x", suppressed: false } },
+ { driver: "generic-lowercase", rawName: "write", rawInput: { path: "/x" }, expected: { name: "write", target: "/x", suppressed: false } },
+ { driver: "generic-lowercase", rawName: "grep", rawInput: { pattern: "TODO" }, expected: { name: "grep", target: "TODO", suppressed: false } },
{ driver: "opencode", rawName: "bash", rawInput: { command: "rm tmp" }, expected: { name: "bash", target: "rm tmp", suppressed: false } },
{ driver: "opencode", rawName: "read", rawInput: { file_path: "/x" }, expected: { name: "read", target: "/x", suppressed: false } },
@@ -1853,12 +2000,12 @@ describe("extractToolAudit — driver coverage matrix", () => {
{ driver: "opencode", rawName: "write", rawInput: { file_path: "/x" }, expected: { name: "write", target: "/x", suppressed: false } },
{ driver: "opencode", rawName: "grep", rawInput: { pattern: "TODO" }, expected: { name: "grep", target: "TODO", suppressed: false } },
- { driver: "copilot", rawName: "bash", rawInput: '{"command":"rm tmp"}', expected: { name: "bash", target: "rm tmp", suppressed: false } },
- { driver: "copilot", rawName: "bash", rawInput: { command: "rm tmp" }, expected: { name: "bash", target: "rm tmp", suppressed: false } },
- { driver: "copilot", rawName: "read", rawInput: { file_path: "/x" }, expected: { name: "read", target: "/x", suppressed: false } },
- { driver: "copilot", rawName: "edit", rawInput: { file_path: "/x" }, expected: { name: "edit", target: "/x", suppressed: false } },
- { driver: "copilot", rawName: "write", rawInput: { file_path: "/x" }, expected: { name: "write", target: "/x", suppressed: false } },
- { driver: "copilot", rawName: "grep", rawInput: { pattern: "TODO" }, expected: { name: "grep", target: "TODO", suppressed: false } },
+ { driver: "generic-string-input", rawName: "bash", rawInput: '{"command":"rm tmp"}', expected: { name: "bash", target: "rm tmp", suppressed: false } },
+ { driver: "generic-file-path", rawName: "bash", rawInput: { command: "rm tmp" }, expected: { name: "bash", target: "rm tmp", suppressed: false } },
+ { driver: "generic-file-path", rawName: "read", rawInput: { file_path: "/x" }, expected: { name: "read", target: "/x", suppressed: false } },
+ { driver: "generic-file-path", rawName: "edit", rawInput: { file_path: "/x" }, expected: { name: "edit", target: "/x", suppressed: false } },
+ { driver: "generic-file-path", rawName: "write", rawInput: { file_path: "/x" }, expected: { name: "write", target: "/x", suppressed: false } },
+ { driver: "generic-file-path", rawName: "grep", rawInput: { pattern: "TODO" }, expected: { name: "grep", target: "TODO", suppressed: false } },
];
it.each(cases)("$driver × $rawName produces canonical shape", ({ rawName, rawInput, expected }) => {
expect(extractToolAudit(rawName, rawInput)).toEqual(expected);
@@ -1866,7 +2013,7 @@ describe("extractToolAudit — driver coverage matrix", () => {
});
describe("onBotAuditEvent — integration through onRuntimeEvent (T9/T10)", () => {
- it("emits canonical lowercase name for every driver × tool combo", () => {
+ it("emits canonical lowercase name for every driver × tool combo", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
@@ -1884,7 +2031,7 @@ describe("onBotAuditEvent — integration through onRuntimeEvent (T9/T10)", () =
];
for (const c of combos) {
- session.fire("runtime_event", { kind: "tool_call", name: c.name, input: c.input });
+ await session.fire("runtime_event", { kind: "tool_call", name: c.name, input: c.input });
}
const payloads = onBotAuditEvent.mock.calls
@@ -1893,14 +2040,14 @@ describe("onBotAuditEvent — integration through onRuntimeEvent (T9/T10)", () =
expect(payloads).toEqual(combos.map((c) => c.expect));
});
- it("alook-shell suppression fires for Bash, pi bash, AND codex shell", () => {
+ it("alook-shell suppression fires for Bash, pi bash, AND codex shell", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
- session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "alook inbox pull" } });
- session.fire("runtime_event", { kind: "tool_call", name: "bash", input: { command: "alook" } });
- session.fire("runtime_event", { kind: "tool_call", name: "shell", input: { command: "alook message send" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "Bash", input: { command: "alook inbox pull" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "bash", input: { command: "alook" } });
+ await session.fire("runtime_event", { kind: "tool_call", name: "shell", input: { command: "alook message send" } });
const toolCalls = onBotAuditEvent.mock.calls.filter(
([, ev]) => (ev as { kind?: string })?.kind === "tool_call"
@@ -1916,17 +2063,24 @@ describe("onBotAuditEvent — integration through onRuntimeEvent (T9/T10)", () =
describe("AgentProcessManager — onFsmTransition trace (observability, zero behavior change)", () => {
function makeWithTrace(trace?: (rec: Record<string, unknown>) => void) {
const session = fakeSession();
+ const sessions = [session];
+ let sessionIndex = 0;
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: () => {
+ const next = sessions[sessionIndex] ?? fakeSession();
+ if (!sessions[sessionIndex]) sessions.push(next);
+ sessionIndex += 1;
+ return next;
+ },
onFsmTransition: trace as never,
});
mgr.register("a1");
- return { mgr, session };
+ return { mgr, session, sessions };
}
- it("fires once per agent-scoped dispatch with the wedge-triage fields", () => {
+ it("fires once per agent-scoped dispatch with the wedge-triage fields", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hello" });
@@ -1934,14 +2088,66 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const wake = recs.find((r) => r.event === "wake");
expect(wake).toBeTruthy();
// Every field the triage needs to split the three "why no watchdog" exits.
- for (const k of ["agentId", "event", "status", "turnActive", "inbox", "lastDeliverAt", "lastProgressAt", "resetting", "resettingSince", "apmPhase", "effects", "nowMs"]) {
+ for (const k of ["agentId", "event", "status", "turnActive", "inbox", "lastDeliverAt", "lastProgressAt", "resetting", "resettingSince", "deliveryPhase", "effects", "nowMs"]) {
expect(wake).toHaveProperty(k);
}
expect(wake!.agentId).toBe("a1");
expect(Array.isArray(wake!.effects)).toBe(true);
});
- it("does NOT change behavior — the observed effect sequence is identical with and without the hook", () => {
+ it("uses manager pending mode only before admission reaches the driver, then projects authoritative snapshot diagnostics", async () => {
+ const recs: Record<string, unknown>[] = [];
+ const session = fakeSession();
+ const baseSnapshot = session.snapshot.bind(session);
+ session.snapshot = () => ({
+ ...baseSnapshot(),
+ diagnostics: {
+ deliveryPhase: "compacting",
+ metrics: {
+ physicalOpenCount: 1,
+ turnCount: 2,
+ commandAdmissionCount: 3,
+ commandAdmissionLatencyTotalMs: 12.5,
+ queueDwellCount: 4,
+ queueDwellTotalMs: 8.5,
+ sseReconnectCount: 6,
+ resumeOutcome: "resumed",
+ terminalOwnerKind: "transport_request",
+ },
+ },
+ });
+ const mgr = new AgentProcessManager({
+ driverFor: () => fakeDriver("codex"),
+ baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
+ sessionFactory: sessionFactoryFor(session),
+ onFsmTransition: ((row: Record<string, unknown>) => recs.push(row)) as never,
+ });
+ mgr.register("a1");
+ mgr.deliver("a1", { seq: 1, text: "hello" });
+ await vi.waitFor(() => expect(session.startResolver).toBeTypeOf("function"));
+
+ expect(recs.find((row) => row.event === "admission_started")).toMatchObject({
+ deliveryPhase: "admission_wait",
+ });
+ await session.pushAgentEvent({ type: "internal_progress", turnId: "test-turn", source: "test" });
+ expect(recs.filter((row) => row.event === "runtime_signal").at(-1)).toMatchObject({
+ deliveryPhase: "compacting",
+ physicalOpenCount: 1,
+ turnCount: 2,
+ commandAdmissionCount: 3,
+ commandAdmissionLatencyTotalMs: 12.5,
+ queueDwellCount: 4,
+ queueDwellTotalMs: 8.5,
+ sseReconnectCount: 6,
+ resumeOutcome: "resumed",
+ terminalOwnerKind: "transport_request",
+ });
+ expect(recs.some((row) => "apmPhase" in row)).toBe(false);
+ session.startResolver?.();
+ await Promise.resolve();
+ });
+
+ it("does NOT change behavior — the observed effect sequence is identical with and without the hook", async () => {
// deliver() returns a boolean (produced-effect), so compare the effect
// SEQUENCE the trace observed instead: it reflects exactly what the reducer
// emitted. A wired hook must not perturb that sequence.
@@ -1966,7 +2172,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => now,
tickIntervalMs: 5,
staleThresholdMs: 100,
@@ -2003,7 +2209,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => now,
tickIntervalMs: 5,
idleTimeoutMs: 50, // drive into `stopping` via idle-timeout
@@ -2015,8 +2221,8 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
mgr.deliver("a1", { seq: 1, text: "hi" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
// While running/idle-not-stopping, the field is null.
const runningRec = recs.find((r) => r.status === "running");
@@ -2042,15 +2248,15 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
// distinguishable from a clean nap/idle (red line 7). B1 only RECORDS it —
// onTurnEnd behavior is unchanged (verified in the "clean" case below).
- it("a mid-turn error then turn_end stamps fixed metadata but drops free-text errorDetail", () => {
+ it("a mid-turn error then turn_end stamps fixed metadata but drops free-text errorDetail", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
// Genuinely interrupt the turn: an `error` event (as the normalizer emits
// from an is_error result) FOLLOWED by the trailing turn_end.
- session.fire("runtime_event", { kind: "error", message: "boom: model overloaded" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "error", message: "boom: model overloaded" });
+ await session.fire("runtime_event", { kind: "turn_end" });
const turnEnd = recs.find((r) => r.event === "turn_end" && r.agentId === "a1");
expect(turnEnd).toBeTruthy();
@@ -2059,12 +2265,12 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
expect(turnEnd!.errorDetail).toBeUndefined();
});
- it("a CLEAN turn_end (no preceding error/kill) carries no endReason/terminationCause/errorDetail (byte-for-byte the old row)", () => {
+ it("a CLEAN turn_end (no preceding error/kill) carries no endReason/terminationCause/errorDetail (byte-for-byte the old row)", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
const turnEnd = recs.find((r) => r.event === "turn_end" && r.agentId === "a1");
expect(turnEnd).toBeTruthy();
@@ -2073,17 +2279,17 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
expect(turnEnd!.errorDetail).toBeUndefined();
});
- it("an intentional-kill (superseded) death-rattle error does NOT tag its turn_end errored (red line 5 — reset/nap is not a crash)", () => {
+ it("an intentional-kill (superseded) death-rattle error does NOT tag its turn_end errored (red line 5 — reset/nap is not a crash)", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
// Enter the reset/nap kill window, THEN the dying process rattles. The
// marker is gated by the same `!sessionSuperseded` as the audit, so it must
// NOT set — a nap must stay indistinguishable-from-clean, not read as crash.
mgr.markResetting("a1");
- session.fire("runtime_event", { kind: "error", message: "turn interrupted" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "error", message: "turn interrupted" });
+ await session.fire("runtime_event", { kind: "turn_end" });
const turnEnd = recs.find((r) => r.event === "turn_end" && r.agentId === "a1");
expect(turnEnd).toBeTruthy();
@@ -2091,22 +2297,23 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
expect(turnEnd!.terminationCause).toBeUndefined();
});
- it("a mid-turn error followed by a hard exit (no turn_end) clears the marker so the NEXT turn is not mis-tagged (3a marker-leak guard)", () => {
+ it("a mid-turn error followed by a hard exit (no turn_end) clears the marker so the NEXT turn is not mis-tagged (3a marker-leak guard)", async () => {
const recs: Record<string, unknown>[] = [];
- const { mgr, session } = makeWithTrace((r) => recs.push(r));
+ const { mgr, session, sessions } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
// Error with NO trailing turn_end, then a hard process exit (bypasses the
// normalizer) — the marker would otherwise leak in the map.
- session.fire("runtime_event", { kind: "error", message: "crashed hard" });
- session.fire("exit");
+ await session.fire("runtime_event", { kind: "error", message: "crashed hard" });
+ await session.fire("exit");
// A fresh wake spawns a new session; its clean turn_end must NOT inherit the
// stale marker.
recs.length = 0;
mgr.deliver("a1", { seq: 2, text: "again" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s2" });
- session.fire("runtime_event", { kind: "turn_end" });
+ const rebornSession = sessions[1]!;
+ await rebornSession.fire("runtime_event", { kind: "session_init", sessionId: "s2" });
+ await rebornSession.fire("runtime_event", { kind: "turn_end" });
const turnEnd = recs.find((r) => r.event === "turn_end" && r.agentId === "a1");
expect(turnEnd).toBeTruthy();
@@ -2126,7 +2333,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => now,
tickIntervalMs: 5,
staleThresholdMs: 100, // wedge → terminate_stalled after 100ms of no progress
@@ -2137,7 +2344,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
mgr.deliver("a1", { seq: 1, text: "hi" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
// Turn is in flight (turnActive) and makes NO progress. No error injected —
// this is a genuine hang, exactly Blair's case.
now = 200; // past staleThreshold=100 → stalled watchdog fires terminate_stalled
@@ -2148,7 +2355,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
// The SIGKILL makes the process emit its trailing turn_end (no error
// rattle needed — that's the whole point of keying on cause, not rattle).
recs.length = 0;
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "turn_end" });
const turnEnd = recs.find((r) => r.event === "turn_end" && r.agentId === "a1");
expect(turnEnd).toBeTruthy();
expect(turnEnd!.endReason).toBe("errored");
@@ -2172,11 +2379,16 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
// `stopping` → stoppingStuck escalates force_exit (the path that leaks).
const stopSpy = vi.fn();
const session = fakeSession();
+ const rebornSession = fakeSession();
session.stop = stopSpy;
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"), // per_turn — same stall setup as the killed_stalled test above
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (() => {
+ let index = 0;
+ const sessions = [session, rebornSession];
+ return (hooks: Parameters<SessionFactory>[0]) => bindFactorySession(hooks, sessions[index++]!);
+ })(),
now: () => now,
tickIntervalMs: 5,
staleThresholdMs: 100,
@@ -2188,7 +2400,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
mgr.deliver("a1", { seq: 1, text: "hi" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
// Turn is in flight (turnActive) and makes NO progress → terminate_stalled
// sets killed_stalled marker. (Same trigger as the killed_stalled test.)
now = 200;
@@ -2199,13 +2411,14 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
await vi.advanceTimersByTimeAsync(10);
expect(recs.find((r) => Array.isArray(r.effects) && (r.effects as string[]).includes("force_exit"))).toBeTruthy();
- // force_exit dispatched a synthetic exit → respawn. The reborn turn runs
- // and ends CLEANLY. Its turn_end must NOT inherit the leaked marker.
- session.startResolver?.();
+ // A later wake opens a fresh logical session. The reborn turn runs and
+ // ends CLEANLY. Its turn_end must NOT inherit the leaked marker.
+ mgr.deliver("a1", { seq: 2, text: "reborn" });
+ rebornSession.startResolver?.();
await Promise.resolve();
recs.length = 0;
- session.fire("runtime_event", { kind: "session_init", sessionId: "s2" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await rebornSession.fire("runtime_event", { kind: "session_init", sessionId: "s2" });
+ await rebornSession.fire("runtime_event", { kind: "turn_end" });
const turnEnd = recs.find((r) => r.event === "turn_end" && r.agentId === "a1");
expect(turnEnd).toBeTruthy();
// The whole point: marker was cleared at force_exit, so this healthy turn
@@ -2234,7 +2447,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => now,
tickIntervalMs: 5,
idleTimeoutMs: 50, // idle → voluntary stop(idle_timeout), flips stopping
@@ -2246,8 +2459,8 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
mgr.deliver("a1", { seq: 1, text: "hi" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" }); // clean end → idle
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" }); // clean end → idle
recs.length = 0;
now = 100; // past idleTimeout=50 → idle-hibernation issues a voluntary stop
await vi.advanceTimersByTimeAsync(10);
@@ -2267,13 +2480,13 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
// trace. T1 threads the raw physical fact (exitCode/exitSignal/abnormal) onto
// the exit event → trace. Physical fact only; onExit behavior UNCHANGED.
- it("T1 — an established session's exit on a signal records exitSignal + abnormal=true on the trace exit row", () => {
+ it("T1 — an established session's exit on a signal records exitSignal + abnormal=true on the trace exit row", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // hasEstablished
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // hasEstablished
// Hard death on SIGKILL, NOT a requested stop → abnormal physical fact.
- session.fire("exit", { signal: "SIGKILL", reason: "runtime_exit" });
+ await session.fire("exit", { signal: "SIGKILL", reason: "runtime_exit" });
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
@@ -2282,12 +2495,12 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
expect(exitRec!.abnormal).toBe(true);
});
- it("T1 — an established session's non-zero code exit records exitCode + abnormal=true", () => {
+ it("T1 — an established session's non-zero code exit records exitCode + abnormal=true", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("exit", { code: 137, reason: "runtime_exit" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("exit", { code: 137, reason: "runtime_exit" });
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
@@ -2296,12 +2509,12 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
expect(exitRec!.abnormal).toBe(true);
});
- it("T1 — a clean code-0 exit records abnormal=false (distinguishable from a crash in the trace)", () => {
+ it("T1 — a clean code-0 exit records abnormal=false (distinguishable from a crash in the trace)", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("exit", { code: 0, reason: "runtime_exit" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("exit", { code: 0, reason: "runtime_exit" });
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
@@ -2309,7 +2522,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
expect(exitRec!.abnormal).toBe(false);
});
- it("T1 — a deliberate stop (reason=requested) records the physical fact but abnormal=false", () => {
+ it("T1 — a deliberate stop (reason=requested) records the physical fact but abnormal=false", async () => {
// A requested stop that still died on a signal (SIGTERM grace → the process
// exits): the physical fact (signal) is recorded, but it's NOT abnormal —
// reason==="requested" gates that. So trace shows how it died without
@@ -2317,8 +2530,8 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("exit", { signal: "SIGTERM", reason: "requested" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("exit", { signal: "SIGTERM", reason: "requested" });
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
@@ -2326,28 +2539,28 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
expect(exitRec!.abnormal).toBe(false);
});
- it("T1 — the exit physical fact is READ-ONLY: abnormal exit and clean exit produce the SAME onExit respawn/idle decision (Claudette #382)", () => {
+ it("T1 — the exit physical fact is READ-ONLY: abnormal exit and clean exit produce the SAME onExit respawn/idle decision (Claudette #382)", async () => {
// With a queued inbox, onExit respawns (spawn effect); with empty inbox it
// settles idle. That decision keys on inbox.length ONLY — the new
// exitCode/exitSignal/abnormal fields must NOT change the branch.
- function exitEffectsFor(exitInfo: Record<string, unknown>, queueBefore: boolean): string[] {
+ async function exitEffectsFor(exitInfo: Record<string, unknown>, queueBefore: boolean): Promise<string[]> {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
if (queueBefore) mgr.deliver("a1", { seq: 2, text: "queued" }); // inbox non-empty at exit
recs.length = 0;
- session.fire("exit", exitInfo);
+ await session.fire("exit", exitInfo);
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
return (exitRec!.effects as string[]) ?? [];
}
// Empty inbox: idle (no spawn), identical for abnormal vs clean.
- expect(exitEffectsFor({ signal: "SIGKILL", reason: "runtime_exit" }, false)).toEqual(
- exitEffectsFor({ code: 0, reason: "runtime_exit" }, false),
+ expect(await exitEffectsFor({ signal: "SIGKILL", reason: "runtime_exit" }, false)).toEqual(
+ await exitEffectsFor({ code: 0, reason: "runtime_exit" }, false),
);
// Queued inbox: respawn (spawn), identical for abnormal vs clean.
- expect(exitEffectsFor({ signal: "SIGKILL", reason: "runtime_exit" }, true)).toEqual(
- exitEffectsFor({ code: 0, reason: "runtime_exit" }, true),
+ expect(await exitEffectsFor({ signal: "SIGKILL", reason: "runtime_exit" }, true)).toEqual(
+ await exitEffectsFor({ code: 0, reason: "runtime_exit" }, true),
);
});
@@ -2357,43 +2570,43 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
// in the trace it was indistinguishable from a clean exit. T2 carries the
// failure reason (same value as the audit) onto the exit event → trace.
- it("T2 — a pre-handshake exit records spawnFailureReason on the trace exit row", () => {
+ it("T2 — a pre-handshake exit records spawnFailureReason on the trace exit row", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
// Exit with NO prior runtime_event (never established) → pre_handshake_exit.
- session.fire("exit");
+ await session.fire("exit");
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
expect(exitRec!.spawnFailureReason).toBe("pre_handshake_exit");
});
- it("T2 — an ENOENT spawn error carries that exact reason (same string as the web audit) into the trace", () => {
+ it("T2 — an ENOENT spawn error carries that exact reason (same string as the web audit) into the trace", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("error", { code: "ENOENT" });
- session.fire("exit");
+ await session.fire("error", { code: "ENOENT" });
+ await session.fire("exit");
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
expect(exitRec!.spawnFailureReason).toBe("ENOENT");
});
- it("T2 — a normal established exit carries NO spawnFailureReason", () => {
+ it("T2 — a normal established exit carries NO spawnFailureReason", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // established
- session.fire("exit", { code: 0, reason: "runtime_exit" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" }); // established
+ await session.fire("exit", { code: 0, reason: "runtime_exit" });
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
expect(exitRec!.spawnFailureReason).toBeUndefined();
});
- it("T2 no-leak (Claudette #398) — a spawn failure then a SUCCESSFUL spawn + clean exit: the clean exit carries NO stale spawnFailureReason", () => {
+ it("T2 no-leak (Claudette #398) — a spawn failure then a SUCCESSFUL spawn + clean exit: the clean exit carries NO stale spawnFailureReason", async () => {
// Guards the per-spawn `state` isolation: the failure reason lives on the
// spawn's own `state` object (fresh each doSpawn), so a later spawn's exit
// can't inherit it. This assertion would also catch a regression to a
@@ -2405,10 +2618,10 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => {
+ sessionFactory: (hooks) => {
const s = fakeSession();
sessions.push(s);
- return s;
+ return bindFactorySession(hooks, s);
},
onFsmTransition: ((r: Record<string, unknown>) => recs.push(r)) as never,
});
@@ -2416,13 +2629,13 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
// Spawn #1: fails pre-handshake.
mgr.deliver("a1", { seq: 1, text: "hi" });
- sessions[0]!.fire("exit"); // → pre_handshake_exit, agent back to idle
+ await sessions[0]!.fire("exit"); // → pre_handshake_exit, agent back to idle
// Spawn #2: succeeds (establishes), then exits cleanly.
recs.length = 0;
mgr.deliver("a1", { seq: 2, text: "again" });
- sessions[1]!.fire("runtime_event", { kind: "session_init", sessionId: "s2" });
- sessions[1]!.fire("exit", { code: 0, reason: "runtime_exit" });
+ await sessions[1]!.fire("runtime_event", { kind: "session_init", sessionId: "s2" });
+ await sessions[1]!.fire("exit", { code: 0, reason: "runtime_exit" });
const cleanExit = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(cleanExit).toBeTruthy();
@@ -2445,7 +2658,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => now,
tickIntervalMs: 5,
staleThresholdMs: 100,
@@ -2456,12 +2669,12 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
mgr.deliver("a1", { seq: 1, text: "hi" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
now = 200; // past staleThreshold → terminate_stalled (sets the semantic marker)
await vi.advanceTimersByTimeAsync(10);
// The killed process's real exit (via the exit listener, where state lives).
recs.length = 0;
- session.fire("exit", { signal: "SIGKILL", reason: "requested" });
+ await session.fire("exit", { signal: "SIGKILL", reason: "requested" });
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
@@ -2484,7 +2697,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => now,
tickIntervalMs: 5,
idleTimeoutMs: 50,
@@ -2496,12 +2709,12 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
mgr.deliver("a1", { seq: 1, text: "hi" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" }); // clean end → idle
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" }); // clean end → idle
now = 100; // past idleTimeout → voluntary stop (sets idle_stop, NOT killed_stalled)
await vi.advanceTimersByTimeAsync(10);
recs.length = 0;
- session.fire("exit", { signal: "SIGTERM", reason: "requested" });
+ await session.fire("exit", { signal: "SIGTERM", reason: "requested" });
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
@@ -2526,7 +2739,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
const mgr = new AgentProcessManager({
driverFor: () => persistentDriver,
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => now,
tickIntervalMs: 5,
idleTimeoutMs: 50,
@@ -2538,8 +2751,8 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
mgr.deliver("a1", { seq: 1, text: "hi" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
now = 100; // idle-timeout → stopping (stop swallowed, no exit)
await vi.advanceTimersByTimeAsync(10);
recs.length = 0;
@@ -2559,12 +2772,12 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
}
});
- it("T3 — a plain runtime exit (no recovery) carries NO terminationSemantics", () => {
+ it("T3 — a plain runtime exit (no recovery) carries NO terminationSemantics", async () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("exit", { code: 0, reason: "runtime_exit" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("exit", { code: 0, reason: "runtime_exit" });
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
expect(exitRec).toBeTruthy();
@@ -2583,7 +2796,7 @@ describe("T1 — abnormal-exit user audit stays gated (no nap-noise on deliberat
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
- sessionFactory: () => session,
+ sessionFactory: (hooks) => bindFactorySession(hooks, session),
now: () => now,
tickIntervalMs: 5,
staleThresholdMs: 100,
@@ -2595,12 +2808,12 @@ describe("T1 — abnormal-exit user audit stays gated (no nap-noise on deliberat
mgr.deliver("a1", { seq: 1, text: "hi" });
session.startResolver?.();
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
// Stall → terminate_stalled sets suppressExitLog before the kill.
now = 200;
await vi.advanceTimersByTimeAsync(10);
// The killed process exits on a signal (a requested/deliberate stop path).
- session.fire("exit", { signal: "SIGKILL", reason: "requested" });
+ await session.fire("exit", { signal: "SIGKILL", reason: "requested" });
// Trace: the physical fact IS recorded (forensics needs it).
const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
@@ -2653,16 +2866,23 @@ function b1GatedDriver(): Driver {
} as Driver;
}
-function b1Session(order: string[], name = "s"): FakeSession {
+function b1Session(order: string[], name = "s", turnId = "test-turn"): FakeSession {
const session = fakeSession();
- session.start = vi.fn(async (input: { text: string; sessionId?: string }) => {
+ session.start = vi.fn(async (input: { id: string; text: string }) => {
order.push(`${name}:start:${input.text}`);
+ void session.pushAgentEvent({ type: "command_accepted", commandId: input.id, turnId, delivery: "prompt" });
+ void session.pushAgentEvent({ type: "turn_started", turnId, commandIds: [input.id] });
+ return { status: "accepted" as const, delivery: "prompt" as const, commandId: input.id, turnId };
});
- session.send = vi.fn((input: { text: string; mode: "busy" | "idle" }) => {
- order.push(`${name}:send:${input.mode}:${input.text}`);
+ session.send = vi.fn(async (input: { id: string; text: string }) => {
+ order.push(`${name}:send:${input.text}`);
+ void session.pushAgentEvent({ type: "command_accepted", commandId: input.id, turnId, delivery: "steer" });
+ void session.pushAgentEvent({ type: "turn_started", turnId, commandIds: [input.id] });
+ return { status: "accepted" as const, delivery: "steer" as const, commandId: input.id, turnId };
});
- session.stop = vi.fn((opts?: { reason?: string }) => {
+ session.stop = vi.fn(async (opts?: { reason?: string }) => {
order.push(`${name}:stop:${opts?.reason ?? ""}`);
+ return { status: "accepted" as const, requestId: "test-stop" };
});
return session;
}
@@ -2690,7 +2910,7 @@ function b1Manager(opts: {
config: {} as LaunchContext["config"],
credentialProxy: {} as LaunchContext["credentialProxy"],
}),
- sessionFactory: () => sessions[index++]!,
+ sessionFactory: (hooks) => bindFactorySession(hooks, sessions[index++]!),
onFsmTransition: opts.trace as never,
now: opts.now,
...(opts.handshakeTimeoutMs !== undefined ? { handshakeTimeoutMs: opts.handshakeTimeoutMs } : {}),
@@ -2747,11 +2967,11 @@ describe("B1 red gate — daemon-owned turn span lifecycle", () => {
mgr.deliver("a1", { seq: 1, text: "first" });
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "session-a" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "session-a" });
mgr.deliver("a1", { seq: 2, text: "busy" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "turn_end" });
mgr.deliver("a1", { seq: 3, text: "idle-second" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "turn_end" });
const begins = b1SpanRows(rows, "turn_begin");
const ends = b1SpanRows(rows, "turn_end");
@@ -2762,10 +2982,10 @@ describe("B1 red gate — daemon-owned turn span lifecycle", () => {
expect(rows.filter((row) => row.event === "runtime_signal" && row.traceTurnId === "launch-a:1").length).toBeGreaterThan(0);
expect(order.indexOf("trace:turn_begin:1")).toBeLessThan(order.indexOf("s:start:first"));
expect(order.indexOf("trace:turn_end:1")).toBeLessThan(order.indexOf("trace:turn_begin:2"));
- expect(order.filter((entry) => entry.includes("send:busy:busy"))).toHaveLength(1);
+ expect(order.filter((entry) => entry.includes("send:busy"))).toHaveLength(1);
});
- it("closes the old per-turn span inside dispatch before a queued spawn effect opens the replacement", async () => {
+ it("keeps a queued next-turn command inside the same logical-session span boundary", async () => {
const order: string[] = [];
const rows: B1TraceRow[] = [];
const first = b1Session(order, "a");
@@ -2782,21 +3002,18 @@ describe("B1 red gate — daemon-owned turn span lifecycle", () => {
mgr.deliver("a1", { seq: 1, text: "first" });
await Promise.resolve();
mgr.deliver("a1", { seq: 2, text: "queued" });
- first.fire("runtime_event", { kind: "turn_end" });
- first.fire("exit", { code: 0, reason: "runtime_exit" });
+ await first.fire("runtime_event", { kind: "turn_end" });
+ await first.fire("exit", { code: 0, reason: "runtime_exit" });
await Promise.resolve();
const begins = b1SpanRows(rows, "turn_begin");
const ends = b1SpanRows(rows, "turn_end");
- expect(begins).toHaveLength(2);
+ expect(begins).toHaveLength(1);
expect(ends).toHaveLength(1);
- expect(order.indexOf(`trace:turn_end:${String(ends[0]!.daemonTurnOrdinal)}`)).toBeLessThan(
- order.indexOf(`trace:turn_begin:${String(begins[1]!.daemonTurnOrdinal)}`),
- );
- expect(order.filter((entry) => entry.startsWith("b:start:"))).toHaveLength(1);
+ expect(order.filter((entry) => entry.startsWith("b:start:"))).toHaveLength(0);
});
- it("uses the process nonce fallback only when launchId is absent", () => {
+ it("uses the process nonce fallback only when launchId is absent", async () => {
const rows: B1TraceRow[] = [];
const session = b1Session([]);
const { mgr } = b1Manager({ sessions: [session], launchId: null, trace: (row) => rows.push(row) });
@@ -2819,8 +3036,8 @@ describe("B1 red gate — daemon-owned turn span lifecycle", () => {
});
cleanManager.deliver("a1", { seq: 1, text: "clean" });
await Promise.resolve();
- cleanSession.fire("runtime_event", { kind: "session_init", sessionId: "clean-session" });
- cleanSession.fire("runtime_event", { kind: "turn_end" });
+ await cleanSession.fire("runtime_event", { kind: "session_init", sessionId: "clean-session" });
+ await cleanSession.fire("runtime_event", { kind: "turn_end" });
const cleanEnd = b1SpanRows(cleanRows, "turn_end")[0];
expect(cleanEnd).toBeTruthy();
@@ -2835,9 +3052,9 @@ describe("B1 red gate — daemon-owned turn span lifecycle", () => {
});
errorManager.deliver("a1", { seq: 1, text: "error" });
await Promise.resolve();
- errorSession.fire("runtime_event", { kind: "session_init", sessionId: "error-session" });
- errorSession.fire("runtime_event", { kind: "error", message: "HOSTILE_RUNTIME_DETAIL_220b" });
- errorSession.fire("runtime_event", { kind: "turn_end" });
+ await errorSession.fire("runtime_event", { kind: "session_init", sessionId: "error-session" });
+ await errorSession.fire("runtime_event", { kind: "error", message: "HOSTILE_RUNTIME_DETAIL_220b" });
+ await errorSession.fire("runtime_event", { kind: "turn_end" });
const errorEnd = b1SpanRows(errorRows, "turn_end")[0];
expect(errorEnd).toBeTruthy();
@@ -2852,9 +3069,12 @@ describe("B1 red gate — daemon-owned turn span lifecycle", () => {
});
unknownManager.deliver("a1", { seq: 1, text: "unknown" });
await Promise.resolve();
+ await Promise.resolve();
(unknownManager as unknown as { dispatch(event: unknown): void }).dispatch({
- type: "turn_end",
+ type: "turn_completed",
agentId: "a1",
+ sessionInstanceId: "test-instance",
+ turnId: "test-turn",
nowMs: 1,
endReason: "errored",
terminationCause: "HOSTILE_UNKNOWN_CAUSE_832a",
@@ -2867,7 +3087,7 @@ describe("B1 red gate — daemon-owned turn span lifecycle", () => {
expect(JSON.stringify(unknownRows)).not.toContain("HOSTILE_UNKNOWN_CAUSE_832a");
});
- it("annotates active tick/progress/runtime_signal rows and clears every later row after close", async () => {
+ it("annotates active tick/root_work/runtime_signal rows and leaves tail diagnostics observational", async () => {
vi.useFakeTimers();
try {
let now = 1_000;
@@ -2882,26 +3102,27 @@ describe("B1 red gate — daemon-owned turn span lifecycle", () => {
mgr.start();
mgr.deliver("a1", { seq: 1, text: "active" });
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "text", text: "root work" });
now = 1_005;
await vi.advanceTimersByTimeAsync(5);
const begin = b1SpanRows(rows, "turn_begin")[0];
expect(begin).toBeTruthy();
const activeId = begin!.traceTurnId;
- for (const event of ["progress", "runtime_signal", "tick"]) {
+ for (const event of ["root_work", "runtime_signal", "tick"]) {
expect(rows.some((row) => row.event === event && row.traceTurnId === activeId)).toBe(true);
}
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "turn_end" });
const close = b1SpanRows(rows, "turn_end")[0];
expect(close!.traceTurnId).toBe(activeId);
rows.length = 0;
now = 1_010;
await vi.advanceTimersByTimeAsync(5);
- session.fire("runtime_event", { kind: "internal_progress" });
- session.fire("exit", { code: 0, reason: "runtime_exit" });
+ await session.fire("stderr", "tail diagnostic");
+ await session.fire("exit", { code: 0, reason: "runtime_exit" });
expect(rows.some((row) => ["tick", "runtime_signal", "exit"].includes(String(row.event)))).toBe(true);
expect(rows.every((row) => row.traceTurnId === undefined)).toBe(true);
} finally {
@@ -2917,8 +3138,8 @@ describe("B1 red gate — strict read-only trace sink", () => {
const { mgr } = b1Manager({ sessions: [session], trace, now: () => 1_700_000_000_000 });
mgr.deliver("a1", { seq: 1, text: "one" });
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
mgr.deliver("a1", { seq: 2, text: "two" });
await mgr.stop("a1");
return { state: mgr.snapshot(), calls, runtimeCalls: b1CallProjection(session) };
@@ -3008,20 +3229,57 @@ describe("B1 red gate — exact-once terminal matrix", () => {
});
}
- it("physical exit aborts once and its duplicate late exit cannot close again", () => {
+ it("shutdown joins a session cleanup that was already stopping", async () => {
+ const session = b1Session([]);
+ let finishCleanup!: (result: AgentSessionResult) => void;
+ const cleanupFinished = new Promise<AgentSessionResult>((resolve) => {
+ finishCleanup = resolve;
+ });
+ Object.defineProperty(session, "closed", { value: cleanupFinished });
+ session.stop = vi.fn(async () => ({
+ status: "already_stopping" as const,
+ requestId: "cleanup-in-flight",
+ }));
+ const { mgr } = b1Manager({ sessions: [session] });
+ mgr.deliver("a1", { seq: 1, text: "active Cursor turn" });
+ await Promise.resolve();
+
+ let shutdownSettled = false;
+ const shutdown = mgr.stopAll().then(() => {
+ shutdownSettled = true;
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(session.stop).toHaveBeenCalledWith({ reason: "shutdown", forceAfterMs: 2_000 });
+ expect(shutdownSettled).toBe(false);
+
+ finishCleanup({
+ outcome: "stopped",
+ requested: true,
+ exitCode: null,
+ signal: null,
+ cleanup: { status: "released" },
+ });
+ await shutdown;
+ expect(shutdownSettled).toBe(true);
+ });
+
+ it("physical exit aborts once and its duplicate late exit cannot close again", async () => {
const rows: B1TraceRow[] = [];
const session = b1Session([]);
const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
mgr.deliver("a1", { seq: 1, text: "active" });
- session.fire("exit", { signal: "SIGKILL", reason: "runtime_exit" });
- session.fire("exit", { signal: "SIGKILL", reason: "runtime_exit" });
+ await Promise.resolve();
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("exit", { signal: "SIGKILL", reason: "runtime_exit" });
+ await session.fire("exit", { signal: "SIGKILL", reason: "runtime_exit" });
const aborts = b1SpanRows(rows, "turn_abort");
expect(aborts).toHaveLength(1);
expect(aborts[0]!.abortCause).toBe("physical_exit");
});
- it("start synchronous throw aborts once and rethrows the exact error", () => {
+ it("start synchronous throw aborts once and reports the public open failure", async () => {
const rows: B1TraceRow[] = [];
const error = new Error("unique-start-sync-secret");
const session = b1Session([]);
@@ -3030,7 +3288,7 @@ describe("B1 red gate — exact-once terminal matrix", () => {
});
const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
- expect(() => mgr.deliver("a1", { seq: 1, text: "active" })).toThrow(error);
+ expect(() => mgr.deliver("a1", { seq: 1, text: "active" })).not.toThrow();
const aborts = b1SpanRows(rows, "turn_abort");
expect(aborts).toHaveLength(1);
expect(aborts[0]!.abortCause).toBe("start_threw");
@@ -3049,6 +3307,399 @@ describe("B1 red gate — exact-once terminal matrix", () => {
expect(aborts[0]!.abortCause).toBe("start_rejected");
});
+ it("a rejected start receipt reports the public reason and stops the session", async () => {
+ const session = b1Session([]);
+ session.start = vi.fn(async () => ({
+ status: "rejected" as const,
+ reason: "runtime_unavailable" as const,
+ error: { category: "process" as const, code: "start_denied", message: "denied", retryable: true },
+ }));
+ const onRuntimeSpawnFailed = vi.fn();
+ const { mgr } = b1Manager({ sessions: [session], onRuntimeSpawnFailed });
+ mgr.deliver("a1", { seq: 1, text: "active" });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(onRuntimeSpawnFailed).toHaveBeenCalledWith("codex", "start_denied");
+ expect(session.stop).toHaveBeenCalledTimes(1);
+ });
+
+ it("drains messages queued during start and audits a rejected queued receipt", async () => {
+ const session = fakeSession();
+ session.send = vi.fn(async () => ({
+ status: "rejected" as const,
+ reason: "closed" as const,
+ error: { category: "process" as const, code: "queued_denied", message: "closed", retryable: true },
+ }));
+ const { mgr } = b1Manager({ sessions: [session] });
+ const internal = mgr as unknown as {
+ doSpawn(agentId: string, messages: Array<{ id: string; seq: number; text: string }>, resumeSessionId: null): void;
+ };
+ internal.doSpawn("a1", [
+ { id: "first", seq: 1, text: "first" },
+ { id: "queued", seq: 2, text: "queued" },
+ ], null);
+ session.startResolver?.();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(session.send).toHaveBeenCalledTimes(1);
+ });
+
+ it("audits a queued send promise rejection without leaking it", async () => {
+ const session = fakeSession();
+ session.send = vi.fn(() => Promise.reject(new Error("queued send rejected")));
+ const { mgr } = b1Manager({ sessions: [session] });
+ const internal = mgr as unknown as {
+ doSpawn(agentId: string, messages: Array<{ id: string; seq: number; text: string }>, resumeSessionId: null): void;
+ };
+ internal.doSpawn("a1", [
+ { id: "first", seq: 1, text: "first" },
+ { id: "queued", seq: 2, text: "queued" },
+ ], null);
+ session.startResolver?.();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(session.send).toHaveBeenCalledTimes(1);
+ });
+
+ it("stops a session whose asynchronous factory resolves after its spawn state was superseded", async () => {
+ let resolveFactory!: (session: FakeSession) => void;
+ const created = new Promise<FakeSession>((resolve) => { resolveFactory = resolve; });
+ const session = b1Session([]);
+ const mgr = new AgentProcessManager({
+ driverFor: () => b1PersistentDriver(),
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: (() => created) as SessionFactory,
+ });
+ mgr.register("a1", { launchId: "launch-a" });
+ mgr.deliver("a1", { seq: 1, text: "first" });
+ const internal = mgr as unknown as { activeSpawnState: Map<string, object> };
+ internal.activeSpawnState.delete("a1");
+ resolveFactory(session);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(session.stop).toHaveBeenCalledWith({ reason: "shutdown", forceAfterMs: 2_000 });
+ expect(session.start).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["rejected receipt", () => Promise.resolve({
+ status: "rejected" as const,
+ reason: "closed" as const,
+ error: { category: "process" as const, code: "send_denied", message: "closed", retryable: true },
+ })],
+ ["rejected promise", () => Promise.reject(new Error("send rejected"))],
+ ] as const)("%s from an established send closes the active turn once", async (_name, send) => {
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
+ mgr.deliver("a1", { seq: 1, text: "first" });
+ await Promise.resolve();
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ session.send = vi.fn(send);
+ mgr.deliver("a1", { seq: 2, text: "second" });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(session.send).toHaveBeenCalledTimes(1);
+ expect(b1SpanRows(rows, "turn_abort").filter((row) => row.abortCause === "send_threw")).toHaveLength(1);
+ });
+
+ it("reports an event-stream rejection and a closed-promise rejection", async () => {
+ const eventFailure = b1Session([]);
+ Object.defineProperty(eventFailure, "events", {
+ value: {
+ maxBufferedBytes: 4_194_304,
+ [Symbol.asyncIterator]() {
+ return { next: () => Promise.reject(new Error("event stream rejected")) };
+ },
+ },
+ });
+ const eventFailureReported = vi.fn();
+ const { mgr: eventMgr } = b1Manager({ sessions: [eventFailure], onRuntimeSpawnFailed: eventFailureReported });
+ eventMgr.deliver("a1", { seq: 1, text: "event failure" });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(eventFailureReported).toHaveBeenCalledWith("codex", "event_stream_failed");
+
+ const closeFailure = b1Session([]);
+ Object.defineProperty(closeFailure, "closed", { value: Promise.reject(new Error("closed rejected")) });
+ const closeFailureReported = vi.fn();
+ const { mgr: closeMgr } = b1Manager({ sessions: [closeFailure], onRuntimeSpawnFailed: closeFailureReported });
+ closeMgr.deliver("a1", { seq: 1, text: "close failure" });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(closeFailureReported).toHaveBeenCalledWith("codex", "session_closed_rejected");
+ });
+
+ it("maps all public session event families into backend-neutral runtime signals", async () => {
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
+ mgr.deliver("a1", { seq: 1, text: "active" });
+ await Promise.resolve();
+ const internal = mgr as unknown as {
+ activeSpawnState: Map<string, object>;
+ onAgentEvent(agentId: string, event: AgentEvent<BuiltinBackendSpecs, "codex">, runtimeId: "codex", owner: object): void;
+ };
+ const owner = internal.activeSpawnState.get("a1")!;
+ const baselineSignals = rows.filter((row) => row.event === "runtime_signal").length;
+ let sequence = 100;
+ const publish = (event: object) => internal.onAgentEvent("a1", {
+ ...event,
+ sequence: ++sequence,
+ sessionInstanceId: "test-instance",
+ at: Date.now(),
+ } as never, "codex", owner);
+ publish({ type: "tool_started", turnId: "test-turn", name: "Read", input: {} });
+ publish({ type: "tool_finished", turnId: "test-turn", name: "Read" });
+ publish({ type: "diagnostic", severity: "warning", source: "codex", message: "warning" });
+ publish({ type: "token_usage", turnId: "test-turn", source: "codex", usage: {}, details: {} });
+ publish({ type: "rate_limits", turnId: "test-turn", source: "codex", details: {} });
+ publish({ type: "command_queued", commandId: "queued", reason: "runtime_busy" });
+ publish({ type: "command_accepted", commandId: "accepted", turnId: "test-turn", delivery: "steer" });
+ publish({
+ type: "command_failed",
+ commandId: "failed",
+ error: { category: "process", code: "failed", message: "failed", retryable: true },
+ });
+ publish({ type: "turn_started", turnId: "test-turn", commandIds: ["accepted"] });
+
+ expect(rows.filter((row) => row.event === "runtime_signal")).toHaveLength(baselineSignals + 9);
+ });
+
+ it("keeps tail telemetry observational while turn-correlated work can recover a false terminal", async () => {
+ const session = b1Session([], "s", "root-turn");
+ const { mgr } = b1Manager({ sessions: [session] });
+ mgr.deliver("a1", { id: "root-command", seq: 1, text: "active" });
+ await Promise.resolve();
+ const internal = mgr as unknown as {
+ activeSpawnState: Map<string, object>;
+ onAgentEvent(agentId: string, event: AgentEvent<BuiltinBackendSpecs, "codex">, runtimeId: "codex", owner: object): void;
+ };
+ const owner = internal.activeSpawnState.get("a1")!;
+ let sequence = 200;
+ const publish = (event: object) => internal.onAgentEvent("a1", {
+ ...event,
+ sequence: ++sequence,
+ sessionInstanceId: "test-instance",
+ at: Date.now(),
+ } as never, "codex", owner);
+
+ publish({ type: "turn_started", turnId: "root-turn", commandIds: ["root-command"] });
+ publish({
+ type: "turn_completed",
+ turnId: "root-turn",
+ commandIds: ["root-command"],
+ result: { outcome: "success", backendSessionId: "s1" },
+ });
+ const idleSince = mgr.snapshot().agents.a1.idleSince;
+ expect(mgr.snapshot().agents.a1).toMatchObject({ turnActive: false, turnId: "root-turn" });
+
+ publish({ type: "diagnostic", turnId: "root-turn", severity: "warning", source: "codex", message: "tail" });
+ publish({ type: "token_usage", turnId: "root-turn", source: "codex", usage: {}, details: {} });
+ publish({ type: "rate_limits", source: "codex", details: {} });
+ expect(mgr.snapshot().agents.a1).toMatchObject({ turnActive: false, idleSince });
+
+ publish({ type: "internal_progress", turnId: "root-turn", source: "codex", itemType: "root-work" });
+ expect(mgr.snapshot().agents.a1).toMatchObject({ turnActive: true, turnId: "root-turn", idleSince: null });
+ });
+
+ it("requeues a later asynchronous command_failed exactly once by delivery id", async () => {
+ const session = b1Session([]);
+ const { mgr } = b1Manager({ sessions: [session] });
+ mgr.deliver("a1", { id: "first", seq: 1, text: "first" });
+ await Promise.resolve();
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ session.send = vi.fn(async () => ({ status: "queued" as const, reason: "unsafe_boundary" as const, commandId: "later" }));
+ mgr.deliver("a1", { id: "later", seq: 2, text: "later" });
+ await Promise.resolve();
+
+ const internal = mgr as unknown as {
+ activeSpawnState: Map<string, object>;
+ onAgentEvent(agentId: string, event: AgentEvent<BuiltinBackendSpecs, "codex">, runtimeId: "codex", owner: object): void;
+ };
+ const owner = internal.activeSpawnState.get("a1")!;
+ const failed = {
+ type: "command_failed",
+ commandId: "later",
+ turnId: "test-turn",
+ error: { category: "process", code: "delivery_failed", message: "failed", retryable: true },
+ sequence: 300,
+ sessionInstanceId: "test-instance",
+ at: Date.now(),
+ } as const;
+ internal.onAgentEvent("a1", failed as never, "codex", owner);
+ internal.onAgentEvent("a1", { ...failed, sequence: 301 } as never, "codex", owner);
+
+ expect(mgr.snapshot().agents.a1.inbox).toEqual([{ id: "later", seq: 2, text: "later" }]);
+ expect(session.stop).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not expire a driver-acknowledged next-turn queue while the active root keeps making progress", async () => {
+ vi.useFakeTimers();
+ try {
+ let now = 0;
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([], "cursor", "root-turn");
+ const { mgr } = b1Manager({
+ sessions: [session],
+ driver: fakeDriver("cursor"),
+ trace: (row) => rows.push(row),
+ now: () => now,
+ tickIntervalMs: 5,
+ staleThresholdMs: 50,
+ });
+ mgr.start();
+ mgr.deliver("a1", { id: "root", seq: 1, text: "root" });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ session.send = vi.fn(async (input: { id: string }) => {
+ void session.pushAgentEvent({
+ type: "command_queued",
+ commandId: input.id,
+ reason: "runtime_busy",
+ });
+ return { status: "queued" as const, reason: "runtime_busy" as const, commandId: input.id };
+ });
+
+ now = 10;
+ mgr.deliver("a1", { id: "next", seq: 2, text: "next" });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(mgr.snapshot().agents.a1.pendingAdmissions).toHaveLength(1);
+
+ // The queued command is waiting for Cursor's next-turn boundary, while
+ // the original root is demonstrably healthy. Its queue dwell may exceed
+ // the generic admission watchdog without turning into a send stall.
+ now = 55;
+ await session.pushAgentEvent({
+ type: "internal_progress",
+ turnId: "root-turn",
+ source: "cursor",
+ });
+ now = 70;
+ await vi.advanceTimersByTimeAsync(10);
+
+ expect(mgr.snapshot().agents.a1.status).toBe("running");
+ expect(mgr.snapshot().agents.a1.pendingAdmissions).toHaveLength(1);
+ expect(session.stop).not.toHaveBeenCalled();
+ expect(rows.some((row) =>
+ Array.isArray(row.effects) && (row.effects as string[]).includes("expire_admission")
+ )).toBe(false);
+
+ await mgr.stopAll();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("does not terminate a long tool wait hidden by a next-turn queue, but resumes ordinary stall detection", async () => {
+ vi.useFakeTimers();
+ try {
+ let now = 0;
+ let deliveryPhase: "working" | "tool_wait" | "next_turn_queued" = "working";
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([], "cursor", "root-turn");
+ const baseSnapshot = session.snapshot.bind(session);
+ session.snapshot = () => ({
+ ...baseSnapshot(),
+ diagnostics: {
+ deliveryPhase,
+ metrics: {
+ physicalOpenCount: 1,
+ turnCount: 1,
+ commandAdmissionCount: 1,
+ commandAdmissionLatencyTotalMs: 0,
+ queueDwellCount: 0,
+ queueDwellTotalMs: 0,
+ sseReconnectCount: 0,
+ resumeOutcome: "fresh",
+ terminalOwnerKind: "transport_request",
+ },
+ },
+ });
+ const { mgr } = b1Manager({
+ sessions: [session],
+ driver: fakeDriver("cursor"),
+ trace: (row) => rows.push(row),
+ now: () => now,
+ tickIntervalMs: 5,
+ staleThresholdMs: 50,
+ });
+ mgr.start();
+ mgr.deliver("a1", { id: "root", seq: 1, text: "run a long command" });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "running", turnActive: true });
+
+ await session.pushAgentEvent({
+ type: "tool_started",
+ turnId: "root-turn",
+ callId: "long-call",
+ name: "Shell",
+ input: { command: "long-running" },
+ });
+ deliveryPhase = "tool_wait";
+ session.send = vi.fn(async (input: { id: string }) => {
+ deliveryPhase = "next_turn_queued";
+ void session.pushAgentEvent({
+ type: "command_queued",
+ commandId: input.id,
+ reason: "runtime_busy",
+ });
+ return { status: "queued" as const, reason: "runtime_busy" as const, commandId: input.id };
+ });
+ now = 10;
+ mgr.deliver("a1", { id: "next", seq: 2, text: "handle this next" });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(mgr.snapshot().agents.a1.pendingAdmissions).toMatchObject([
+ { commandId: "next", driverAcknowledged: true },
+ ]);
+
+ // The single diagnostics phase is now the queue overlay, not tool_wait.
+ // The independently fenced tool lifecycle must keep the legitimate long
+ // command alive beyond the generic root-silence threshold.
+ now = 60;
+ await vi.advanceTimersByTimeAsync(10);
+ expect(mgr.snapshot().agents.a1.status).toBe("running");
+ expect(mgr.snapshot().agents.a1.pendingAdmissions).toHaveLength(1);
+ expect(session.stop).not.toHaveBeenCalled();
+ expect(rows.some((row) =>
+ row.deliveryPhase === "next_turn_queued"
+ && Array.isArray(row.effects)
+ && (row.effects as string[]).includes("terminate_stalled")
+ )).toBe(false);
+
+ // Finishing the tool removes the blocker and counts as root work. Do not
+ // turn this into a global watchdog bypass: ordinary silence after that
+ // point must still hit the existing threshold exactly once.
+ now = 65;
+ await session.pushAgentEvent({
+ type: "tool_finished",
+ turnId: "root-turn",
+ callId: "long-call",
+ name: "Shell",
+ });
+ deliveryPhase = "working";
+ now = 120;
+ await vi.advanceTimersByTimeAsync(10);
+ expect(mgr.snapshot().agents.a1.status).toBe("stopping");
+ expect(session.stop).toHaveBeenCalledWith({ reason: "stalled", forceAfterMs: 2_000 });
+ expect(rows.filter((row) =>
+ Array.isArray(row.effects) && (row.effects as string[]).includes("terminate_stalled")
+ )).toHaveLength(1);
+
+ await mgr.stopAll();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
for (const mode of ["idle", "busy"] as const) {
it(`${mode} send synchronous throw aborts once and rethrows without another send`, async () => {
const rows: B1TraceRow[] = [];
@@ -3057,8 +3708,8 @@ describe("B1 red gate — exact-once terminal matrix", () => {
const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
mgr.deliver("a1", { seq: 1, text: "first" });
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- if (mode === "idle") session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ if (mode === "idle") await session.fire("runtime_event", { kind: "turn_end" });
session.send = vi.fn(() => {
throw error;
});
@@ -3072,7 +3723,7 @@ describe("B1 red gate — exact-once terminal matrix", () => {
});
}
- it("handshake timeout aborts once before its synthetic exit", async () => {
+ it("handshake timeout aborts once before the session's terminal close", async () => {
vi.useFakeTimers();
try {
const rows: B1TraceRow[] = [];
@@ -3085,6 +3736,7 @@ describe("B1 red gate — exact-once terminal matrix", () => {
mgr.deliver("a1", { seq: 1, text: "active" });
await Promise.resolve();
await vi.advanceTimersByTimeAsync(101);
+ await session.fire("exit", { reason: "requested" });
const aborts = b1SpanRows(rows, "turn_abort");
expect(aborts).toHaveLength(1);
@@ -3115,7 +3767,7 @@ describe("B1 red gate — exact-once terminal matrix", () => {
mgr.start();
mgr.deliver("a1", { seq: 1, text: "active" });
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
now = 100;
await vi.advanceTimersByTimeAsync(10);
now = 200;
@@ -3139,15 +3791,15 @@ describe("B1 red gate — stale owner isolation", () => {
const { mgr } = b1Manager({ sessions: [first, second], trace: (row) => rows.push(row), launchId: "launch-a" });
mgr.deliver("a1", { seq: 1, text: "first" });
await mgr.resetSession("a1", { runtimeConfig: B1_RUNTIME_CONFIG, launchId: "launch-b", rewakePrompt: "reborn" });
- first.fire("exit", { signal: "SIGTERM", reason: "requested" });
+ await first.fire("exit", { signal: "SIGTERM", reason: "requested" });
await Promise.resolve();
const begins = b1SpanRows(rows, "turn_begin");
expect(begins).toHaveLength(2);
const replacementId = begins[1]!.traceTurnId;
rows.length = 0;
- first.fire("runtime_event", { kind: "text", text: "late old output" });
- first.fire("runtime_event", { kind: "turn_end" });
+ await first.fire("runtime_event", { kind: "text", text: "late old output" });
+ await first.fire("runtime_event", { kind: "turn_end" });
first.startRejector!(new Error("HOSTILE_LATE_START_REJECTION_19cf"));
await new Promise((resolve) => setTimeout(resolve, 0));
const staleRows = [...rows];
@@ -3162,14 +3814,185 @@ describe("B1 red gate — stale owner isolation", () => {
).toHaveLength(0);
expect(JSON.stringify(rows)).not.toContain("HOSTILE_LATE_START_REJECTION_19cf");
- second.fire("runtime_event", { kind: "turn_end" });
+ await second.fire("runtime_event", { kind: "turn_end" });
const replacementCloses = b1SpanRows(rows).filter((row) => row.traceTurnId === replacementId && (row.event === "turn_end" || row.event === "turn_abort"));
expect(replacementCloses).toHaveLength(1);
});
});
+describe("AgentProcessManager — defensive owner fences", () => {
+ it("drops stale and superseded public events before state mutation", () => {
+ const logger = stubLogger();
+ const { mgr } = makeManager({ logger });
+ mgr.deliver("a1", { seq: 1, text: "hello" });
+ const internal = mgr as unknown as {
+ activeSpawnState: Map<string, { sessionInstanceId: string | null; superseded: boolean }>;
+ onAgentEvent(agentId: string, event: object, runtimeId: "codex", owner: object): void;
+ };
+ const owner = internal.activeSpawnState.get("a1")!;
+ owner.sessionInstanceId = "test-instance";
+ internal.onAgentEvent("a1", {
+ type: "thinking_delta", turnId: "turn", text: "stale", sequence: 1,
+ sessionInstanceId: "stale-instance", at: Date.now(),
+ }, "codex", owner);
+ owner.superseded = true;
+ (mgr as unknown as { state: { agents: { a1: { execution: { sessionInstanceId: string } } } } })
+ .state.agents.a1.execution.sessionInstanceId = "replacement-instance";
+ internal.onAgentEvent("a1", {
+ type: "thinking_delta", turnId: "turn", text: "superseded", sequence: 2,
+ sessionInstanceId: "test-instance", at: Date.now(),
+ }, "codex", owner);
+ expect(logger.calls.warn.map(([message]) => message)).toEqual([
+ "ignored event from stale session epoch",
+ "ignored event from superseded session owner",
+ ]);
+ });
+
+ it.each(["resolve", "reject"] as const)("ignores a stale send promise %s", async (outcome) => {
+ const session = b1Session([]);
+ const { mgr } = b1Manager({ sessions: [session] });
+ mgr.deliver("a1", { id: "first", seq: 1, text: "first" });
+ await Promise.resolve();
+ let resolve!: (receipt: DeliveryReceipt) => void;
+ let reject!: (error: unknown) => void;
+ session.send = vi.fn(() => new Promise<DeliveryReceipt>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ }));
+ mgr.deliver("a1", { id: "later", seq: 2, text: "later" });
+ const internal = mgr as unknown as { activeSpawnState: Map<string, { torndown: boolean }> };
+ internal.activeSpawnState.get("a1")!.torndown = true;
+ if (outcome === "resolve") {
+ resolve({ status: "rejected", reason: "closed" });
+ } else {
+ reject(new Error("late rejection"));
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(session.stop).not.toHaveBeenCalled();
+ });
+
+ it("rejects a send with no attached session and expires owned admissions", async () => {
+ const { mgr, session } = makeManager();
+ const internal = mgr as unknown as {
+ applyEffect(effect: object): void;
+ activeSpawnState: Map<string, {
+ sessionInstanceId: string | null;
+ pendingDeliverySpans: Map<string, object>;
+ terminationSemantics: string | null;
+ }>;
+ };
+ internal.applyEffect({
+ type: "send", agentId: "a1", message: { id: "missing", seq: 1, text: "missing" }, mode: "busy",
+ });
+ mgr.deliver("a1", { id: "first", seq: 2, text: "first" });
+ session.stop = vi.fn(session.stop);
+ const owner = internal.activeSpawnState.get("a1")!;
+ owner.sessionInstanceId = "test-instance";
+ owner.pendingDeliverySpans.set("expired", { sessionInstanceId: "test-instance", span: null });
+ internal.applyEffect({
+ type: "expire_admission", agentId: "a1", sessionInstanceId: "test-instance", commandIds: ["expired"],
+ });
+ expect(owner.pendingDeliverySpans.has("expired")).toBe(false);
+ expect(owner.terminationSemantics).toBe("killed_stalled");
+ expect(session.stop).toHaveBeenCalledWith({ reason: "stalled", forceAfterMs: 2_000 });
+ });
+
+ it("marks a previous spawn owner superseded before replacing it", () => {
+ const mgr = new AgentProcessManager({
+ driverFor: () => b1PersistentDriver(),
+ baseContextFor: () => ({
+ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "",
+ config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: (() => new Promise<FakeSession>(() => {})) as SessionFactory,
+ });
+ mgr.register("a1");
+ const internal = mgr as unknown as {
+ doSpawn(agentId: string, messages: Array<{ id: string; seq: number; text: string }>, resumeSessionId: null): void;
+ activeSpawnState: Map<string, { superseded: boolean }>;
+ };
+ internal.doSpawn("a1", [{ id: "one", seq: 1, text: "one" }], null);
+ const first = internal.activeSpawnState.get("a1")!;
+ internal.doSpawn("a1", [{ id: "two", seq: 2, text: "two" }], null);
+ expect(first.superseded).toBe(true);
+ });
+
+ it("abandons queued startup delivery when dispatch replaces its owner", async () => {
+ const session = fakeSession();
+ session.send = vi.fn(session.send);
+ const { mgr } = b1Manager({ sessions: [session] });
+ const internal = mgr as unknown as {
+ doSpawn(agentId: string, messages: Array<{ id: string; seq: number; text: string }>, resumeSessionId: null): void;
+ dispatch(event: { type: string }, owner?: object): void;
+ activeSpawnState: Map<string, object>;
+ };
+ const dispatch = internal.dispatch.bind(mgr);
+ vi.spyOn(internal, "dispatch").mockImplementation((event, owner) => {
+ dispatch(event, owner);
+ if (event.type === "spawned") internal.activeSpawnState.delete("a1");
+ });
+ internal.doSpawn("a1", [
+ { id: "first", seq: 1, text: "first" },
+ { id: "queued", seq: 2, text: "queued" },
+ ], null);
+ session.startResolver?.();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(session.send).not.toHaveBeenCalled();
+ });
+
+ it("abandons a queued receipt that settles after owner teardown", async () => {
+ const session = fakeSession();
+ session.stop = vi.fn(session.stop);
+ let resolve!: (receipt: DeliveryReceipt) => void;
+ session.send = vi.fn(() => new Promise<DeliveryReceipt>((done) => { resolve = done; }));
+ const { mgr } = b1Manager({ sessions: [session] });
+ const internal = mgr as unknown as {
+ doSpawn(agentId: string, messages: Array<{ id: string; seq: number; text: string }>, resumeSessionId: null): void;
+ activeSpawnState: Map<string, { torndown: boolean }>;
+ };
+ internal.doSpawn("a1", [
+ { id: "first", seq: 1, text: "first" },
+ { id: "queued", seq: 2, text: "queued" },
+ ], null);
+ session.startResolver?.();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(session.send).toHaveBeenCalledOnce();
+ internal.activeSpawnState.get("a1")!.torndown = true;
+ resolve({ status: "accepted", delivery: "steer", commandId: "queued", turnId: "test-turn" });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(session.stop).not.toHaveBeenCalled();
+ });
+
+ it("audits an unexpected queued-delivery orchestration failure", async () => {
+ const session = fakeSession();
+ const { mgr } = b1Manager({ sessions: [session] });
+ const internal = mgr as unknown as {
+ doSpawn(agentId: string, messages: Array<{ id: string; seq: number; text: string }>, resumeSessionId: null): void;
+ beginPendingDelivery(...args: unknown[]): void;
+ emitErrorAudit(...args: unknown[]): void;
+ };
+ const begin = internal.beginPendingDelivery.bind(mgr);
+ let calls = 0;
+ vi.spyOn(internal, "beginPendingDelivery").mockImplementation((...args) => {
+ if (++calls === 2) throw new Error("queued orchestration failed");
+ begin(...args);
+ });
+ const audit = vi.spyOn(internal, "emitErrorAudit");
+ internal.doSpawn("a1", [
+ { id: "first", seq: 1, text: "first" },
+ { id: "queued", seq: 2, text: "queued" },
+ ], null);
+ session.startResolver?.();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(audit).toHaveBeenCalledWith("a1", "runtime", "send_failed", "Error: queued orchestration failed");
+ });
+});
+
describe("B1 red gate — privacy normalization and coherent time", () => {
- it("drops hostile prompt/error detail, normalizes unknown spawn reason, and preserves the audit callback input", () => {
+ it("drops hostile prompt/error detail, normalizes unknown spawn reason, and preserves the audit callback input", async () => {
const rows: B1TraceRow[] = [];
const onRuntimeSpawnFailed = vi.fn();
const session = b1Session([]);
@@ -3181,8 +4004,8 @@ describe("B1 red gate — privacy normalization and coherent time", () => {
const prompt = "UNIQUE_PROMPT_SECRET_8f26";
const hostileCode = "UNIQUE_RAW_REASON_SECRET_71ac";
mgr.deliver("a1", { seq: 1, text: prompt });
- session.fire("error", { code: hostileCode, message: "UNIQUE_DETAIL_SECRET_5d44" });
- session.fire("exit");
+ await session.fire("error", { code: hostileCode, message: "UNIQUE_DETAIL_SECRET_5d44" });
+ await session.fire("exit");
const serialized = JSON.stringify(rows);
expect(serialized).not.toContain(prompt);
@@ -3213,18 +4036,18 @@ describe("B1 red gate — privacy normalization and coherent time", () => {
mgr.deliver("a1", { seq: 1, text: secrets.prompt });
await Promise.resolve();
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "text", text: secrets.response });
- session.fire("runtime_event", { kind: "thinking", text: secrets.thinking });
- session.fire("runtime_event", {
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "text", text: secrets.response });
+ await session.fire("runtime_event", { kind: "thinking", text: secrets.thinking });
+ await session.fire("runtime_event", {
kind: "tool_call",
name: "Read",
input: { file_path: secrets.tool, nested: { raw: secrets.tool } },
});
- session.fire("runtime_event", { kind: secrets.recentEvent, text: secrets.response });
+ await session.fire("runtime_event", { kind: secrets.recentEvent, text: secrets.response });
mgr.deliver("a1", { seq: 2, text: secrets.send });
- expect(rows.some((row) => Array.isArray(row.effects) && (row.effects as string[]).includes("gated_hold"))).toBe(true);
+ expect(rows.some((row) => Array.isArray(row.effects) && (row.effects as string[]).includes("gated_hold"))).toBe(false);
const serialized = JSON.stringify(rows);
for (const secret of Object.values(secrets)) expect(serialized).not.toContain(secret);
expect(serialized).not.toContain("mid_turn_wake");
@@ -3249,7 +4072,7 @@ describe("B1 red gate — privacy normalization and coherent time", () => {
expect(JSON.stringify(rows)).not.toContain("HOSTILE_TERMINATION_SEMANTIC_03cc");
});
- it("derives every row timeIso from that row's single nowMs sample", () => {
+ it("derives every row timeIso from that row's single nowMs sample", async () => {
let tick = 0;
const rows: B1TraceRow[] = [];
const session = b1Session([]);
@@ -3259,8 +4082,8 @@ describe("B1 red gate — privacy normalization and coherent time", () => {
now: () => Date.UTC(2026, 0, 1) + tick++,
});
mgr.deliver("a1", { seq: 1, text: "time" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- session.fire("runtime_event", { kind: "turn_end" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ await session.fire("runtime_event", { kind: "turn_end" });
expect(rows.length).toBeGreaterThan(0);
for (const row of rows) {
@@ -3268,3 +4091,90 @@ describe("B1 red gate — privacy normalization and coherent time", () => {
}
});
});
+
+describe("Codex root event ownership — subagent completion isolation", () => {
+ it("ignores multiple child completions while the parent keeps working past idle timeout, then hibernates after the true root completion", async () => {
+ vi.useFakeTimers();
+ try {
+ let now = 0;
+ const session = fakeSession();
+ const adapter = createBuiltinAgentDriverRegistry().get("codex").createAdapter();
+ const mgr = new AgentProcessManager({
+ driverFor: () => fakeDriver("codex"),
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: sessionFactoryFor(session),
+ now: () => now,
+ tickIntervalMs: 5,
+ idleTimeoutMs: 50,
+ staleThresholdMs: 1_000,
+ });
+
+ const publishNormalized = async (events: readonly AdapterEvent[]) => {
+ for (const event of events) {
+ if (event.kind === "session_init") {
+ await session.pushAgentEvent({ type: "session_started", backendSessionId: event.sessionId });
+ } else if (event.kind === "thinking") {
+ await session.pushAgentEvent({ type: "thinking_delta", turnId: "test-turn", text: event.text });
+ } else if (event.kind === "tool_call") {
+ await session.pushAgentEvent({ type: "tool_started", turnId: "test-turn", name: event.name, input: event.input as never });
+ } else if (event.kind === "tool_output") {
+ await session.pushAgentEvent({ type: "tool_finished", turnId: "test-turn", name: event.name });
+ } else if (event.kind === "turn_end") {
+ await session.pushAgentEvent({
+ type: "turn_completed",
+ turnId: "test-turn",
+ commandIds: ["root-command"],
+ result: { outcome: "success", backendSessionId: event.sessionId ?? "root-thread" },
+ });
+ }
+ }
+ };
+ const notify = (method: string, params: unknown) => JSON.stringify({ jsonrpc: "2.0", method, params });
+
+ mgr.start();
+ mgr.register("a1");
+ mgr.deliver("a1", { id: "root-command", text: "work" });
+ session.startResolver?.();
+ await Promise.resolve();
+ await publishNormalized(adapter.normalizeLine(JSON.stringify({ jsonrpc: "2.0", id: 2, result: { thread: { id: "root-thread" } } })));
+ await publishNormalized(adapter.normalizeLine(notify("turn/started", {
+ threadId: "root-thread",
+ turn: { id: "root-turn", status: "inProgress" },
+ })));
+
+ for (let child = 1; child <= 3; child += 1) {
+ const events = adapter.normalizeLine(notify("turn/completed", {
+ threadId: `child-thread-${child}`,
+ turn: { id: `child-turn-${child}`, status: "completed" },
+ }));
+ expect(events).toEqual([]);
+ await publishNormalized(events);
+ now += 40;
+ await publishNormalized(adapter.normalizeLine(notify(child % 2 === 0 ? "item/completed" : "item/started", {
+ threadId: "root-thread",
+ turnId: "root-turn",
+ item: { type: "commandExecution" },
+ })));
+ await vi.advanceTimersByTimeAsync(40);
+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "running", turnActive: true });
+ }
+
+ await publishNormalized(adapter.normalizeLine(notify("turn/completed", {
+ threadId: "root-thread",
+ turn: { id: "root-turn", status: "completed" },
+ })));
+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "running", turnActive: false });
+ now += 60;
+ await vi.advanceTimersByTimeAsync(60);
+ expect(mgr.snapshot().agents.a1.status).toBe("stopping");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index ede9faaee..2c76cf8b5 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -1,15 +1,3 @@
-/**
- * Agent process manager — thin side-effect executor.
- *
- * This is the impure half: it owns the mutable `ManagerState`, drives the pure
- * `reduceManager` policy with real events, and applies the emitted effects
- * against real runtime sessions (spawn / send / stop) plus a tick timer for
- * stall detection. It is intentionally thin — all decisions live in the policy;
- * this layer only does I/O.
- *
- * A host wires it up with a `SessionFactory` (how to build a runtime session for
- * an agent) and feeds it inbound messages via `deliver()`.
- */
import {
reduceManager,
createInitialManagerState,
@@ -17,41 +5,31 @@ import {
type ManagerState,
type ManagerEvent,
type ManagerEffect,
- type AgentRuntimeCaps,
type AgentMsg,
type AgentState,
type AgentStatus,
isActivelyWorking,
} from "./managerPolicy.js";
-import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
-import { busyDeliveryModeOf, supportsStdinNotificationOf } from "../types.js";
-import { resolveLaunchFieldsOrDefault, type RuntimeConfig } from "../runtimeConfig.js";
-import { createChildProcessRuntimeSession, type ChildProcessRuntimeSession } from "../runtime/runtimeSession.js";
-import { SESSION_STOP_GRACE_MS, killProcessTree } from "../runtime/killTree.js";
+import type {
+ AgentEvent,
+ AgentSession,
+ AgentSessionSnapshot,
+ AgentSessionResult,
+ BuiltinBackendId,
+ BuiltinBackendSpecs,
+ DeliveryReceipt,
+} from "@alook/agent-driver";
+import type { HostLaunchContext } from "./hostContext.js";
+import { runtimeModelName, type RuntimeConfig } from "../runtimeConfig.js";
import { scrubRuntimeErrorDiagnosticText } from "../runtime/errorDiagnostics.js";
-import { SdkManagedSession } from "../runtime/sdkManagedSession.js";
-import { DEFAULT_CLI_CONFIG } from "../drivers/cliTransport.js";
+import { buildCliSystemPrompt } from "../drivers/systemPrompt.js";
import { createLogger, type Logger } from "../logger.js";
import { nowLocalISO } from "../util/localTime.js";
import { randomUUID } from "node:crypto";
-
-/**
- * Derived activity state reported up the control plane — NOT a raw passthrough
- * of `AgentState.status` (see `deriveActivity` below). Mirrors
- * `@alook/shared`'s `AgentActivityState`, inlined here since this is
- * daemon-internal.
- */
+const SESSION_STOP_GRACE_MS = 2_000;
export type AgentActivityState = "idle" | "starting" | "running" | "stopping";
-
-/** Minimal shape the executor needs from a runtime session. */
-export interface ManagedSession {
- on(event: string, cb: (...args: unknown[]) => void): void;
- start(input: { text: string; sessionId?: string }): Promise<unknown>;
- send(input: { text: string; mode: "busy" | "idle" }): unknown;
- stop(opts?: { reason?: string; forceAfterMs?: number }): Promise<void> | void;
- readonly currentSessionId: string | null;
-}
-
+export type DaemonAgentSession = AgentSession<BuiltinBackendSpecs, BuiltinBackendId>;
+type ManagedEvent = AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>;
type TraceTerminationCause = "runtime_error" | "killed_stalled" | "other";
type TraceSpawnFailureReason = "ENOENT" | "handshake_timeout" | "pre_handshake_exit" | "spawn_threw" | "other";
type TraceTerminationSemantics = "killed_stalled" | "idle_stop" | "force_exit" | "other";
@@ -70,7 +48,6 @@ type TraceAbortCause =
| "terminate_stalled"
| "force_exit"
| "other";
-
interface ActiveTurnSpan {
traceTurnId: string;
daemonTurnOrdinal: number;
@@ -78,32 +55,36 @@ interface ActiveTurnSpan {
turnOrdinal: number;
launchIdSnapshot: string | null;
}
-
+interface PendingDeliveryTrace {
+ sessionInstanceId: string;
+ span: ActiveTurnSpan | null;
+ mode: "busy" | "idle";
+ driverObserved: boolean;
+}
interface ActiveSpawnState {
agentId: string;
- session: ManagedSession;
+ session: DaemonAgentSession | null;
+ sessionInstanceId: string | null;
hasEstablished: boolean;
hasReportedSpawnFailure: boolean;
suppressExitLog: boolean;
handshakeTimer: ReturnType<typeof setTimeout> | null;
torndown: boolean;
superseded: boolean;
- pid: number | null;
spawnFailureReason: string | null;
terminationSemantics: string | null;
spawnOrdinal: number;
launchIdSnapshot: string | null;
nextTurnOrdinal: number;
activeSpan: ActiveTurnSpan | null;
+ pendingDeliverySpans: Map<string, PendingDeliveryTrace>;
}
-
interface TraceRecordBase {
agentId: string;
effects: string[];
nowMs: number;
timeIso: string;
}
-
interface TraceSpanMetadata {
traceTurnId: string;
daemonTurnOrdinal: number;
@@ -111,11 +92,11 @@ interface TraceSpanMetadata {
turnOrdinal: number;
launchIdSnapshot: string | null;
}
-
interface FsmTraceRecord extends TraceRecordBase, Partial<TraceSpanMetadata> {
recordKind: "fsm";
- event: ManagerEvent["type"];
+ event: ManagerEvent["type"] | "root_work" | "turn_end";
status: AgentStatus;
+ turnId: string | null;
turnActive: boolean;
inbox: number;
lastDeliverAt: number | null;
@@ -124,7 +105,16 @@ interface FsmTraceRecord extends TraceRecordBase, Partial<TraceSpanMetadata> {
resetting: boolean;
resettingSince: number | null;
stoppingSince: number | null;
- apmPhase: AgentState["apm"]["phase"];
+ deliveryPhase: AgentSessionSnapshot["diagnostics"]["deliveryPhase"];
+ physicalOpenCount?: number;
+ turnCount?: number;
+ commandAdmissionCount?: number;
+ commandAdmissionLatencyTotalMs?: number;
+ queueDwellCount?: number;
+ queueDwellTotalMs?: number;
+ sseReconnectCount?: number;
+ resumeOutcome?: "not_requested" | "pending" | "resumed" | "reset_required" | "failed";
+ terminalOwnerKind?: "transport_request" | "vendor_message" | "prompt_invocation" | "lane_generation";
sinceProgressMs: number;
sinceDeliverMs: number | null;
sinceStoppingMs: number | null;
@@ -136,7 +126,6 @@ interface FsmTraceRecord extends TraceRecordBase, Partial<TraceSpanMetadata> {
spawnFailureReason?: TraceSpawnFailureReason;
terminationSemantics?: TraceTerminationSemantics;
}
-
type TurnSpanTraceRecord = TraceRecordBase &
TraceSpanMetadata &
(
@@ -149,14 +138,10 @@ type TurnSpanTraceRecord = TraceRecordBase &
}
| { recordKind: "turn_span"; event: "turn_abort"; abortCause: TraceAbortCause }
);
-
-/** Metadata-only local trace row with an explicit privacy allowlist. */
export type ManagerTraceRecord = FsmTraceRecord | TurnSpanTraceRecord;
-
function normalizeTerminationCause(value: unknown): TraceTerminationCause {
return value === "runtime_error" || value === "killed_stalled" ? value : "other";
}
-
function normalizeAbortCause(value: unknown): TraceAbortCause {
switch (value) {
case "start_threw":
@@ -177,7 +162,6 @@ function normalizeAbortCause(value: unknown): TraceAbortCause {
return "other";
}
}
-
function normalizeSpawnFailureReason(value: unknown): TraceSpawnFailureReason {
switch (value) {
case "ENOENT":
@@ -189,7 +173,6 @@ function normalizeSpawnFailureReason(value: unknown): TraceSpawnFailureReason {
return "other";
}
}
-
function normalizeTerminationSemantics(value: unknown): TraceTerminationSemantics {
switch (value) {
case "killed_stalled":
@@ -200,90 +183,28 @@ function normalizeTerminationSemantics(value: unknown): TraceTerminationSemantic
return "other";
}
}
-
-/**
- * How the host builds a session for an agent launch. Given the agent id, the
- * driver, and the launch context (prompt + resume id filled in), return a
- * session the executor will drive.
- */
export type SessionFactory = (args: {
agentId: string;
- driver: Driver;
- ctx: LaunchContext;
-}) => ManagedSession;
-
+ ctx: HostLaunchContext;
+ runtimeConfig: RuntimeConfig;
+}) => DaemonAgentSession | Promise<DaemonAgentSession>;
export interface ManagerRuntimeOpts {
- /**
- * Resolve a driver for an agent. The optional `runtimeConfig` is supplied
- * whenever the manager knows it (i.e. after `register` with the server-pushed
- * config) so callers can pick the right runtime; tests may omit it.
- */
- driverFor: (agentId: string, runtimeConfig?: RuntimeConfig) => Driver;
- baseContextFor: (agentId: string) => Omit<LaunchContext, "prompt" | "config" | "standingPrompt"> & {
+ driverFor: (agentId: string, runtimeConfig?: RuntimeConfig) => { readonly id: BuiltinBackendId };
+ baseContextFor: (agentId: string) => Omit<HostLaunchContext, "prompt" | "config" | "standingPrompt"> & {
standingPrompt?: string;
- config?: LaunchContext["config"];
+ config?: HostLaunchContext["config"];
};
sessionFactory?: SessionFactory;
- /**
- * Zero-trust credential handoff for real (child-process) spawns. Required when
- * NOT using a `sessionFactory` — `prepareCliTransport` refuses to launch a CLI
- * runtime without it (no plaintext fallback). Threaded into each LaunchContext.
- */
- credentialProxy?: LaunchContext["credentialProxy"];
- /**
- * Builds the `SdkDriverDeps` for an in-process SDK driver's `createSession`
- * (see `types.ts`). Required when NOT using a `sessionFactory` AND a
- * resolved driver declares `createSession` (Pi today) — mirrors the
- * `credentialProxy` requirement for child-process drivers. Called once per
- * spawn with the same base `ctx` a `ChildProcessRuntimeSession` would get.
- */
- sdkDriverDepsFor?: (ctx: LaunchContext) => SdkDriverDeps;
+ credentialProxy?: HostLaunchContext["credentialProxy"];
staleThresholdMs?: number;
- /** Idle hibernation timeout (ms): stop a persistent process idle this long. */
idleTimeoutMs?: number;
- /** Reset-stuck reconcile threshold (ms): `resetting` stuck this long ⇒ escalate. */
resetStuckThresholdMs?: number;
- /** Stopping-stuck escalation threshold (ms): `stopping` this long (no exit came) ⇒ force_exit. */
stoppingStuckThresholdMs?: number;
- /**
- * Handshake watchdog (ms): a spawned session that never emits its first
- * `runtime_event` (the handshake) within this window is treated as a
- * pre-establishment failure — the process is stopped, an `error` audit row
- * is emitted, and the FSM is returned to idle. Catches the case a bad model
- * makes the CLI HANG (no exit, no stderr, no stdout) — otherwise invisible
- * and unrecoverable (the `onTick` stall watchdog excludes an empty-inbox
- * gated agent). Defaults to 60s: a healthy cold start handshakes in <10s.
- */
handshakeTimeoutMs?: number;
tickIntervalMs?: number;
- /** Injectable clock (tests). Defaults to Date.now. */
now?: () => number;
- /**
- * Notified when an agent's runtime session id is first learned (from a
- * `session_init` event). The router relays this to the server as
- * `reportAgentSession` so the server can correlate + resume.
- */
onAgentSession?: (info: { agentId: string; sessionId: string; launchId: string }) => void;
- /**
- * Notified whenever an agent's DERIVED activity (per `deriveActivity`)
- * changes — not on every raw FSM transition. See the Design Overview in
- * plans/community-bot-status-telemetry.md.
- */
onAgentActivity?: (info: { agentId: string; state: AgentActivityState }) => void;
- /**
- * Notified whenever a runtime `thinking` or `tool_call` event lands. Wired
- * in `createDaemon` to send a `bot_audit_event` frame through the WS
- * control channel. Tool calls flow through `extractToolAudit`, which
- * canonicalizes the tool name to lowercase (`Bash` → `bash`, codex
- * `shell` → `bash`, codex `file_change` → `edit`, etc.), picks a
- * `target` field driver-agnostically (file path / shell command /
- * pattern / url / mcp name), and suppresses any bash-family call whose
- * resolved command is `alook <sub>` — the credential-proxy
- * `cli_invocation` sighting is authoritative for those.
- *
- * `thinking` payloads carry truncated `text` + original `chars`; the audit
- * log does not record raw tool input beyond the optional `target`.
- */
onBotAuditEvent?: (
agentId: string,
event:
@@ -300,136 +221,25 @@ export interface ManagerRuntimeOpts {
},
context: { sessionId: string | null; launchId: string | null }
) => void;
- /**
- * Notified when the daemon itself terminates an agent (idle hibernation or
- * stall-recovery) — NOT for server-sent `agent:stop`, which the router
- * already tracks. Wired in `createDaemon` to `AgentRouter.markLocallyStopped`
- * so `ready.runningAgents` stays aligned with what's actually live.
- */
onAgentLocallyStopped?: (info: { agentId: string; reason: "stop" | "terminate_stalled" }) => void;
- /**
- * Observability-only tap for complete child-process stdout lines. The host
- * owns persistence; the manager only adds agent identity before the shared
- * runtime session parses the line. SDK sessions do not emit through it.
- */
onRuntimeRawLine?: (agentId: string, line: string) => void;
- /**
- * Pure-observability FSM and turn-lifecycle trace. Each agent-scoped
- * `dispatch` emits the post-reduce key fields + effect kinds; trace-only
- * turn_begin/end/abort rows add lifecycle boundaries without entering the
- * reducer. Wired in `createDaemon` when `ALOOK_FSM_TRACE` is set. No behavior
- * change; omit ⇒ no-op.
- */
onFsmTransition?: (rec: ManagerTraceRecord) => void;
- /**
- * Optional context-timeline recorder. When provided, the manager logs each
- * spawn as a "running" row, fills in the session id on session_init, and closes
- * the row on turn_end / exit — a pure DAILY LOG, no steering. It also supplies
- * the resume session id for an agent's next launch (latest finished session in
- * that agent's own timeline). Omitted ⇒ no logging, in-memory resume only.
- */
timeline?: TimelineRecorder;
- /**
- * Appended once to the coalesced wake prompt (after dedup). Use for a
- * one-shot instruction like "Use `alook inbox pull` to read your messages."
- */
wakePromptFooter?: string;
- /**
- * When true, prepend a `[<local-tz ISO>]` timestamp to every prompt handed
- * to the runtime driver (both spawn's initial prompt and mid-turn steer
- * sends). Stamped inside `withFooter` — as close to "the moment the agent
- * actually sees this text" as we can get — so the number reflects the real
- * arrival wall-clock, not an earlier layer's timestamp. Off in tests so
- * exact-string assertions on send/prompt stay stable; enabled in production
- * via `createDaemon`.
- */
stampWakePromptTime?: boolean;
- /**
- * Notified when a spawn fails BEFORE the runtime emits its handshake
- * `runtime_event` (pre-establishment error). The host may use definitive
- * executable errors to update global runtime health, but transient failures
- * such as `handshake_timeout` must remain scoped to this launch so a later
- * wake can retry.
- *
- * `reason` is a short code like `"ENOENT"` or `"pre_handshake_exit"`.
- */
onRuntimeSpawnFailed?: (runtimeId: string, reason: string) => void;
- /**
- * Notified once per session when it emits its first post-handshake
- * `runtime_event`. Typically wired to `AgentRouter.markRuntimeHealthy` so
- * a runtime that was flagged unhealthy self-heals after the user fixes
- * their install (or after a genuine transient failure).
- */
onRuntimeSessionEstablished?: (runtimeId: string) => void;
- /** Defaults to `createLogger({ header: "@alook/daemon:manager" })`. */
logger?: Logger;
}
-
-/**
- * Lifecycle sink the manager calls to record turns + look up resume. Kept as an
- * injected interface so managerRuntime stays fs-free and unit-testable; the
- * daemon backs it with the `src/timeline` module over the agent's workdir.
- */
export interface TimelineRecorder {
- /**
- * Record the runtime session id (from session_init). The recorder bakes it into
- * the entry opened by the agent's next inbox pull (which happens after
- * session_init), so the row carries the right session id.
- */
setSession(agentId: string, sessionId: string): void;
- /**
- * Append a piece of the agent's response (a runtime `text` event) to the
- * agent's latest entry's `agent_responses` — the "what I said this turn" data
- * that makes the timeline usable as memory. The entry itself is opened on the
- * DATA plane (inbox pull); the manager only accumulates onto the latest row.
- */
appendResponseToLatest(agentId: string, text: string): void;
- /** Latest session id for this agent (resume target), or null. */
resumeSessionId(agentId: string, provider: string | null): string | null;
- /**
- * Reset: the caller asked the daemon to forget this agent's prior session so
- * the next spawn starts fresh. Recorder appends a `system` barrier row —
- * `reset_session` (owner) or `nap` (agent self-reset, default
- * `reset_session`) — visible to both the resume walker (returns null on the
- * barrier — every turn at or before it becomes invisible to
- * `resumeSessionId`) and the agent's own history read (so the agent sees it
- * in-line with turns). Kill happens BEFORE the barrier is written (see
- * `AgentProcessManager.resetSession`), so no race — no `forgot_session_id`
- * needed. Safe to call on an unknown agentId.
- */
forgetSession(agentId: string, barrierType?: "reset_session" | "nap"): void;
}
-
-/** Max UTF-8 byte budget for `thinking` text in the audit log. */
const THINKING_MAX_BYTES = 4096;
-
-/** Max length of a runtime-stderr line the daemon logs verbatim (with an ellipsis when cut). */
-const STDERR_LOG_MAX_LEN = 2000;
-
-/** Max length of an `error` audit row's message (schema caps at 2048; leave headroom). */
const AUDIT_ERROR_MESSAGE_MAX_LEN = 2000;
-
-/**
- * Max UTF-16 code units for a tool_call's `target` field. The wire schema
- * caps `target` at 240 (see `AuditLogToolCallPayloadSchema`) and Zod's
- * `.max()` measures UTF-16 length — the extractor truncates at 200 to keep
- * 40 units of headroom for any future producer that stamps a suffix before
- * wire validation. Truncating on codepoints would let an emoji-heavy target
- * exceed 240 UTF-16 units and get rejected at the wire.
- */
const MAX_TARGET_CODE_UNITS = 200;
-
-/**
- * Canonicalize a driver-raw tool name to the lowercase tag the audit log
- * stores. The map is case-insensitive on the input: `Bash|bash|BASH → bash`,
- * codex's `shell → bash` and `file_change → edit`, `MultiEdit → edit`
- * (intentional semantic collapse — every MultiEdit acts on one file),
- * `NotebookEdit → notebook_edit`, `LS → ls`, `WebSearch → web_search`,
- * `WebFetch → web_fetch`, `TodoWrite → todo_write`. Anything else falls
- * through to its lowercased original (e.g. `mcp_search` stays `mcp_search`,
- * an unknown `Frobnicate` becomes `frobnicate`) so new drivers don't need
- * this table updated to surface.
- */
export function canonicalToolName(rawName: string): string {
const lower = rawName.toLowerCase();
switch (lower) {
@@ -468,9 +278,7 @@ export function canonicalToolName(rawName: string): string {
return lower;
}
}
-
type ToolClass = "shell" | "file_target" | "pattern" | "fallthrough";
-
function classify(canonicalName: string): ToolClass {
switch (canonicalName) {
case "bash":
@@ -489,19 +297,6 @@ function classify(canonicalName: string): ToolClass {
return "fallthrough";
}
}
-
-/**
- * Coerce a runtime-emitted `input` to a plain record for field-picking.
- * Non-object inputs (null, undefined, array, number, boolean) become
- * `undefined`. As a special case, string inputs get a single `JSON.parse`
- * attempt: copilot's OpenAI-style tool-call `arguments` reaches this layer
- * as a stringified JSON blob when the driver's `arguments ?? parameters ??
- * input ?? {}` fallback picks the raw string up unparsed. If the parse
- * succeeds and yields a record, that record is returned; on any failure
- * (non-JSON string, JSON that decodes to a non-object) we return
- * `undefined` — never throw. One parse attempt per event, so an adversarial
- * huge string is bounded by the runtime's own event size limits.
- */
function coerceInputRecord(input: unknown): Record<string, unknown> | undefined {
if (typeof input === "string") {
try {
@@ -517,16 +312,6 @@ function coerceInputRecord(input: unknown): Record<string, unknown> | undefined
if (!input || typeof input !== "object" || Array.isArray(input)) return undefined;
return input as Record<string, unknown>;
}
-
-/**
- * Extract a raw command string from a shell-class tool_call's `input`. Every
- * driver reduces to a root `input.command` after its normalizer runs
- * (Anthropic, cursor, kimi, opencode, pi, gemini, copilot, and codex — the
- * codex normalizer unwraps `params.item`, so `command` is already flat).
- * String or array (`["bash", "-lc", "..."]` from codex) — arrays get
- * space-joined, keeping the honest form the runtime saw. Returns
- * `undefined` when no plausible command is present.
- */
export function pickCommandString(input: unknown): string | undefined {
const rec = coerceInputRecord(input);
if (!rec) return undefined;
@@ -534,7 +319,6 @@ export function pickCommandString(input: unknown): string | undefined {
if (Array.isArray(rec.command)) return rec.command.filter((v) => typeof v === "string").join(" ");
return undefined;
}
-
function pickFileTarget(input: unknown): string | undefined {
const rec = coerceInputRecord(input);
if (!rec) return undefined;
@@ -543,7 +327,6 @@ function pickFileTarget(input: unknown): string | undefined {
if (typeof rec.notebook_path === "string") return rec.notebook_path;
return undefined;
}
-
function pickPatternTarget(input: unknown): string | undefined {
const rec = coerceInputRecord(input);
if (!rec) return undefined;
@@ -552,7 +335,6 @@ function pickPatternTarget(input: unknown): string | undefined {
if (typeof rec.path === "string") return rec.path;
return undefined;
}
-
function pickFallthroughTarget(input: unknown): string | undefined {
const rec = coerceInputRecord(input);
if (!rec) return undefined;
@@ -562,37 +344,14 @@ function pickFallthroughTarget(input: unknown): string | undefined {
if (typeof rec.name === "string") return rec.name;
return undefined;
}
-
-/**
- * A bash-family tool_call is the daemon proxy's shadow when — and only when
- * — the resolved command is `alook` or `alook <sub …>`. In that case the
- * credential proxy emits an authoritative `cli_invocation` audit row and
- * the tool_call would duplicate it. Any other command (rm, sed, git, pnpm,
- * echo, `bash -lc "alook …"` — the outer shell is real work) is user
- * intent and must surface.
- */
-// The agent invokes the CLI two ways, both authoritative-`cli_invocation`
-// sources the tool_call must suppress:
-// - the injected env var: `$ALOOK_CLI …` / `${ALOOK_CLI} …` (the form the
-// system prompt now teaches — an absolute path that dodges PATH; see
-// spawnEnv `<PREFIX>_CLI` / systemPrompt), and
-// - the bare name `alook …` (legacy / any agent that still types it).
-// `<PREFIX>_CLI` is `${DEFAULT_CLI_CONFIG.envPrefix}_CLI` = `ALOOK_CLI`.
-const ALOOK_CLI_ENV_VAR = `${DEFAULT_CLI_CONFIG.envPrefix}_CLI`;
+const ALOOK_CLI_ENV_VAR = "ALOOK_CLI";
const ALOOK_SHELL_INVOCATION_RE = new RegExp(
- `^(?:${DEFAULT_CLI_CONFIG.cliName}|\\$\\{?${ALOOK_CLI_ENV_VAR}\\}?)(\\s|$)`,
+ `^(?:alook|\\$\\{?${ALOOK_CLI_ENV_VAR}\\}?)(\\s|$)`,
);
-
export function isAlookShellInvocation(command: string | undefined): boolean {
if (!command) return false;
return ALOOK_SHELL_INVOCATION_RE.test(command.trimStart());
}
-
-/**
- * Truncate a target to at most `MAX_TARGET_CODE_UNITS` UTF-16 code units,
- * appending `…` when cut. Walks back one unit if the boundary lands on a
- * high surrogate (never emits a lone surrogate).
- */
export function truncateTargetToCodeUnits(s: string): string {
if (s.length <= MAX_TARGET_CODE_UNITS) return s;
let end = MAX_TARGET_CODE_UNITS - 1;
@@ -600,20 +359,6 @@ export function truncateTargetToCodeUnits(s: string): string {
if (cu >= 0xd800 && cu <= 0xdbff) end -= 1;
return s.slice(0, end) + "…";
}
-
-/**
- * Driver-agnostic tool_call extractor. Given a runtime-raw `(name, input)`
- * pair, returns the canonical lowercase `name`, an optional short `target`
- * summary (file path / shell command / pattern / url / mcp name), and a
- * `suppressed` flag that's true for bash-family calls whose command is
- * `alook <sub>` (the credential proxy's `cli_invocation` is authoritative
- * for those).
- *
- * The returned object contains ONLY `{name, target?, suppressed}`. Raw
- * `input` is NEVER returned. Callers must destructure — never spread — so
- * a future extractor field addition cannot accidentally leak sensitive tool
- * args onto the wire.
- */
export function extractToolAudit(
rawName: string,
rawInput: unknown
@@ -640,83 +385,32 @@ export function extractToolAudit(
}
return { name, target: truncateTargetToCodeUnits(target), suppressed: false };
}
-
-/**
- * Truncate a `thinking` string to at most `THINKING_MAX_BYTES` UTF-8 bytes
- * without splitting a multi-byte sequence. Exported for tests. Callers get the
- * (possibly truncated) text plus the original char count so the UI can render
- * "+N more chars" without re-fetching.
- */
export function truncateThinking(
text: string
): { text: string; truncated: boolean; chars: number } {
- // Count codepoints (user-facing characters), not UTF-16 code units — an
- // emoji-heavy string reports one "char" per emoji, matching the "Show N
- // more characters" affordance in the UI.
const chars = [...text].length;
const buf = Buffer.from(text, "utf8");
if (buf.byteLength <= THINKING_MAX_BYTES) {
return { text, truncated: false, chars };
}
- // Walk back from the boundary to a safe UTF-8 char break. Continuation
- // bytes are `10xxxxxx` (0x80-0xBF); slice must land BEFORE one.
let end = THINKING_MAX_BYTES;
while (end > 0 && (buf[end] & 0xc0) === 0x80) end--;
const truncatedText = buf.subarray(0, end).toString("utf8");
return { text: truncatedText, truncated: true, chars };
}
-
export class AgentProcessManager {
private state: ManagerState;
- private readonly sessions = new Map<string, ManagedSession>();
- /** agentId → server-pushed RuntimeConfig (from agent:wake). */
+ private readonly sessions = new Map<string, DaemonAgentSession>();
private readonly runtimeConfigs = new Map<string, RuntimeConfig>();
- /** agentId → resume sessionId pushed by the server (from agent:wake). */
private readonly resumeSessions = new Map<string, string>();
- /** agentId → launchId from the latest agent:wake (for session correlation). */
private readonly launchIds = new Map<string, string>();
- /** agentId → live runtime sessionId (learned from session_init), for resync. */
private readonly liveSessions = new Map<string, string>();
- /**
- * agentId → accumulated `thinking` text for the current reasoning block.
- * Several drivers (codex, pi, copilot) stream thinking token-by-token; we
- * buffer the deltas and flush ONE audit row at the next non-thinking event /
- * turn boundary / exit, instead of a D1 insert+prune per token. Block-based
- * drivers (claude, cursor) emit one full-text event → one row, unchanged.
- */
private readonly thinkingBuffers = new Map<string, string>();
- /**
- * agentId → the current spawn's per-session end-tracking and trace ownership,
- * shared
- * between `doSpawn`'s closure (turn_end / exit) and `applyEffect` (stop /
- * terminate_stalled) — see `logSessionEnded`'s `suppressExitLog` handling.
- */
private readonly activeSpawnState = new Map<string, ActiveSpawnState>();
private readonly traceProcessNonce = randomUUID();
private nextSpawnOrdinal = 1;
private nextDaemonTurnOrdinal = 1;
- /**
- * agentId → why the current turn ended NON-cleanly, buffered until the
- * trailing `turn_end` reads+clears it. Two symmetric marker points feed it
- * (Cecilia 架构#352 / Claudette #353 — key on CAUSE, never on bare `status`,
- * so a voluntary idle-timeout `stop` that also flips `stopping` is never
- * misread as a crash):
- * - `runtime_error`: a runtime `error` event mid-turn, set ONLY in the
- * `!sessionSuperseded` branch (an intentional reset/nap death-rattle never
- * marks). Free-text `detail` stays on the existing policy/audit path and
- * is never serialized to the local trace.
- * - `killed_stalled`: the `terminate_stalled` effect (the stall watchdog
- * SIGKILLing a wedged turn — Blair's actual case). By construction, no
- * dependence on whether the runtime emits a trailing error rattle.
- * At the trailing `turn_end` this becomes `endReason:"errored"` (the binary
- * can-rewake judgement) + `terminationCause` (the cause, for B2 policy
- * branching). A kill's marker is authoritative: if a `killed_stalled` marker
- * is present, a following `runtime_error` rattle must NOT downgrade it (the
- * kill is the real cause; the rattle is its side effect). Cleared on the
- * `exit` teardown too, so a hard exit with no trailing turn_end can't leak a
- * stale marker onto the next turn (B1 3a). See
- * plans/daemon-runtime-error-rewake.md.
- */
+ private nextDeliveryOrdinal = 1;
private readonly nonCleanEndMarker = new Map<
string,
{ cause: "runtime_error" | "killed_stalled"; detail?: string }
@@ -727,7 +421,6 @@ export class AgentProcessManager {
| "sessionFactory"
| "now"
| "credentialProxy"
- | "sdkDriverDepsFor"
| "onAgentSession"
| "onAgentActivity"
| "onBotAuditEvent"
@@ -746,7 +439,6 @@ export class AgentProcessManager {
| "sessionFactory"
| "now"
| "credentialProxy"
- | "sdkDriverDepsFor"
| "onAgentSession"
| "onAgentActivity"
| "onBotAuditEvent"
@@ -762,7 +454,6 @@ export class AgentProcessManager {
private tickTimer: ReturnType<typeof setInterval> | null = null;
private readonly now: () => number;
private readonly log: Logger;
-
constructor(opts: ManagerRuntimeOpts) {
this.opts = {
tickIntervalMs: 5_000,
@@ -783,122 +474,47 @@ export class AgentProcessManager {
this.opts.stoppingStuckThresholdMs,
);
}
-
- /**
- * Register an agent (idempotent) so it can receive messages. `launch` carries
- * the server-pushed RuntimeConfig (and optional resume sessionId) from
- * `agent:wake`; it's remembered and merged into the LaunchContext at spawn.
- */
register(agentId: string, launch?: { runtimeConfig?: RuntimeConfig; sessionId?: string; launchId?: string }): void {
if (launch?.runtimeConfig) this.runtimeConfigs.set(agentId, launch.runtimeConfig);
if (launch?.sessionId) this.resumeSessions.set(agentId, launch.sessionId);
if (launch?.launchId) this.launchIds.set(agentId, launch.launchId);
- const driver = this.opts.driverFor(agentId, this.runtimeConfigs.get(agentId));
- const caps: AgentRuntimeCaps = {
- lifecycleKind: driver.lifecycle.kind,
- supportsStdinNotification: supportsStdinNotificationOf(driver.lifecycle),
- busyDeliveryMode: busyDeliveryModeOf(driver.lifecycle),
- };
- this.dispatch({ type: "register", agentId, caps });
+ this.dispatch({ type: "register", agentId });
}
-
- /**
- * Inbound message for an agent → drives spawn/steer/queue per policy.
- * Returns whether the wake produced any executable effect (spawn/send/
- * gated_hold). `false` means the message was only coalesced into the inbox
- * with nothing dispatched toward a process — benign for the queue-and-drain
- * cases (starting/stopping/reset-window/per-turn), pathological for a
- * deaf-but-`running` agent that will never drain. The router uses this for a
- * daemon-local honest-ack diagnostic; it does NOT change the wire ack status.
- * See plans/daemon-fsm-desync.md batch B.
- */
deliver(agentId: string, message: AgentMsg): boolean {
- const effects = this.dispatch({ type: "wake", agentId, message, nowMs: this.now() });
+ const normalized = message.id
+ ? message
+ : {
+ ...message,
+ id: message.seq !== undefined
+ ? `${agentId}:source:${message.seq}`
+ : `${agentId}:synthetic:${this.nextDeliveryOrdinal++}`,
+ };
+ const effects = this.dispatch({ type: "wake", agentId, message: normalized, nowMs: this.now() });
return effects.length > 0;
}
-
- /**
- * Clear every cached source that could seed the next spawn's
- * `resumeSessionId`, append the timeline barrier, and null the FSM
- * sessionId. Does NOT touch the running process (existing contract) and
- * does NOT block subsequent wakes — see `resetSession` for the full
- * orchestration. Caller: `resetSession` (below), after `register` and
- * before `markResetting`.
- */
forgetSession(agentId: string, barrierType: "reset_session" | "nap" = "reset_session"): void {
this.resumeSessions.delete(agentId);
this.liveSessions.delete(agentId);
this.dispatch({ type: "reset_session", agentId });
this.opts.timeline?.forgetSession(agentId, barrierType);
}
-
- /**
- * Append a synthetic rewake message to the agent's FSM inbox WITHOUT
- * emitting any effect. Called by `resetSession`'s live-branch: `stop()` is
- * about to kill the ManagedSession, so a `send` toward it (via `deliver`
- * → `onWake` → `send` effect on a persistent+direct agent) would be
- * silently dropped. The queued message rides the `onExit` drain-then-
- * spawn path instead.
- */
enqueueRewake(agentId: string, message: AgentMsg): void {
this.dispatch({ type: "rewake_after_reset", agentId, message });
}
-
- /**
- * Mark the agent as being in a reset window (`resetting = true`). Every
- * subsequent non-idle wake queues to inbox instead of steering the dying
- * session or spawning a duplicate — see `onWake` in managerPolicy. The
- * flag clears automatically on `onExit` (kill-and-respawn path) and on
- * `onSpawned` (idle-branch spawn path); the runtime does not dispatch an
- * explicit "end reset" event.
- */
markResetting(agentId: string): void {
this.dispatch({ type: "begin_reset", agentId, nowMs: this.now() });
- // Mark the CURRENTLY-live session (if any) superseded, so its death rattle
- // — the interrupted-turn error the dying process emits before `exit` — is
- // suppressed by the error-audit gate, while the reborn session (a fresh
- // `activeSpawnState` entry with `superseded=false`) still surfaces its own
- // genuine errors. Per-session identity, set at kill-initiation. If there's
- // no live session yet (reset of an idle agent), there's nothing to rattle.
const live = this.activeSpawnState.get(agentId);
if (live) live.superseded = true;
}
-
- /**
- * Owner-triggered synchronous reset. Orchestrates the "kill and rewake"
- * flow atomically:
- * 1. `register` — idempotent; ensures the FSM knows the agent and its
- * runtime caps (fresh daemon after restart, bot never woken since).
- * 2. `forgetSession` — clears resume caches + writes the timeline
- * barrier; nulls `AgentState.sessionId` via the reset_session event.
- * 3. `markResetting` — flips `agent.resetting = true` so any wake that
- * lands between here and the reset spawn just enqueues to inbox
- * (no steer against the dying session, no duplicate spawn).
- * 4. If idle: `deliver` — emits `spawn` for a fresh session with the
- * rewake as the prompt. `resetting` is cleared by `onSpawned`.
- * 5. If live/starting/stopping: `enqueueRewake` (no effect) then
- * `stop`. The `exit` event fires later; `onExit` drains the inbox
- * (rewake + any queued unreads) into a single fresh spawn and clears
- * `resetting`.
- *
- * Steps 1–3 (and 4/5's initial dispatch) are all synchronous reducer
- * dispatches inside a single Node tick — no incoming wake can interleave
- * before `resetting = true` is set. Only `await stop()` yields the event
- * loop; by then the gate is up.
- */
async resetSession(
agentId: string,
opts: {
runtimeConfig: RuntimeConfig;
launchId: string;
rewakePrompt: string;
- /** Timeline barrier kind — `reset_session` (owner) or `nap` (self). Default reset_session. */
barrierType?: "reset_session" | "nap";
},
): Promise<void> {
- // Reset = restart that FORGETS the session (writes the timeline barrier),
- // so the fresh spawn starts with no prior context. `agent:nap` reuses this
- // path with `barrierType: "nap"`.
await this.restartAgent(agentId, {
runtimeConfig: opts.runtimeConfig,
launchId: opts.launchId,
@@ -909,31 +525,6 @@ export class AgentProcessManager {
opName: "reset",
});
}
-
- /**
- * Shared "kill and rewake" orchestration behind `resetSession` (forget) and
- * `switchModel` (preserve). Atomic within one Node tick up to `stop()`:
- * 1. `register` — idempotent; ensures the FSM knows the agent + its runtime
- * caps (fresh daemon after restart, bot never woken since).
- * 2. `forgetSession` (ONLY when `opts.forgetSession`) — clears resume caches
- * + writes the timeline barrier + nulls `AgentState.sessionId`. Skipped
- * by `switchModel` so the session + history SURVIVE across the relaunch.
- * 3. `markResetting` — flips `agent.resetting = true` (the SPAWN GATE, not a
- * semantic "reset"): a wake landing between here and the respawn queues
- * to inbox instead of steering the dying session / double-spawning.
- * 4. idle → `deliver` emits a fresh `spawn` with the rewake as prompt
- * (`resetting` cleared by `onSpawned`). Non-idle → `enqueueRewake` then
- * `stop`; `onExit` drains rewake + queued unreads into one fresh spawn
- * and clears `resetting`.
- *
- * The idle branch's `doSpawn` can throw synchronously (missing
- * credentialProxy / sdkDriverDepsFor, driver constructor throwing). Without
- * recovery the FSM would wedge at `starting`+`resetting=true` forever; the
- * catch dispatches `exit` so `onExit` clears the gate back to `idle`, then
- * rethrows. This is the single unified failure path for both callers — the
- * observable failure landing (idle, gate cleared, throw propagated) is
- * identical to the pre-convergence per-method arms.
- */
private async restartAgent(
agentId: string,
opts: {
@@ -943,7 +534,6 @@ export class AgentProcessManager {
forgetSession: boolean;
barrierType?: "reset_session" | "nap";
abortCause: "reset" | "nap" | "model_switch";
- /** Human label for logs so a restart failure reads as reset vs model switch. */
opName: string;
},
): Promise<void> {
@@ -954,7 +544,10 @@ export class AgentProcessManager {
const status = this.state.agents[agentId]?.status;
if (status === "idle") {
try {
- this.deliver(agentId, { text: opts.rewakePrompt });
+ this.deliver(agentId, {
+ id: `${opts.launchId}:${opts.abortCause}:rewake`,
+ text: opts.rewakePrompt,
+ });
} catch (err) {
this.log.error(`agent ${opts.opName} idle-branch spawn threw synchronously`, {
agentId,
@@ -965,49 +558,16 @@ export class AgentProcessManager {
}
return;
}
- // Live / starting / stopping: enqueue the rewake so `onExit`'s drain picks
- // it up. `stop()` yields the event loop; any inbound wake in the interim
- // hits the gate and queues to inbox — landing in the SAME drain-and-spawn.
- this.enqueueRewake(agentId, { text: opts.rewakePrompt });
+ this.enqueueRewake(agentId, {
+ id: `${opts.launchId}:${opts.abortCause}:rewake`,
+ text: opts.rewakePrompt,
+ });
await this.stop(agentId);
}
-
- /**
- * Owner-triggered model switch — `resetSession` MINUS the `forgetSession`
- * call, so the session and conversation history SURVIVE while the process is
- * relaunched on the new model. `register` installs the new `runtimeConfig`
- * into `runtimeConfigs`, which `doSpawn` reads at launch, so the respawn
- * carries the new model.
- *
- * Session preservation comes from two verified places — NOT from
- * `resumeSessions` (that map is only populated when `register` receives a
- * `launch.sessionId`, and `buildUnreadWakeCommand` never sets one, so it is
- * empty for community bots):
- * - Live path: skipping `forgetSession` means `reset_session` is never
- * dispatched, so `agent.sessionId` is still set at exit time and `onExit`
- * emits `{ type: "spawn", resumeSessionId: agent.sessionId }` — the
- * respawn resumes the same session.
- * - Durable path: no `reset_session` timeline barrier is written, so
- * `findResumableSession` still walks back to the last real session id
- * after a daemon restart.
- *
- * `markResetting`/`begin_reset` are reused as the SPAWN GATE, not as a
- * semantic "reset": they set `agent.resetting = true` so a wake landing
- * mid-switch queues to inbox instead of double-spawning. The field name reads
- * as reset-specific but the mechanism is identical; duplicating it would just
- * fork the same gate. `onExit` clears the flag unconditionally (including on
- * the spawn-failure path), so no new unlock path is needed.
- */
async switchModel(
agentId: string,
opts: { runtimeConfig: RuntimeConfig; launchId: string; rewakePrompt: string },
): Promise<void> {
- // Model switch = restart that PRESERVES the session: skipping `forgetSession`
- // means no `reset_session` barrier is written and `agent.sessionId` is still
- // set at exit time, so `onExit` respawns with `resumeSessionId` (live path)
- // and `findResumableSession` still resolves the last session after a daemon
- // restart (durable path) — the agent picks up where it left off on the new
- // model.
await this.restartAgent(agentId, {
runtimeConfig: opts.runtimeConfig,
launchId: opts.launchId,
@@ -1017,22 +577,18 @@ export class AgentProcessManager {
opName: "model switch",
});
}
-
start(): void {
if (this.tickTimer) return;
this.tickTimer = setInterval(() => this.dispatch({ type: "tick", nowMs: this.now() }), this.opts.tickIntervalMs);
this.tickTimer.unref?.();
}
-
- /** Stop a single agent's session (if running). */
async stop(agentId: string): Promise<void> {
const session = this.sessions.get(agentId);
if (!session) return;
this.abortCurrentTurn(agentId, "requested_stop");
- await Promise.resolve(session.stop({ reason: "requested", forceAfterMs: SESSION_STOP_GRACE_MS }));
- this.sessions.delete(agentId);
+ await session.stop({ reason: "owner_request", forceAfterMs: SESSION_STOP_GRACE_MS });
+ if (this.sessions.get(agentId) === session) this.sessions.delete(agentId);
}
-
async stopAll(): Promise<void> {
if (this.tickTimer) {
clearInterval(this.tickTimer);
@@ -1040,35 +596,21 @@ export class AgentProcessManager {
}
const entries = [...this.sessions.entries()];
for (const [agentId] of entries) this.abortCurrentTurn(agentId, "shutdown");
- await Promise.all(entries.map(([, session]) =>
- Promise.resolve(session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS })),
- ));
+ await Promise.all(entries.map(async ([, session]) => {
+ const receipt = await session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ if (receipt.status === "already_stopping") await session.closed;
+ }));
this.sessions.clear();
}
-
- /** For inspection/testing. */
snapshot(): ManagerState {
return this.state;
}
-
- /**
- * Live agent sessions (agentId + sessionId + launchId) for control-plane
- * resync after a reconnect. Only agents whose runtime has reported a session.
- */
- /**
- * Current (sessionId, launchId) for an agent, or nulls if not yet known.
- * Read by Producer B (credential-proxy sighting) so `cli_invocation` audit
- * events carry the same context Producer A's `tool_call` / `thinking`
- * events do — plan §Data model asks for launchId on every event where
- * known, and sessionId once the runtime handshake has landed.
- */
auditContext(agentId: string): { sessionId: string | null; launchId: string | null } {
return {
sessionId: this.liveSessions.get(agentId) ?? null,
launchId: this.launchIds.get(agentId) ?? null,
};
}
-
liveSessionReports(): Array<{ agentId: string; sessionId: string; launchId: string }> {
return [...this.liveSessions.entries()].map(([agentId, sessionId]) => ({
agentId,
@@ -1076,36 +618,16 @@ export class AgentProcessManager {
launchId: this.launchIds.get(agentId) ?? "",
}));
}
-
- /**
- * Current derived activity for every known agent, for control-plane resync
- * and heartbeat re-assert. Level-triggered snapshot of the same
- * `deriveActivity` the edge-triggered dispatch uses, so a dropped
- * `agent_activity` frame can be recovered from the daemon's own truth.
- */
liveAgentActivities(): Array<{ agentId: string; state: AgentActivityState }> {
return Object.entries(this.deriveActivitySnapshot(this.state)).map(([agentId, state]) => ({
agentId,
state,
}));
}
-
- /** Current derived activity for one agent, or null if it isn't known. */
agentActivity(agentId: string): AgentActivityState | null {
const agent = this.state.agents[agentId];
return agent ? this.deriveActivity(agent) : null;
}
-
- /**
- * Slim per-agent FSM projection for the `daemon status` snapshot file (batch
- * E2). Metadata only — NO message content, NO PII. Exposes BOTH the raw FSM
- * `status` AND the `derivedActivity` (the running/idle display) so a reader
- * can tell apart the three idle-looking states the frontend's coarse marker
- * conflates: between-turns idle (running + !turnActive), a real turn in
- * flight, and a wedge (climbing `sinceProgressMs` / non-null `stoppingSince`).
- * `nowMs` is passed in so the caller stamps a single consistent `writtenAt`.
- * See plans/daemon-fsm-desync.md batch E2.
- */
statusProjection(nowMs: number): Array<{
agentId: string;
status: AgentStatus;
@@ -1125,27 +647,18 @@ export class AgentProcessManager {
stoppingSince: a.stoppingSince,
}));
}
-
- /* --------------------------------------------------------------- */
- /* Core dispatch: reduce → apply effects */
- /* --------------------------------------------------------------- */
-
private emitTrace(rec: ManagerTraceRecord): void {
if (!this.opts.onFsmTransition) return;
try {
this.opts.onFsmTransition(rec);
} catch {
- // Trace is strictly read-only. A broken sink cannot change reducer or
- // runtime-call behavior, nor can it leave a lifecycle span half-closed.
}
}
-
private traceOwnerFor(agentId: string, captured?: ActiveSpawnState): ActiveSpawnState | undefined {
if (captured) return captured.agentId === agentId ? captured : undefined;
const owner = this.activeSpawnState.get(agentId);
return owner && this.sessions.get(agentId) === owner.session ? owner : undefined;
}
-
private openTurn(owner: ActiveSpawnState): ActiveTurnSpan {
if (owner.activeSpan) return owner.activeSpan;
const daemonTurnOrdinal = this.nextDaemonTurnOrdinal++;
@@ -1169,7 +682,6 @@ export class AgentProcessManager {
});
return span;
}
-
private closeTurn(
owner: ActiveSpawnState,
expectedSpan: ActiveTurnSpan | null,
@@ -1178,7 +690,6 @@ export class AgentProcessManager {
| { event: "turn_abort"; abortCause: TraceAbortCause },
): boolean {
if (!expectedSpan || owner.activeSpan !== expectedSpan) return false;
- // Clear before invoking the sink: throw/re-entry can never close twice.
owner.activeSpan = null;
const nowMs = this.now();
const base = {
@@ -1205,42 +716,39 @@ export class AgentProcessManager {
}
return true;
}
-
private abortCurrentTurn(agentId: string, cause: TraceAbortCause): void {
const owner = this.traceOwnerFor(agentId);
if (owner) this.closeTurn(owner, owner.activeSpan, { event: "turn_abort", abortCause: cause });
}
-
private dispatch(event: ManagerEvent, capturedOwner?: ActiveSpawnState): ManagerEffect[] {
const before = this.deriveActivitySnapshot(this.state);
+ const previousState = this.state;
const { state, effects } = reduceManager(this.state, event);
this.state = state;
const eventAgentId = (event as { agentId?: string }).agentId;
const closingOwner =
- event.type === "turn_end" && eventAgentId
+ event.type === "turn_completed" && eventAgentId && state !== previousState
? this.traceOwnerFor(eventAgentId, capturedOwner)
: undefined;
const closingSpan = closingOwner?.activeSpan ?? null;
- // FSM transition trace (plans/daemon-fsm-desync.md): pure observability, no
- // behavior change. Emits one record per reduce so a wedge that leaves no
- // other log (the gated_hold/send branches are the only ones that log today,
- // and the wedge slips both) is reconstructable from the agent's FSM history
- // — the missing capability behind every "no log when it breaks" incident.
- // Guarded so it's a no-op unless a sink is wired (createDaemon opts).
if (this.opts.onFsmTransition) {
const emit = (agentId: string): void => {
const a = this.state.agents[agentId];
if (!a) return;
const nowMs = this.now();
+ const diagnostics = this.traceDiagnostics(agentId, capturedOwner);
const activeSpan = this.traceOwnerFor(agentId, capturedOwner)?.activeSpan ?? null;
- // Effects this dispatch produced FOR THIS agent (effects carry agentId,
- // so a tick that terminates one wedged agent attributes correctly).
const myEffects = effects.filter((e) => (e as { agentId?: string }).agentId === agentId).map((e) => e.type);
this.emitTrace({
recordKind: "fsm",
agentId,
- event: event.type,
+ event: event.type === "turn_work"
+ ? "root_work"
+ : event.type === "turn_completed"
+ ? "turn_end"
+ : event.type,
status: a.status,
+ turnId: a.turnId,
turnActive: a.turnActive,
inbox: a.inbox.length,
lastDeliverAt: a.lastDeliverAt,
@@ -1249,28 +757,15 @@ export class AgentProcessManager {
resetting: a.resetting,
resettingSince: a.resettingSince,
stoppingSince: a.stoppingSince,
- apmPhase: a.apm.phase,
+ ...diagnostics,
effects: myEffects,
nowMs,
timeIso: new Date(nowMs).toISOString(),
...(activeSpan ? activeSpan : {}),
- // Derived watchdog inputs — the ONLY way to judge, per wedge, WHY no
- // watchdog fired: `sinceProgressMs` is `stalled`/`suspectedDeaf`'s
- // "no progress for how long" (if it keeps getting reset small on a
- // wedged agent, lastProgressAt is being bumped by stray progress =
- // the anchor is unusable — the exit-1 decision). `sinceDeliverMs` is
- // suspectedDeaf's half (null when no deliver ever happened = its
- // blind spot). `sinceStoppingMs` is the stopping-stuck backstop's
- // clock (null unless in `stopping`) — how close it is to `force_exit`,
- // so a stopping-wedge is legible in the trace instead of inferred from
- // a bare `status=stopping` streak. See plans/daemon-fsm-desync.md.
sinceProgressMs: nowMs - a.lastProgressAt,
sinceDeliverMs: a.lastDeliverAt === null ? null : nowMs - a.lastDeliverAt,
sinceStoppingMs: a.stoppingSince === null ? null : nowMs - a.stoppingSince,
- // Non-clean-turn tag, carried on the `turn_end` event itself (not agent
- // state). Spread so a clean turn_end / any other event omits the keys
- // entirely rather than emitting explicit undefineds. B1.
- ...(event.type === "turn_end" && (event as { endReason?: "errored" }).endReason === "errored"
+ ...(event.type === "turn_completed" && (event as { endReason?: "errored" }).endReason === "errored"
? {
endReason: "errored" as const,
terminationCause: normalizeTerminationCause(
@@ -1278,16 +773,11 @@ export class AgentProcessManager {
),
}
: {}),
- // Raw physical exit fact, carried on the `exit` event (not agent
- // state). Spread on exit only so non-exit events omit the keys. T1 —
- // makes a hard exit distinguishable from a clean one in the trace.
...(event.type === "exit"
? {
exitCode: (event as { exitCode?: number | null }).exitCode ?? null,
exitSignal: (event as { exitSignal?: string | null }).exitSignal ?? null,
abnormal: (event as { abnormal?: boolean }).abnormal ?? false,
- // Launch-failure reason (T2). Included only when present so a
- // normal exit row stays free of the key.
...((event as { spawnFailureReason?: string | null }).spawnFailureReason != null
? {
spawnFailureReason: normalizeSpawnFailureReason(
@@ -1295,8 +785,6 @@ export class AgentProcessManager {
),
}
: {}),
- // Recovery semantic (T3). Included only when present — a plain
- // runtime exit has none.
...((event as { terminationSemantics?: string | null }).terminationSemantics != null
? {
terminationSemantics: normalizeTerminationSemantics(
@@ -1309,19 +797,11 @@ export class AgentProcessManager {
});
};
if (eventAgentId) {
- // Agent-scoped event (wake / spawned / turn_end / …).
emit(eventAgentId);
} else if (event.type === "tick") {
- // A tick carries no agentId but the reducer evaluates EVERY agent's
- // watchdogs — fan out so each agent's per-tick watchdog inputs + any
- // effect (or its ABSENCE) are on record. This is what makes "did the
- // tick run and why did stalled not fire" answerable (exit-3).
for (const id of Object.keys(this.state.agents)) emit(id);
}
}
- // Trace-only lifecycle close: never enters the reducer. It occurs after the
- // FSM row (which still carries the active id) and before any queued effect
- // can open the next turn.
if (closingOwner && closingSpan) {
const errored = (event as { endReason?: unknown }).endReason === "errored";
this.closeTurn(
@@ -1338,72 +818,134 @@ export class AgentProcessManager {
: { event: "turn_end", outcome: "clean" },
);
}
- for (const effect of effects) this.applyEffect(effect);
- if (this.opts.onAgentActivity) {
- const after = this.deriveActivitySnapshot(this.state);
+ if (
+ this.opts.onAgentActivity
+ && event.type !== "spawned"
+ && event.type !== "admission_started"
+ && event.type !== "admission_settled"
+ ) {
+ const after = this.deriveActivitySnapshot(state);
for (const [agentId, activity] of Object.entries(after)) {
- // Skip a brand-new agent appearing this dispatch (register) — only
- // report real transitions of an already-known agent.
if (agentId in before && before[agentId] !== activity) {
this.opts.onAgentActivity({ agentId, state: activity });
}
}
}
+ for (const effect of effects) this.applyEffect(effect);
return effects;
}
-
private deriveActivitySnapshot(state: ManagerState): Record<string, AgentActivityState> {
const snapshot: Record<string, AgentActivityState> = {};
for (const [agentId, agent] of Object.entries(state.agents)) snapshot[agentId] = this.deriveActivity(agent);
return snapshot;
}
-
- /**
- * `AgentState.status` alone doesn't mean "actively working" — a persistent
- * agent stays `"running"` for up to `idleTimeoutMs` after a turn ends, before
- * the tick loop finally stops it. A `running` agent is "running" only while it
- * has work in hand (`isActivelyWorking`: turn in flight OR queued inbox);
- * otherwise it reads "idle" the moment the turn ends, without waiting for the
- * hibernation timeout. `starting`/`stopping` pass through unchanged.
- */
private deriveActivity(agent: AgentState): AgentActivityState {
if (agent.status === "running") return isActivelyWorking(agent) ? "running" : "idle";
return agent.status;
}
-
+ private traceDiagnostics(agentId: string, capturedOwner?: ActiveSpawnState): Pick<
+ FsmTraceRecord,
+ | "deliveryPhase"
+ | "physicalOpenCount"
+ | "turnCount"
+ | "commandAdmissionCount"
+ | "commandAdmissionLatencyTotalMs"
+ | "queueDwellCount"
+ | "queueDwellTotalMs"
+ | "sseReconnectCount"
+ | "resumeOutcome"
+ | "terminalOwnerKind"
+ > {
+ const owner = this.traceOwnerFor(agentId, capturedOwner);
+ const snapshot = owner?.session?.snapshot();
+ const pending = owner
+ ? [...owner.pendingDeliverySpans.values()].find((delivery) => !delivery.driverObserved)
+ : undefined;
+ const snapshotDiagnostics = snapshot?.diagnostics;
+ const deliveryPhase = pending
+ ? pending.mode === "idle" ? "admission_wait" : "steering"
+ : snapshotDiagnostics?.deliveryPhase ?? "idle";
+ if (!snapshotDiagnostics) return { deliveryPhase };
+ return { deliveryPhase, ...snapshotDiagnostics.metrics };
+ }
private withFooter(text: string): string {
return this.opts.wakePromptFooter ? `${text}\n\n${this.opts.wakePromptFooter}` : text;
}
-
- /**
- * Prepend the local-tz wall-clock the moment BEFORE the text is handed to
- * the runtime driver. Called at the very last mile — inside `doSpawn` right
- * before `session.start(...)`, and inside `applyEffect`'s `send` branch
- * right before `session.send(...)` — so the timestamp reflects "when the
- * agent actually sees this text", not when the effect was scheduled. Gated
- * by an opt-in flag so tests that assert on exact prompt strings stay
- * stable; enabled in production via `createDaemon`.
- */
private stampNow(text: string): string {
return this.opts.stampWakePromptTime ? `[${nowLocalISO()}] ${text}` : text;
}
-
+ private beginPendingDelivery(
+ owner: ActiveSpawnState,
+ commandId: string,
+ message: AgentMsg,
+ mode: "busy" | "idle",
+ span: ActiveTurnSpan | null,
+ requeueOnFailure = true,
+ ): boolean {
+ const sessionInstanceId = owner.sessionInstanceId;
+ if (!sessionInstanceId || owner.pendingDeliverySpans.has(commandId)) return false;
+ owner.pendingDeliverySpans.set(commandId, {
+ sessionInstanceId,
+ span,
+ mode,
+ driverObserved: false,
+ });
+ this.dispatch({
+ type: "admission_started",
+ agentId: owner.agentId,
+ sessionInstanceId,
+ commandId,
+ exactAgentMsg: message,
+ mode,
+ requeueOnFailure,
+ nowMs: this.now(),
+ }, owner);
+ return true;
+ }
+ private markPendingDeliveryObserved(owner: ActiveSpawnState, commandId: string): void {
+ const pending = owner.pendingDeliverySpans.get(commandId);
+ if (pending) pending.driverObserved = true;
+ }
+ private acknowledgePendingDelivery(owner: ActiveSpawnState, commandId: string): void {
+ const pending = owner.pendingDeliverySpans.get(commandId);
+ if (!pending) return;
+ this.dispatch({
+ type: "admission_acknowledged",
+ agentId: owner.agentId,
+ sessionInstanceId: pending.sessionInstanceId,
+ commandId,
+ }, owner);
+ }
+ private settlePendingDelivery(
+ owner: ActiveSpawnState,
+ commandId: string,
+ outcome: "accepted" | "failed" = "failed",
+ ): PendingDeliveryTrace | undefined {
+ const pending = owner.pendingDeliverySpans.get(commandId);
+ if (!pending) return undefined;
+ owner.pendingDeliverySpans.delete(commandId);
+ this.dispatch({
+ type: "admission_settled",
+ agentId: owner.agentId,
+ sessionInstanceId: pending.sessionInstanceId,
+ commandId,
+ outcome,
+ }, owner);
+ return pending;
+ }
private applyEffect(effect: ManagerEffect): void {
switch (effect.type) {
case "spawn":
- // Timestamp is applied inside doSpawn just before session.start — the
- // spawn path adds workdir resolution + system-prompt assembly + child
- // wiring latency between here and there, which can be tens to hundreds
- // of ms on cold start. Stamping now would lock in a moment that lags
- // reality by the whole spawn setup window.
- this.doSpawn(effect.agentId, this.withFooter(effect.prompt), effect.resumeSessionId);
+ this.doSpawn(effect.agentId, effect.messages, effect.resumeSessionId);
break;
case "send": {
const session = this.sessions.get(effect.agentId);
- // Stamp at the moment the text hits `session.send`, not earlier —
- // between effect creation and this call the event loop can drain other
- // dispatches, and we want the timestamp to match the agent's arrival.
- const input = { text: this.stampNow(this.withFooter(effect.text)), mode: effect.mode };
+ const input = {
+ id: effect.message.id!,
+ kind: "user" as const,
+ text: this.stampNow(this.withFooter(effect.message.text)),
+ sequence: effect.message.seq,
+ };
if (session) {
const owner = this.activeSpawnState.get(effect.agentId);
const exactOwner = owner?.session === session ? owner : undefined;
@@ -1412,12 +954,14 @@ export class AgentProcessManager {
? this.openTurn(exactOwner)
: exactOwner.activeSpan
: null;
+ if (exactOwner) this.beginPendingDelivery(exactOwner, input.id, effect.message, effect.mode, associatedSpan);
+ let sent: ReturnType<DaemonAgentSession["send"]>;
try {
- // Deliberately do not inspect/await the return value: ManagedSession
- // send is observationally synchronous under the existing contract.
- session.send(input);
+ sent = session.send(input);
+ if (exactOwner) this.markPendingDeliveryObserved(exactOwner, input.id);
} catch (error) {
if (exactOwner) {
+ this.settlePendingDelivery(exactOwner, input.id);
this.closeTurn(exactOwner, associatedSpan, {
event: "turn_abort",
abortCause: "send_threw",
@@ -1425,6 +969,51 @@ export class AgentProcessManager {
}
throw error;
}
+ void Promise.resolve(sent).then((receipt) => {
+ if (
+ !exactOwner
+ || exactOwner.torndown
+ || this.sessions.get(effect.agentId) !== session
+ || this.activeSpawnState.get(effect.agentId) !== exactOwner
+ ) return;
+ if (receipt.status === "rejected") {
+ if (!exactOwner.pendingDeliverySpans.has(input.id)) return;
+ this.settlePendingDelivery(exactOwner, input.id);
+ this.closeTurn(exactOwner, associatedSpan, {
+ event: "turn_abort",
+ abortCause: "send_threw",
+ });
+ this.emitErrorAudit(
+ effect.agentId,
+ "runtime",
+ receipt.error?.code ?? receipt.reason,
+ receipt.error?.message ?? `Delivery rejected (${receipt.reason})`,
+ );
+ void session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ }
+ }).catch((error) => {
+ if (
+ !exactOwner
+ || exactOwner.torndown
+ || this.sessions.get(effect.agentId) !== session
+ || this.activeSpawnState.get(effect.agentId) !== exactOwner
+ ) return;
+ if (!exactOwner.pendingDeliverySpans.has(input.id)) return;
+ this.settlePendingDelivery(exactOwner, input.id);
+ this.closeTurn(exactOwner, associatedSpan, {
+ event: "turn_abort",
+ abortCause: "send_threw",
+ });
+ this.emitErrorAudit(effect.agentId, "runtime", "send_failed", String(error));
+ void session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ });
+ } else {
+ this.dispatch({
+ type: "delivery_rejected",
+ agentId: effect.agentId,
+ message: effect.message,
+ mode: effect.mode,
+ });
}
this.log.info("steering message sent to running agent", { agentId: effect.agentId, mode: effect.mode });
break;
@@ -1439,31 +1028,14 @@ export class AgentProcessManager {
abortCause: "terminate_stalled",
});
}
- void Promise.resolve(session?.stop({ reason: effect.type, forceAfterMs: SESSION_STOP_GRACE_MS }));
- // The stop we just issued will make the underlying process emit its
- // own `exit` shortly after — suppress that follow-up log so a single
- // termination doesn't produce two contradictory "session ended" lines.
+ void session?.stop({
+ reason: effect.type === "stop" ? "idle_timeout" : "stalled",
+ forceAfterMs: SESSION_STOP_GRACE_MS,
+ });
if (spawnState) spawnState.suppressExitLog = true;
- // `terminate_stalled` is the stall watchdog SIGKILLing a wedged turn —
- // an INVOLUNTARY kill (Blair's case). Mark it by cause so the trailing
- // turn_end tags `killed_stalled`, independent of whether the runtime
- // emits a death-rattle error. `stop` (voluntary idle-timeout) does NOT
- // mark — that's a clean end (Cecilia 架构#352 red line 2). See B1.
if (effect.type === "terminate_stalled") {
this.nonCleanEndMarker.set(effect.agentId, { cause: "killed_stalled" });
}
- // T3: record the recovery SEMANTIC of this stop on the per-spawn state so
- // the trailing exit (via the exit listener, where state is still alive)
- // carries it into the trace. Split by effect.type — the two share this
- // branch but mean opposite things: `terminate_stalled` = stall watchdog
- // SIGKILL (killed_stalled, same word as B1's turn_end-path cause — one
- // concept, one token); voluntary `stop` = idle-timeout hibernation
- // (idle_stop). Conflating them would re-create the "stall-kill
- // impersonates idle" bug in the trace. Purely additive semantic layer
- // over the physical exit fact (exitSignal/etc), never overwriting it —
- // and NOTHING reads it for policy (kept out of B2's rewake gate, which
- // reads terminationCause on turn_end only). See
- // plans/daemon-trace-completeness-charter.md T3.
if (spawnState) {
spawnState.terminationSemantics = effect.type === "terminate_stalled" ? "killed_stalled" : "idle_stop";
}
@@ -1471,24 +1043,28 @@ export class AgentProcessManager {
this.opts.onAgentLocallyStopped?.({ agentId: effect.agentId, reason: effect.type });
break;
}
+ case "expire_admission": {
+ const owner = this.activeSpawnState.get(effect.agentId);
+ if (!owner || owner.sessionInstanceId !== effect.sessionInstanceId) break;
+ for (const commandId of effect.commandIds) {
+ owner.pendingDeliverySpans.delete(commandId);
+ }
+ this.closeTurn(owner, owner.activeSpan, { event: "turn_abort", abortCause: "send_threw" });
+ owner.terminationSemantics = "killed_stalled";
+ void owner.session?.stop({ reason: "stalled", forceAfterMs: SESSION_STOP_GRACE_MS });
+ this.logSessionEnded(effect.agentId, "terminate_stalled");
+ this.opts.onAgentLocallyStopped?.({ agentId: effect.agentId, reason: "terminate_stalled" });
+ break;
+ }
+ case "requeue_delivery":
+ this.dispatch({
+ type: "delivery_rejected",
+ agentId: effect.agentId,
+ message: effect.message,
+ mode: effect.mode,
+ });
+ break;
case "force_exit": {
- // Stopping-stuck black-hole escape (plans/daemon-fsm-desync.md batch L3):
- // the agent sat in `stopping` past the threshold because the `exit` a
- // prior stop/terminate expected never came. Force the FSM out.
- //
- // (1) Best-effort kill the process so we don't leak an orphan, via a
- // three-way fallback (batch F):
- // - session handle present → stop() it (the normal path);
- // - handle gone but we recorded its pid at spawn → killProcessTree
- // the pid directly. This is the case that caused this wedge
- // (batch G / Hypothesis A: the map entry was cleared while the OS
- // process lived on) — now we can actually reap the orphan instead
- // of only warning. killProcessTree self-guards a dead/invalid pid.
- // - neither (SDK in-process session: no OS pid) → genuinely
- // unkillable, so warn (honest, not a fake kill).
- // DIAGNOSTIC (batch G): log which branch we took + that the session
- // handle was absent, so the proximate no-op root (why sessions map
- // lost the entry) has a durable data point at each real occurrence.
const session = this.sessions.get(effect.agentId);
const state = this.activeSpawnState.get(effect.agentId);
if (state) {
@@ -1498,431 +1074,323 @@ export class AgentProcessManager {
});
}
if (session) {
- void Promise.resolve(session.stop({ reason: effect.reason, forceAfterMs: SESSION_STOP_GRACE_MS })).catch(() => {});
- } else if (state?.pid != null) {
- // Orphan reap: handle gone (sessions.has === false) but pid recorded.
- this.log.warn("force_exit: session handle gone at force_exit — reaping orphan via recorded pid (batch G Hypothesis A confirmed at runtime)", {
- agentId: effect.agentId,
- reason: effect.reason,
- pid: state.pid,
- });
- void Promise.resolve(killProcessTree(state.pid, { graceMs: SESSION_STOP_GRACE_MS })).catch(() => {});
+ void Promise.resolve(
+ session.stop({ reason: "stalled", forceAfterMs: SESSION_STOP_GRACE_MS }),
+ ).catch(() => {});
} else {
- this.log.warn("force_exit: no session handle AND no recorded pid — cannot kill (SDK in-process session or pre-spawn); possible orphan", {
+ this.log.warn("force_exit: logical session handle is already absent", {
agentId: effect.agentId,
reason: effect.reason,
});
}
- // (2) Tear down tracking + mark torndown so the killed process's eventual
- // late `exit` (if the kill does land) is a no-op, not a second
- // teardown that could clobber a session a fresh wake spawned in
- // between — same guard the handshake-timeout path uses.
if (state) state.torndown = true;
this.logSessionEnded(effect.agentId, "terminate_stalled");
if (this.sessions.get(effect.agentId) === session) this.sessions.delete(effect.agentId);
this.liveSessions.delete(effect.agentId);
if (this.activeSpawnState.get(effect.agentId) === state) this.activeSpawnState.delete(effect.agentId);
- // Clear the killed_stalled marker set at (1249) — this force_exit IS its
- // trailing terminal event. The `session.on("exit")` clear (~:1569) can't
- // do it on this path: force_exit set `torndown` (the late real exit
- // bails at the torndown early-return) AND deleted activeSpawnState (its
- // `=== state` guard then fails). Without this, the leaked marker gets
- // consumed by the NEXT healthy reborn turn's turn_end (~:1842) and
- // mislabels that turn `killed_stalled` in the trace/audit — a forensic
- // lie, not a behavior bug, but it corrupts post-force_exit trace reads.
this.nonCleanEndMarker.delete(effect.agentId);
this.opts.onAgentLocallyStopped?.({ agentId: effect.agentId, reason: "terminate_stalled" });
- // (3) Synthetic `exit` → the normal onExit recovery (drain-respawn or
- // settle idle; enterStable clears stoppingSince). Universal backstop:
- // works whether or not we could kill the process.
- // T3: `terminationSemantics` is set INLINE here, not via the state
- // marker — activeSpawnState was already deleted at (2) above, so the
- // marker is unreadable by the time this synthetic exit dispatches.
- // Labels this as the stopping-stuck black-hole escape (force_exit),
- // otherwise the synthetic exit is a bare, unexplained exit in trace.
this.dispatch({ type: "exit", agentId: effect.agentId, terminationSemantics: "force_exit" });
break;
}
- case "gated_hold":
- // Pure observability — no behavioral effect. Emitted whenever a
- // gated agent has a non-empty inbox but nothing was actually sent.
- this.log.info("gated busy message held", {
- agentId: effect.agentId,
- reason: effect.reason,
- blockedReason: effect.blockedReason,
- recentEvents: effect.recentEvents,
- });
- break;
}
}
-
private logSessionEnded(agentId: string, reason: "turn_end" | "stopped" | "terminate_stalled" | "exit"): void {
this.log.info("agent session ended", { agentId, sessionId: this.liveSessions.get(agentId) ?? "", reason });
}
-
- private doSpawn(agentId: string, prompt: string, resumeSessionId: string | null): void {
+ private doSpawn(agentId: string, messages: AgentMsg[], resumeSessionId: string | null): void {
+ const [first, ...pending] = messages;
+ if (!first) throw new Error(`AgentProcessManager: spawn for ${agentId} has no command`);
+ const prompt = this.withFooter(first.text);
const driver = this.opts.driverFor(agentId, this.runtimeConfigs.get(agentId));
const base = this.opts.baseContextFor(agentId);
- // The server-pushed RuntimeConfig (from agent:wake) takes precedence over
- // any baseContextFor default; the resume sessionId likewise prefers the
- // manager's runtime-tracked id, then the server-pushed one, then the base.
- const runtimeConfig = this.runtimeConfigs.get(agentId) ?? base.config?.runtimeConfig;
- // Logged AFTER `runtimeConfig` is declared — reading it above would be a
- // `const` TDZ ReferenceError on every spawn. The resolved model is the QA
- // signal that a wake/reset/switch launched on the configured model.
+ const configuredRuntime = this.runtimeConfigs.get(agentId) ?? base.config?.runtimeConfig;
this.log.info("spawning agent", {
agentId,
runtime: driver.id,
- model: resolveLaunchFieldsOrDefault(runtimeConfig).model ?? "default",
+ model: runtimeModelName(configuredRuntime) ?? "default",
});
- const provider = runtimeConfig?.runtime ?? null;
- // Resume precedence: an explicit effect-supplied id → the manager's in-memory
- // tracked id → the server-pushed id → the durable timeline (latest finished
- // session for this agent, survives daemon restarts) → the base context.
+ if (!this.opts.sessionFactory) {
+ throw new Error("AgentProcessManager: a public AgentSession factory is required");
+ }
+ const runtimeConfig = configuredRuntime ?? ({
+ version: 1,
+ runtime: driver.id,
+ model: { kind: "default" },
+ mode: { kind: "default" },
+ } as RuntimeConfig);
+ const provider = runtimeConfig.runtime;
const sessionId =
resumeSessionId ??
this.resumeSessions.get(agentId) ??
this.opts.timeline?.resumeSessionId(agentId, provider) ??
base.config?.sessionId;
- const description = runtimeConfig?.instruction ?? base.config?.description ?? runtimeConfig?.agentName;
- const agentName = runtimeConfig?.agentName ?? base.config?.agentName;
- const agentHandle = runtimeConfig?.agentHandle ?? base.config?.agentHandle;
- const config: LaunchContext["config"] = { ...(base.config ?? {}), runtimeConfig, sessionId, description, agentName, agentHandle };
- // The driver owns system-prompt assembly — it knows its runtime's format,
- // notification style, and CLI contract. The daemon just calls it.
- const standingPrompt = base.standingPrompt || driver.buildSystemPrompt?.(config, agentId) || "";
- const ctx: LaunchContext = {
+ const description = runtimeConfig.instruction ?? base.config?.description ?? runtimeConfig.agentName;
+ const agentName = runtimeConfig.agentName ?? base.config?.agentName;
+ const agentHandle = runtimeConfig.agentHandle ?? base.config?.agentHandle;
+ const config: HostLaunchContext["config"] = {
+ ...(base.config ?? {}),
+ runtimeConfig,
+ sessionId,
+ description,
+ agentName,
+ agentHandle,
+ };
+ const standingPrompt = base.standingPrompt || buildCliSystemPrompt(config);
+ const ctx: HostLaunchContext = {
...base,
prompt,
standingPrompt,
credentialProxy: base.credentialProxy ?? this.opts.credentialProxy,
- // The latest agent:wake's launchId (tracked in `this.launchIds`) — falls
- // back to whatever `baseContextFor` set, then undefined (cliTransport's
- // own "default" fallback). Without this, every real spawn left it
- // undefined, so every launch's voucher silently collided on the same
- // "default" voucher path (see plans/fix-credential-proxy-connection-leak.md).
launchId: this.launchIds.get(agentId) ?? base.launchId,
config,
};
-
- if (!this.opts.sessionFactory && driver.createSession && !this.opts.sdkDriverDepsFor) {
- throw new Error(
- `AgentProcessManager: real spawn of "${agentId}" on in-process SDK runtime "${driver.id}" needs ` +
- "sdkDriverDepsFor — set ManagerRuntimeOpts.sdkDriverDepsFor, or pass a sessionFactory for tests.",
- );
- }
- if (!this.opts.sessionFactory && !driver.createSession && !ctx.credentialProxy) {
- throw new Error(
- `AgentProcessManager: real spawn of "${agentId}" needs a credentialProxy — ` +
- "set ManagerRuntimeOpts.credentialProxy (or baseContextFor's), or pass a sessionFactory for tests.",
- );
- }
-
- const rawLineSink = this.opts.onRuntimeRawLine;
- const session: ManagedSession = this.opts.sessionFactory
- ? this.opts.sessionFactory({ agentId, driver, ctx })
- : driver.createSession
- ? new SdkManagedSession(
- driver as Driver & { createSession: NonNullable<Driver["createSession"]> },
- ctx,
- this.opts.sdkDriverDepsFor!(ctx),
- )
- : (createChildProcessRuntimeSession(
- driver,
- ctx,
- rawLineSink ? { onRawStdoutLine: (line) => rawLineSink(agentId, line) } : undefined,
- ) as ChildProcessRuntimeSession);
-
- this.sessions.set(agentId, session);
-
- // Per-session flags.
- // - hasEstablished: has this session ever emitted its handshake
- // `runtime_event`? Once true, `error`/`exit` are session-level and
- // don't invalidate the runtime.
- // - hasReportedSpawnFailure: guards against multiple pre-establishment
- // paths reporting the SAME failure (child_process emits both `error`
- // and `exit` on ENOENT, plus `session.start().catch`). Only the FIRST
- // path to see the failure gets to name the reason — subsequent paths
- // no-op instead of clobbering a specific `ENOENT` with generic
- // `pre_handshake_exit`.
- // - suppressExitLog: set once this session's end has already been
- // logged via a more specific reason (`turn_end` for a `per_turn`
- // runtime that's about to exit on its own, or `stopped`/
- // `terminate_stalled` from `applyEffect`) so the process's eventual
- // `exit` event doesn't ALSO log a redundant/contradictory
- // "session ended" line for the same termination.
const state: ActiveSpawnState = {
agentId,
- session,
+ session: null,
+ sessionInstanceId: null,
hasEstablished: false,
hasReportedSpawnFailure: false,
suppressExitLog: false,
handshakeTimer: null,
torndown: false,
superseded: false,
- pid: null,
spawnFailureReason: null,
terminationSemantics: null,
spawnOrdinal: this.nextSpawnOrdinal++,
launchIdSnapshot: typeof ctx.launchId === "string" && ctx.launchId.length > 0 ? ctx.launchId : null,
nextTurnOrdinal: 1,
activeSpan: null,
+ pendingDeliverySpans: new Map(),
};
+ const previousOwner = this.activeSpawnState.get(agentId);
+ if (previousOwner && previousOwner !== state) {
+ previousOwner.superseded = true;
+ }
this.activeSpawnState.set(agentId, state);
const clearHandshakeTimer = () => {
- if (state.handshakeTimer) {
- clearTimeout(state.handshakeTimer);
- state.handshakeTimer = null;
- }
+ if (state.handshakeTimer) clearTimeout(state.handshakeTimer);
+ state.handshakeTimer = null;
};
const reportSpawnFailure = (
reason: string,
- opts?: { message?: string; scope?: "spawn" | "handshake_timeout" },
+ options?: { message?: string; scope?: "spawn" | "handshake_timeout" },
) => {
if (state.hasEstablished || state.hasReportedSpawnFailure) return;
state.hasReportedSpawnFailure = true;
+ state.spawnFailureReason = reason;
this.closeTurn(state, state.activeSpan, {
event: "turn_abort",
- abortCause: opts?.scope === "handshake_timeout" ? "handshake_timeout" : "spawn_failure",
+ abortCause: options?.scope === "handshake_timeout" ? "handshake_timeout" : "spawn_failure",
});
- // Record the launch-failure reason on THIS spawn's state so the exit
- // dispatch that follows can carry it into the fsm-trace (T2 — same reason
- // string the web audit below gets, so trace and audit "say the same word":
- // ENOENT / handshake_timeout / pre_handshake_exit / spawn_threw / a Node
- // error code). Lives on per-spawn `state` (fresh each doSpawn), so it can't
- // leak into a later spawn's exit — no per-agent-map read-clear needed. See
- // plans/daemon-trace-completeness-charter.md T2.
- state.spawnFailureReason = reason;
this.log.warn("spawn failed", { agentId, runtime: driver.id, reason });
this.opts.onRuntimeSpawnFailed?.(driver.id, reason);
- // Surface to the owner: a spawn that never handshakes is otherwise
- // web-silent (the runtime-health chip is per-runtime, not per-bot).
- this.emitErrorAudit(agentId, opts?.scope ?? "spawn", reason, opts?.message ?? `Launch failed (${reason})`);
+ this.emitErrorAudit(
+ agentId,
+ options?.scope ?? "spawn",
+ reason,
+ options?.message ?? `Launch failed (${reason})`,
+ );
};
-
- // Timeline entries are opened on the DATA plane (the agent's inbox pull),
- // not here — the manager only annotates the agent's latest row.
- session.on("runtime_event", (e: unknown) => {
- if (!state.hasEstablished) {
- state.hasEstablished = true;
- // The handshake arrived — disarm the watchdog.
- clearHandshakeTimer();
- }
- // Fire on every runtime_event — the router's idempotence check on
- // `markRuntimeHealthy` (status already healthy + no lastError) collapses
- // this to nothing on the wire. Firing unconditionally avoids the trap
- // where session A established, session B failed and flipped the runtime
- // unhealthy, and A's ongoing runtime_events never heal it back.
- this.opts.onRuntimeSessionEstablished?.(driver.id);
- // A `per_turn` runtime handles exactly one turn per spawn and exits on
- // its own right after (see managerPolicy's onTurnEnd) — that upcoming
- // `exit` is expected, not a new termination, so don't double-log it.
- if ((e as { kind?: string })?.kind === "turn_end" && driver.lifecycle.kind === "per_turn") {
- state.suppressExitLog = true;
- }
- // Pass THIS session's own state so the error-audit gate can tell a
- // superseded (being-killed) session's death rattle from a live session's
- // genuine error — per-session identity, not agent-level status. A reborn
- // session gets a fresh `state` with `superseded=false`, so its startup
- // error surfaces even while the agent's reset window is still open.
- this.onRuntimeEvent(agentId, e, driver.id, state);
- });
- // Only ChildProcessRuntimeSession emits `stderr`; SdkManagedSession
- // doesn't, so this is harmless when the session is an SDK adapter.
- // Runtime CLIs (Claude Code, Codex, etc.) write auth prompts, rate-limit
- // errors, panics, and network hangs here — everything the daemon's
- // stream-json parser will NEVER see. Without this line, a gated agent
- // that goes silent is a black hole; with it, the underlying error lands
- // in the main daemon log next to the `gated busy message held` line and
- // the next incident is diagnosable.
- session.on("stderr", (...args: unknown[]) => {
- const raw = typeof args[0] === "string" ? args[0] : String(args[0] ?? "");
- const text = raw.length > STDERR_LOG_MAX_LEN ? raw.slice(0, STDERR_LOG_MAX_LEN) + "…" : raw;
- this.log.warn("runtime stderr", { agentId, runtime: driver.id, text });
- });
- // Child-process `error` (ENOENT etc.) — Node EE emits this before or in
- // parallel with `exit`. Without this subscriber the raw `error` would
- // become an unhandled EE emit.
- session.on("error", (...args: unknown[]) => {
- const err = args[0] as (NodeJS.ErrnoException & { code?: string }) | undefined;
- const code = err?.code ?? "spawn_error";
- reportSpawnFailure(String(code));
- });
- session.on("exit", (...args: unknown[]) => {
+ const teardown = (result: AgentSessionResult) => {
clearHandshakeTimer();
- // Teardown-once guard: the handshake watchdog may have already torn this
- // spawn down (reported the failure, killed the process, dispatched
- // `exit`) and a fresh wake may have spawned a NEW session since. The
- // killed process's own late `exit` event must not run teardown again —
- // that would dispatch a spurious FSM `exit` that could clobber the new
- // session. NB: `stop()` (reset/model_switch/idle) deletes from
- // `this.sessions` BEFORE this exit fires, so a `this.sessions` identity
- // check would wrongly bail on that legitimate exit — guard on our own
- // per-spawn flag instead.
if (state.torndown) return;
state.torndown = true;
+ const failedStart = result.outcome === "failed_to_start";
+ if (failedStart) reportSpawnFailure(result.error.code || "failed_to_start");
+ if (!state.hasEstablished && !failedStart) reportSpawnFailure("pre_handshake_exit");
this.closeTurn(state, state.activeSpan, {
event: "turn_abort",
- abortCause: "physical_exit",
+ abortCause: failedStart ? "spawn_failure" : "physical_exit",
});
- const info = args[0] as { code?: number | null; signal?: string | null; reason?: string } | undefined;
- // A session that exits without ever emitting `runtime_event` is
- // treated as a pre-handshake failure too — covers runtimes whose
- // wrapper binary exits non-zero without a Node-level `error` event.
- // Guarded by `hasReportedSpawnFailure` so an ENOENT (already reported
- // via `error`) doesn't get overwritten with generic `pre_handshake_exit`.
- reportSpawnFailure("pre_handshake_exit");
- // `abnormal` = the RAW PHYSICAL FACT of how the process died: it wasn't a
- // deliberate stop (`reason !== "requested"`) and it left a non-zero code or
- // died on a signal. Computed UNCONDITIONALLY (not gated by
- // `hasEstablished`/`suppressExitLog`) because it feeds the fsm-trace exit
- // row (T1, plans/daemon-trace-completeness-charter.md): the trace is a
- // forensic layer that must record how a process physically terminated for
- // EVERY exit path — a hard exit (segfault/OOM/external SIGKILL) bypasses the
- // normalizer, emits no turn_end, and would otherwise be indistinguishable
- // from a clean exit in the trace. What this exit MEANS in FSM terms
- // (deliberate kill vs crash) is a SEPARATE semantic layer left to T3; T1
- // only records the physical fact and never reinterprets it.
- const exitCode = typeof info?.code === "number" ? info.code : null;
- const exitSignal = info?.signal ?? null;
- const abnormal =
- info?.reason !== "requested" && ((exitCode !== null && exitCode !== 0) || !!exitSignal);
- // Only an ESTABLISHED session "ended" — a pre-handshake exit is
- // already covered by the spawn-failed warning above. And only if this
- // termination wasn't already logged under a more specific reason (see
- // `suppressExitLog` above).
+ const exitCode = "exitCode" in result ? result.exitCode ?? null : null;
+ const exitSignal = "signal" in result ? result.signal ?? null : null;
+ const requested = "requested" in result && result.requested === true;
+ const abnormal = !requested && (exitSignal !== null || (exitCode !== null && exitCode !== 0));
if (state.hasEstablished && !state.suppressExitLog) {
this.logSessionEnded(agentId, "exit");
- // USER-FACING abnormal-exit audit. Stays STRICTLY inside the
- // `!suppressExitLog` gate — a deliberate stop (reset/nap/terminate_stalled
- // sets suppressExitLog) must NOT surface an `abnormal_exit` row in the
- // user's activity, or it re-creates the nap-noise bug (a self-initiated
- // kill showing as a fault). The `abnormal` physical fact above is shared,
- // but its user-audit sink is gated while its trace sink (below) is not.
if (abnormal) {
const detail = exitSignal ? `signal ${exitSignal}` : `code ${exitCode}`;
this.emitErrorAudit(agentId, "exit", "abnormal_exit", `Session ended unexpectedly (${detail})`);
}
}
- // Flush any reasoning block that never saw a following event before exit.
this.flushThinkingAudit(agentId);
- this.sessions.delete(agentId);
+ if (state.sessionInstanceId) {
+ this.dispatch({ type: "session_closed", agentId, sessionInstanceId: state.sessionInstanceId }, state);
+ }
+ state.pendingDeliverySpans.clear();
+ if (state.session && this.sessions.get(agentId) === state.session) this.sessions.delete(agentId);
this.liveSessions.delete(agentId);
if (this.activeSpawnState.get(agentId) === state) {
this.activeSpawnState.delete(agentId);
- // Clear a non-clean-end marker (either cause) that never saw its trailing
- // `turn_end` (a hard exit bypasses the normalizer, B1 3a) so it can't
- // leak onto the next turn. Same `=== state` guard as above: a late exit
- // from a stale/superseded spawn must NOT drop a fresh session's marker.
this.nonCleanEndMarker.delete(agentId);
}
- this.dispatch(
- { type: "exit", agentId, exitCode, exitSignal, abnormal, spawnFailureReason: state.spawnFailureReason, terminationSemantics: state.terminationSemantics },
- state,
- );
- });
-
- // Stamp the wake-prompt timestamp AT the last mile — right before the
- // driver's session sees the text — so the local-tz wall-clock the agent
- // reads reflects the moment its process is being handed the prompt, not
- // the moment the spawn effect was scheduled by the policy reducer. The
- // difference matters on cold starts where system-prompt assembly + child
- // wiring above adds tens/hundreds of ms.
- const stampedPrompt = this.stampNow(prompt);
- const startedSpan = this.openTurn(state);
- let startResult: Promise<unknown>;
- try {
- startResult = Promise.resolve(session.start({ text: stampedPrompt, sessionId: ctx.config.sessionId }));
- } catch (error) {
- this.closeTurn(state, startedSpan, { event: "turn_abort", abortCause: "start_threw" });
- throw error;
- }
- void startResult
- .then(() => {
- // A concurrent stop()/terminate_stalled can race this in-flight
- // start() and finish first — its `exit` handler above already
- // deleted this session from `this.sessions` and dispatched
- // `{type: "exit"}`. If that happened, don't ALSO dispatch `spawned`:
- // that would revive the FSM into "running" for a session nobody
- // tracks anymore, wedging the agent (its inbox already drained into
- // this now-dead spawn) until the daemon restarts.
- if (this.sessions.get(agentId) !== session) return;
- // Record the child pid now that `start()` resolved (the process exists).
- // This is the orphan-kill target of last resort for `force_exit` when
- // the session handle is later gone (batch F). A child-process session
- // exposes `.pid`; an SDK in-process session has none → stays null.
- state.pid = (session as { pid?: number }).pid ?? null;
+ this.dispatch({
+ type: "exit",
+ agentId,
+ exitCode,
+ exitSignal,
+ abnormal,
+ spawnFailureReason: state.spawnFailureReason,
+ terminationSemantics: state.terminationSemantics,
+ }, state);
+ };
+ const onEvent = (event: ManagedEvent) => {
+ if (state.torndown) return;
+ if (event.type === "session_failed" && !state.hasEstablished) {
+ reportSpawnFailure(event.error.code || "failed_to_start", { message: event.error.message });
+ }
+ if (event.type === "session_started") {
+ state.hasEstablished = true;
+ clearHandshakeTimer();
+ this.opts.onRuntimeSessionEstablished?.(driver.id);
+ }
+ this.onAgentEvent(agentId, event, driver.id, state);
+ };
+ const attach = (session: DaemonAgentSession) => {
+ if (state.torndown || this.activeSpawnState.get(agentId) !== state) {
+ void session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ return;
+ }
+ state.session = session;
+ state.sessionInstanceId = session.sessionInstanceId;
+ this.sessions.set(agentId, session);
+ this.dispatch({
+ type: "attach_session",
+ agentId,
+ sessionInstanceId: session.sessionInstanceId,
+ nowMs: this.now(),
+ }, state);
+ previousOwner?.pendingDeliverySpans.clear();
+ void (async () => {
+ try {
+ for await (const event of session.events) onEvent(event as ManagedEvent);
+ } catch (error) {
+ reportSpawnFailure("event_stream_failed", { message: String(error) });
+ }
+ })();
+ void session.closed.then(teardown, (error) => {
+ reportSpawnFailure("session_closed_rejected", { message: String(error) });
+ this.dispatch({ type: "exit", agentId, spawnFailureReason: state.spawnFailureReason }, state);
+ });
+ const startedSpan = this.openTurn(state);
+ const commandId = first.id!;
+ this.beginPendingDelivery(state, commandId, first, "idle", startedSpan, false);
+ let startResult: Promise<DeliveryReceipt>;
+ try {
+ startResult = session.start({
+ id: commandId,
+ kind: "user",
+ text: this.stampNow(prompt),
+ sequence: first.seq,
+ });
+ this.markPendingDeliveryObserved(state, commandId);
+ } catch (error) {
+ this.settlePendingDelivery(state, commandId);
+ this.closeTurn(state, startedSpan, { event: "turn_abort", abortCause: "start_threw" });
+ throw error;
+ }
+ void startResult.then((receipt) => {
+ if (this.sessions.get(agentId) !== session || state.torndown) return;
+ if (receipt?.status === "rejected") {
+ this.settlePendingDelivery(state, commandId);
+ const reason = receipt.error?.code ?? receipt.reason;
+ reportSpawnFailure(reason, { message: receipt.error?.message });
+ void session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ return;
+ }
this.dispatch({ type: "spawned", agentId, nowMs: this.now() }, state);
- // Arm the handshake watchdog. The FSM just went `running`+`turnActive`
- // optimistically (managerPolicy's `spawned`), but the process hasn't
- // proven itself — a bad model can make the CLI HANG with no exit, no
- // stderr, no stdout, so none of the subscribers above ever fire and
- // the `onTick` stall watchdog excludes an empty-inbox gated agent. If
- // no `runtime_event` arrives within the deadline, treat it as a
- // pre-handshake failure: stop the process and return the FSM to idle.
+ void (async () => {
+ for (const message of pending) {
+ if (state.torndown || this.sessions.get(agentId) !== session || this.activeSpawnState.get(agentId) !== state) {
+ return;
+ }
+ this.beginPendingDelivery(state, message.id!, message, "busy", state.activeSpan);
+ let queuedReceipt: DeliveryReceipt;
+ try {
+ const queuedResult = session.send({
+ id: message.id!,
+ kind: "user",
+ text: this.stampNow(this.withFooter(message.text)),
+ sequence: message.seq,
+ });
+ this.markPendingDeliveryObserved(state, message.id!);
+ queuedReceipt = await queuedResult;
+ } catch (error) {
+ this.settlePendingDelivery(state, message.id!);
+ if (!state.torndown && this.sessions.get(agentId) === session && this.activeSpawnState.get(agentId) === state) {
+ this.emitErrorAudit(agentId, "runtime", "send_failed", String(error));
+ void session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ }
+ return;
+ }
+ if (state.torndown || this.sessions.get(agentId) !== session || this.activeSpawnState.get(agentId) !== state) {
+ return;
+ }
+ if (queuedReceipt.status === "rejected") {
+ if (!state.pendingDeliverySpans.has(message.id!)) return;
+ this.settlePendingDelivery(state, message.id!);
+ this.emitErrorAudit(
+ agentId,
+ "runtime",
+ queuedReceipt.error?.code ?? queuedReceipt.reason,
+ queuedReceipt.error?.message ?? `Delivery rejected (${queuedReceipt.reason})`,
+ );
+ void session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ return;
+ }
+ }
+ })().catch((error) => this.emitErrorAudit(agentId, "runtime", "send_failed", String(error)));
if (state.hasEstablished || state.hasReportedSpawnFailure) return;
state.handshakeTimer = setTimeout(() => {
state.handshakeTimer = null;
- if (state.hasEstablished || state.hasReportedSpawnFailure) return;
+ if (state.hasEstablished || state.hasReportedSpawnFailure || state.torndown) return;
if (this.sessions.get(agentId) !== session) return;
- this.closeTurn(state, state.activeSpan, {
- event: "turn_abort",
- abortCause: "handshake_timeout",
- });
reportSpawnFailure("handshake_timeout", {
scope: "handshake_timeout",
message: `No response ${Math.round(this.opts.handshakeTimeoutMs / 1000)}s after launch — the runtime may be misconfigured (e.g. an invalid model).`,
});
- void Promise.resolve(session.stop({ reason: "handshake_timeout", forceAfterMs: SESSION_STOP_GRACE_MS })).catch(() => {});
- // Drop tracking + return the FSM to idle so the next wake can retry;
- // don't wait on the `exit` event, which a wedged process may never
- // emit. Mark `torndown` so the killed process's eventual late `exit`
- // is a no-op instead of a second, session-clobbering teardown.
- state.torndown = true;
- if (this.sessions.get(agentId) === session) this.sessions.delete(agentId);
- this.liveSessions.delete(agentId);
- if (this.activeSpawnState.get(agentId) === state) this.activeSpawnState.delete(agentId);
- // T2: carry the launch-failure reason (just set by reportSpawnFailure)
- // into the FSM/trace — a handshake_timeout exit is otherwise a bare
- // exit in the trace, indistinguishable from a clean one.
- this.dispatch({ type: "exit", agentId, spawnFailureReason: state.spawnFailureReason }, state);
+ state.suppressExitLog = true;
+ void session.stop({ reason: "stalled", forceAfterMs: SESSION_STOP_GRACE_MS });
}, this.opts.handshakeTimeoutMs);
- })
- .catch((err: unknown) => {
- // Synchronous throws inside driver.spawn() (e.g. child_process.spawn
- // throwing ENOENT before returning a subprocess) reach us here.
- // Same guard: whichever path saw the failure first names the reason.
- this.closeTurn(state, startedSpan, {
- event: "turn_abort",
- abortCause: "start_rejected",
- });
- const code =
- (err as { code?: string } | undefined)?.code ??
- "spawn_threw";
- reportSpawnFailure(String(code));
- if (this.sessions.get(agentId) === session) this.sessions.delete(agentId);
- // T2: carry the launch-failure reason into the FSM/trace (same as above).
- this.dispatch({ type: "exit", agentId, spawnFailureReason: state.spawnFailureReason }, state);
+ }).catch((error: unknown) => {
+ this.closeTurn(state, startedSpan, { event: "turn_abort", abortCause: "start_rejected" });
+ const code = (error as { code?: string } | undefined)?.code ?? "spawn_threw";
+ reportSpawnFailure(String(code), { message: String(error) });
});
+ };
+ const failedOpen = (error: unknown) => {
+ reportSpawnFailure(
+ (error as { code?: string } | undefined)?.code ?? "open_failed",
+ { message: String(error) },
+ );
+ if (this.activeSpawnState.get(agentId) === state) this.activeSpawnState.delete(agentId);
+ this.dispatch({ type: "exit", agentId, spawnFailureReason: state.spawnFailureReason }, state);
+ };
+ let created: ReturnType<SessionFactory>;
+ try {
+ created = this.opts.sessionFactory({
+ agentId,
+ ctx,
+ runtimeConfig,
+ });
+ } catch (error) {
+ if (this.activeSpawnState.get(agentId) === state) this.activeSpawnState.delete(agentId);
+ throw error;
+ }
+ if (created && typeof (created as Promise<DaemonAgentSession>).then === "function") {
+ void Promise.resolve(created).then(attach, failedOpen);
+ } else {
+ try {
+ attach(created as DaemonAgentSession);
+ } catch (error) {
+ failedOpen(error);
+ }
+ }
}
-
- /**
- * The model in effect for an agent's current launch (`null` = runtime
- * default), for the `model` field of an `error` audit row — so the common
- * "switched to a bad model" failure names the culprit inline. Reads the same
- * resolved launch fields `doSpawn` logs, so it reflects what was actually
- * handed to the driver.
- */
private currentModelFor(agentId: string): string | null {
- return resolveLaunchFieldsOrDefault(this.runtimeConfigs.get(agentId)).model ?? null;
+ return runtimeModelName(this.runtimeConfigs.get(agentId)) ?? null;
}
-
- /**
- * Emit an `error` audit row (launch/runtime failure the owner should see).
- * Reuses `errorDiagnostics` to classify + scrub the message. Best-effort and
- * never throws — an audit-emit failure must not cascade into the spawn/exit
- * path that called it. No-op when no audit sink is wired.
- */
private emitErrorAudit(
agentId: string,
scope: "spawn" | "runtime" | "exit" | "handshake_timeout" | "model_switch" | "reset",
@@ -1943,13 +1411,6 @@ export class AgentProcessManager {
this.log.debug("audit emit failed (error)", { agentId, err: String(err) });
}
}
-
- /**
- * Emit the buffered reasoning block as a single `thinking` audit row, then
- * clear the buffer. No-op when nothing accumulated (empty deltas were never
- * buffered). Called before any non-thinking event and on session exit so a
- * block always flushes even if the turn ends without a following tool call.
- */
private flushThinkingAudit(agentId: string): void {
const buffered = this.thinkingBuffers.get(agentId);
if (!buffered) return;
@@ -1965,70 +1426,42 @@ export class AgentProcessManager {
launchId: this.launchIds.get(agentId) ?? null,
});
} catch (err) {
- // Observational path (audit emit) — never re-throw, but leave a trail so
- // a silent failure isn't invisible if the emitter starts throwing.
this.log.debug("audit emit failed (thinking)", { agentId, err: String(err) });
}
}
-
- private onRuntimeEvent(
+ private onAgentEvent(
agentId: string,
- e: unknown,
- runtimeId: string,
- ownerOrSuperseded: ActiveSpawnState | boolean,
+ event: ManagedEvent,
+ runtimeId: BuiltinBackendId,
+ owner: ActiveSpawnState,
): void {
- const ev = e as { kind?: string; sessionId?: string; text?: string; name?: string; input?: unknown; message?: string };
- if (!ev?.kind) return;
- // Boolean is retained for the legacy direct unit seam; real subscribers
- // always pass their captured per-spawn owner.
- const owner = typeof ownerOrSuperseded === "boolean" ? undefined : ownerOrSuperseded;
- const sessionSuperseded = typeof ownerOrSuperseded === "boolean"
- ? ownerOrSuperseded
- : ownerOrSuperseded.superseded;
- // A runtime-parsed `error` event (rate limit, auth failure, bad-model API
- // error, provider outage) is otherwise web-silent — the parser sees it,
- // the FSM shrugs, and the owner learns nothing. Emit an `error` audit row
- // so it lands in the bot's activity log. `hasEstablished` is already true
- // here (this fires from the `runtime_event` subscriber), so the scope is
- // `runtime`, not `spawn`.
- //
- // EXCEPT for the death rattle of a SUPERSEDED session: an intentional kill
- // (reset / nap / model_switch) interrupts the dying process mid-turn and it
- // emits a final error `result` that is teardown noise, not a fault.
- //
- // This gates on PER-SESSION identity (`sessionSuperseded`), not the
- // agent-level `resetting` flag. Batch C keeps `resetting` true across the
- // respawn until the reborn process reaches `running`, so the reborn session
- // is LIVE while `resetting` is still set — gating the audit on `resetting`
- // would swallow the reborn session's own genuine startup error (the exact
- // "healthy signal silenced" bug this plan attacks). And status can't
- // separate them either: an old process killed while still `starting` and a
- // reborn erroring while `starting` share the same status. Only session
- // IDENTITY distinguishes them: `restartAgent` marks the OUTGOING session's
- // state `superseded` before killing it, so its rattle is suppressed; the
- // reborn session has a fresh state (`superseded=false`), so its real error
- // surfaces. See plans/daemon-fsm-desync.md batch C (reader-C fix).
- if (ev.kind === "error" && !sessionSuperseded) {
- this.emitErrorAudit(agentId, "runtime", "runtime_error", ev.message ?? "Runtime error");
- // Mark this turn non-clean (cause=runtime_error) so the trailing
- // `turn_end` (a separate normalizer event, B1) carries `endReason:"errored"`
- // + `terminationCause` + detail into the FSM/trace. Gated by the SAME
- // `!sessionSuperseded` as the audit above, so an intentional reset/nap
- // death-rattle never marks. A stall-kill's rattle also reaches here — but
- // if `killed_stalled` was already marked (the kill IS the cause), DON'T
- // downgrade it: the rattle is the kill's side effect, not the reason.
+ if (event.type === "session_closed") return;
+ if (!owner.sessionInstanceId || event.sessionInstanceId !== owner.sessionInstanceId) {
+ this.log.warn("ignored event from stale session epoch", {
+ agentId,
+ event: event.type,
+ expectedSessionInstanceId: owner.sessionInstanceId,
+ });
+ return;
+ }
+ if (
+ owner.superseded
+ && this.state.agents[agentId]?.execution.sessionInstanceId !== owner.sessionInstanceId
+ ) {
+ this.log.warn("ignored event from superseded session owner", { agentId, event: event.type });
+ return;
+ }
+ const sessionSuperseded = owner.superseded;
+ const errorMessage = event.type === "session_failed"
+ ? event.error.message
+ : event.type === "turn_completed" && event.result.outcome === "failed"
+ ? event.result.error.message
+ : undefined;
+ if (errorMessage !== undefined && !sessionSuperseded) {
+ this.emitErrorAudit(agentId, "runtime", "runtime_error", errorMessage);
if (this.nonCleanEndMarker.get(agentId)?.cause !== "killed_stalled") {
- this.nonCleanEndMarker.set(agentId, { cause: "runtime_error", detail: ev.message ?? "Runtime error" });
+ this.nonCleanEndMarker.set(agentId, { cause: "runtime_error", detail: errorMessage });
}
- // Stuck-reset correlation trace (plans/daemon-fsm-desync.md batch D):
- // PURELY ADDITIVE — this runs AFTER the error has already been decided to
- // surface (gate above unchanged), and only annotates. If this error fired
- // while the agent's reset window is wedged (`resetting` still true past
- // the reconcile threshold), leave a diagnostic line correlating the two:
- // an error emerging from a bot whose restart never converged is a
- // higher-signal event than a lone error, and the reconcile watchdog is
- // about to (or already did) escalate it. Never suppresses — a reborn's
- // genuine error keeps surfacing exactly as batch C made it.
const agent = this.state.agents[agentId];
if (
agent?.resetting &&
@@ -2038,39 +1471,25 @@ export class AgentProcessManager {
this.log.warn("runtime error during a stuck reset window", {
agentId,
resettingForMs: this.now() - agent.resettingSince,
- message: ev.message ?? "Runtime error",
+ message: errorMessage,
});
}
}
- // Bot audit hook — thinking + non-Bash tool_call, no correlation.
- // Context carries the sessionId/launchId learned so far this launch so
- // ws-do can persist them alongside each row (the plan's Data model calls
- // for both). `liveSessions` is populated on `session_init`; if this
- // event fires BEFORE the runtime has emitted its handshake, sessionId is
- // null and the row records the launch without a session id.
if (this.opts.onBotAuditEvent) {
- if (ev.kind === "thinking" && typeof ev.text === "string") {
- // Accumulate; a delta-streaming driver emits many of these per block.
- // The flush happens at the next non-thinking event / turn / exit so one
- // reasoning block becomes one audit row, not one row per token.
- if (ev.text.length > 0) {
- this.thinkingBuffers.set(agentId, (this.thinkingBuffers.get(agentId) ?? "") + ev.text);
+ if (event.type === "thinking_delta") {
+ if (event.text.length > 0) {
+ this.thinkingBuffers.set(agentId, (this.thinkingBuffers.get(agentId) ?? "") + event.text);
}
} else {
- // Any non-thinking event ends the current reasoning block — flush it
- // first so the audit log preserves thinking→action ordering.
this.flushThinkingAudit(agentId);
- if (ev.kind === "tool_call" && typeof ev.name === "string") {
- const audit = extractToolAudit(ev.name, ev.input);
+ if (event.type === "tool_started") {
+ const audit = extractToolAudit(event.name, event.input);
if (!audit.suppressed) {
const payload = audit.target !== undefined
? { name: audit.name, target: audit.target }
: { name: audit.name };
try {
- this.opts.onBotAuditEvent(agentId, {
- kind: "tool_call",
- payload,
- }, {
+ this.opts.onBotAuditEvent(agentId, { kind: "tool_call", payload }, {
sessionId: this.liveSessions.get(agentId) ?? null,
launchId: this.launchIds.get(agentId) ?? null,
});
@@ -2081,57 +1500,109 @@ export class AgentProcessManager {
}
}
}
- if (ev.kind === "session_init" && ev.sessionId) {
- this.dispatch({ type: "session", agentId, sessionId: ev.sessionId }, owner);
- this.liveSessions.set(agentId, ev.sessionId);
- this.opts.timeline?.setSession(agentId, ev.sessionId);
+ if (event.type === "session_started") {
+ this.dispatch({ type: "backend_session", agentId, sessionId: event.backendSessionId }, owner);
+ this.liveSessions.set(agentId, event.backendSessionId);
+ this.opts.timeline?.setSession(agentId, event.backendSessionId);
this.opts.onAgentSession?.({
agentId,
- sessionId: ev.sessionId,
+ sessionId: event.backendSessionId,
launchId: this.launchIds.get(agentId) ?? "",
});
- this.log.info("agent session established", { agentId, sessionId: ev.sessionId, runtime: runtimeId });
+ this.log.info("agent session established", {
+ agentId,
+ sessionId: event.backendSessionId,
+ runtime: runtimeId,
+ });
+ }
+ if (event.type === "text_delta" && event.text.length > 0) {
+ this.opts.timeline?.appendResponseToLatest(agentId, event.text);
}
- // Accumulate the agent's text output onto its latest timeline entry, so the
- // log records "what the agent said" — the basis for using it as memory.
- if (ev.kind === "text" && typeof ev.text === "string" && ev.text.length > 0) {
- this.opts.timeline?.appendResponseToLatest(agentId, ev.text);
+ if (event.type === "command_queued") this.acknowledgePendingDelivery(owner, event.commandId);
+ if (event.type === "command_accepted") this.settlePendingDelivery(owner, event.commandId, "accepted");
+ if (event.type === "command_failed") {
+ const pending = this.settlePendingDelivery(owner, event.commandId);
+ if (pending && !sessionSuperseded && this.state.agents[agentId]?.status === "running") {
+ this.closeTurn(owner, pending.span, { event: "turn_abort", abortCause: "send_threw" });
+ this.emitErrorAudit(agentId, "runtime", event.error.code, event.error.message);
+ void owner.session?.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS });
+ }
}
- // Progress for stall detection — but content-free heartbeats
- // (Claude `stream_event` / `status`, Codex raw response items) don't
- // count. They keep firing during a wedged compaction and would mask
- // a real stall from `onTick`'s watchdog. An `error` event likewise isn't
- // progress: a runtime that errors then goes quiet must still trip the
- // stall watchdog rather than reset its progress clock on the way down.
- if (ev.kind !== "internal_progress" && ev.kind !== "error") {
- this.dispatch({ type: "progress", agentId, nowMs: this.now() }, owner);
+ const rootWork = (() => {
+ switch (event.type) {
+ case "turn_started":
+ return { type: "turn_started" as const, turnId: event.turnId, commandIds: event.commandIds };
+ case "thinking_delta":
+ case "text_delta":
+ return event.text.length > 0 ? { type: "turn_work" as const, turnId: event.turnId } : null;
+ case "tool_started":
+ return { type: "turn_tool_started" as const, turnId: event.turnId };
+ case "tool_finished":
+ return { type: "turn_tool_finished" as const, turnId: event.turnId };
+ case "compaction_started":
+ case "compaction_finished":
+ case "review_started":
+ case "review_finished":
+ return { type: "turn_work" as const, turnId: event.turnId };
+ case "internal_progress":
+ return event.turnId ? { type: "turn_work" as const, turnId: event.turnId } : null;
+ default:
+ return null;
+ }
+ })();
+ if (rootWork) {
+ const wasActive = this.state.agents[agentId]?.turnActive === true;
+ this.dispatch({
+ ...rootWork,
+ agentId,
+ sessionInstanceId: event.sessionInstanceId,
+ nowMs: this.now(),
+ }, owner);
+ if (!wasActive && this.state.agents[agentId]?.turnActive && !owner.activeSpan) this.openTurn(owner);
}
- // Forward every parsed event's kind for gated-steering phase tracking
- // (tool/compaction/review boundaries). No-ops in the reducer for kinds
- // it doesn't care about, aside from the diagnostics ring buffer.
- this.dispatch({ type: "runtime_signal", agentId, kind: ev.kind, nowMs: this.now() }, owner);
- if (ev.kind === "turn_end") {
+ const signalKind = (() => {
+ switch (event.type) {
+ case "session_started": return "session_init";
+ case "thinking_delta": return "thinking";
+ case "text_delta": return "text";
+ case "tool_started": return "tool_call";
+ case "tool_finished": return "tool_output";
+ case "diagnostic": return "runtime_diagnostic";
+ case "token_usage":
+ case "rate_limits": return "telemetry";
+ case "turn_completed": return "turn_end";
+ case "session_failed": return "error";
+ case "command_queued":
+ case "command_accepted":
+ case "command_failed":
+ case "turn_started": return "internal_progress";
+ default: return event.type;
+ }
+ })();
+ this.dispatch({ type: "runtime_signal", agentId, kind: signalKind, nowMs: this.now() }, owner);
+ if (event.type === "turn_completed") {
this.logSessionEnded(agentId, "turn_end");
- // Read+clear the non-clean-end marker set this turn by a preceding runtime
- // `error` OR a `terminate_stalled` kill (B1). Present ⇒ the turn is ending
- // NON-cleanly; carry the binary judgement (`endReason:"errored"`) + the
- // cause (`terminationCause`, for B2 policy branching) + free-text detail
- // into the existing policy/audit path so onTurnEnd can tell it from a
- // clean end. The local trace projection serializes only the fixed cause;
- // it never serializes the free-text detail.
const marker = this.nonCleanEndMarker.get(agentId);
this.nonCleanEndMarker.delete(agentId);
this.dispatch(
marker !== undefined
? {
- type: "turn_end",
+ type: "turn_completed",
agentId,
+ sessionInstanceId: event.sessionInstanceId,
nowMs: this.now(),
+ turnId: event.turnId,
endReason: "errored",
terminationCause: marker.cause,
errorDetail: marker.detail,
}
- : { type: "turn_end", agentId, nowMs: this.now() },
+ : {
+ type: "turn_completed",
+ agentId,
+ sessionInstanceId: event.sessionInstanceId,
+ nowMs: this.now(),
+ turnId: event.turnId,
+ },
owner,
);
}
diff --git a/src/daemon/src/manager/managerSwitchModel.test.ts b/src/daemon/src/manager/managerSwitchModel.test.ts
index 39dafecc5..d66b8d722 100644
--- a/src/daemon/src/manager/managerSwitchModel.test.ts
+++ b/src/daemon/src/manager/managerSwitchModel.test.ts
@@ -1,8 +1,10 @@
import { describe, it, expect, vi } from "vitest";
-import { AgentProcessManager, type ManagedSession, type SessionFactory, type TimelineRecorder } from "./managerRuntime.js";
-import type { Driver, LaunchContext } from "../types.js";
+import { AgentProcessManager, type DaemonAgentSession, type SessionFactory, type TimelineRecorder } from "./managerRuntime.js";
+import type { AgentBackend as Driver } from "../drivers/index.js";
+import type { HostLaunchContext as LaunchContext } from "./hostContext.js";
import type { RuntimeConfig } from "../runtimeConfig.js";
import type { Logger } from "../logger.js";
+import type { AgentEvent, AgentSessionResult, BuiltinBackendSpecs } from "@alook/agent-driver";
function stubLogger(): Logger & { calls: Record<"debug" | "info" | "warn" | "error", Array<[string, unknown[]]>> } {
const calls: Record<"debug" | "info" | "warn" | "error", Array<[string, unknown[]]>> = { debug: [], info: [], warn: [], error: [] };
@@ -31,22 +33,79 @@ function fakeDriver(id: string): Driver {
} as unknown as Driver;
}
-interface FakeSession extends ManagedSession {
- fire(evt: string, ...args: unknown[]): void;
+interface FakeSession extends DaemonAgentSession {
+ fire(evt: string, ...args: unknown[]): Promise<void>;
}
function fakeSession(): FakeSession {
- const listeners = new Map<string, Array<(...a: unknown[]) => void>>();
+ type Event = AgentEvent<BuiltinBackendSpecs, "codex">;
+ const queued: Event[] = [];
+ const waiters: Array<(value: IteratorResult<Event>) => void> = [];
+ const publish = (event: Event) => {
+ const waiter = waiters.shift();
+ if (waiter) waiter({ done: false, value: event });
+ else queued.push(event);
+ };
+ let sequence = 0;
+ let resolveClosed!: (result: AgentSessionResult) => void;
+ const closed = new Promise<AgentSessionResult>((resolve) => { resolveClosed = resolve; });
const s: FakeSession = {
- on(event, cb) {
- const arr = listeners.get(event) ?? [];
- arr.push(cb);
- listeners.set(event, arr);
+ backend: "codex",
+ capabilities: {} as FakeSession["capabilities"],
+ sessionInstanceId: "switch-model-test",
+ events: {
+ maxBufferedBytes: 4_194_304,
+ [Symbol.asyncIterator]() {
+ return {
+ next: () => queued.length > 0
+ ? Promise.resolve({ done: false as const, value: queued.shift()! })
+ : new Promise<IteratorResult<Event>>((resolve) => waiters.push(resolve)),
+ };
+ },
+ },
+ closed,
+ async start(message) {
+ return { status: "accepted", delivery: "prompt", commandId: message.id, turnId: "test-turn" };
+ },
+ async send(message) {
+ return { status: "accepted", delivery: "steer", commandId: message.id, turnId: "test-turn" };
+ },
+ async interrupt() { return { status: "not_running" }; },
+ async stop() { return { status: "accepted", requestId: "test-stop" }; },
+ snapshot() {
+ return { sessionInstanceId: "switch-model-test", state: "working", queuedCommands: [], lastEventSequence: sequence };
+ },
+ async invokeExtension() {
+ return { ok: false, error: { category: "internal", code: "unsupported", message: "unsupported", retryable: false } };
+ },
+ async fire(evt, ...args) {
+ if (evt === "runtime_event") {
+ const event = args[0] as { kind: string; sessionId?: string };
+ if (event.kind === "session_init") {
+ publish({
+ type: "session_started",
+ backendSessionId: event.sessionId ?? "test-session",
+ sequence: ++sequence,
+ sessionInstanceId: "switch-model-test",
+ at: Date.now(),
+ });
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ return;
+ }
+ if (evt === "exit") {
+ const result: AgentSessionResult = {
+ outcome: "stopped",
+ requested: true,
+ exitCode: 0,
+ signal: null,
+ cleanup: { status: "released" },
+ };
+ resolveClosed(result);
+ }
+ await Promise.resolve();
+ await Promise.resolve();
},
- start() { return Promise.resolve(); },
- send() {},
- stop() {},
- get currentSessionId() { return null; },
- fire(evt, ...args) { for (const cb of listeners.get(evt) ?? []) cb(...args); },
};
return s;
}
@@ -67,7 +126,7 @@ function makeManager(
const spawns: Array<{ ctx: LaunchContext; prompt: string }> = [];
let session = fakeSession();
const sessions: FakeSession[] = [];
- const factory: SessionFactory = ({ ctx }: { ctx: LaunchContext }) => {
+ const factory: SessionFactory = ({ ctx }) => {
spawns.push({ ctx, prompt: ctx.prompt });
session = fakeSession();
sessions.push(session);
@@ -117,11 +176,11 @@ describe("AgentProcessManager.switchModel", () => {
// First spawn + establish a session id.
mgr.deliver("a1", { seq: 1, text: "hi" });
expect(spawns).toHaveLength(1);
- getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-123" });
+ await getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-123" });
// Switch while live. stop() → onExit drain → single respawn.
await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l2", rewakePrompt: REWAKE });
- getSession().fire("exit");
+ await getSession().fire("exit");
// Exactly two spawns total (initial + one respawn).
expect(spawns).toHaveLength(2);
@@ -137,7 +196,8 @@ describe("AgentProcessManager.switchModel", () => {
const { mgr, spawns, getSession } = makeManager();
mgr.register("a1");
mgr.deliver("a1", { seq: 1, text: "hi" });
- getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-1" });
+ await Promise.resolve();
+ await getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-1" });
expect(spawns).toHaveLength(1);
await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l2", rewakePrompt: REWAKE });
@@ -145,11 +205,11 @@ describe("AgentProcessManager.switchModel", () => {
mgr.deliver("a1", { seq: 2, text: "new unread" });
expect(spawns).toHaveLength(1);
// The exit drain produces exactly one respawn for the queued rewake + unread.
- getSession().fire("exit");
+ await getSession().fire("exit");
expect(spawns).toHaveLength(2);
});
- it("idle-branch synchronous spawn throw dispatches exit and clears the resetting gate", () => {
+ it("idle-branch synchronous spawn throw dispatches exit and clears the resetting gate", async () => {
const logger = stubLogger();
let firstSpawn = true;
const factory: SessionFactory = () => {
@@ -174,7 +234,7 @@ describe("AgentProcessManager.switchModel", () => {
logger,
});
mgr.register("a1");
- expect(() =>
+ await expect(
mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l1", rewakePrompt: REWAKE }),
).rejects.toThrow(/spawn boom/);
// The gate must have cleared (exit dispatched) — a subsequent wake spawns.
@@ -209,7 +269,10 @@ describe("AgentProcessManager.switchModel", () => {
forgetSession: (a) => timelineCalls.push(`forget:${a}`),
};
let session = fakeSession();
- const factory: SessionFactory = () => (session = fakeSession());
+ const factory: SessionFactory = () => {
+ session = fakeSession();
+ return session;
+ };
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
baseContextFor: () => ({
@@ -226,9 +289,9 @@ describe("AgentProcessManager.switchModel", () => {
});
mgr.register("a1");
mgr.deliver("a1", { seq: 1, text: "hi" });
- session.fire("runtime_event", { kind: "session_init", sessionId: "sess-live" });
+ await session.fire("runtime_event", { kind: "session_init", sessionId: "sess-live" });
await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l2", rewakePrompt: REWAKE });
- session.fire("exit");
+ await session.fire("exit");
// forgetSession — the writer of the reset_session barrier — must never run.
expect(timelineCalls.some((c) => c.startsWith("forget:"))).toBe(false);
});
@@ -238,7 +301,7 @@ describe("AgentProcessManager.switchModel", () => {
// respawn still emits session_init AND threads the switch's launchId into
// onAgentSession. Driver-side: resume already yields session_init
// (codex.test "delivers the prompt on resume too"; cursor system/init;
- // SdkRuntimeSession.emitEvents first-event). This pins the manager half.
+ // the SDK lane's first typed event). This pins the manager half.
it("after switchModel respawn, session_init emits onAgentSession with the switch launchId (not the prior wake's)", async () => {
const sessionsSeen: Array<{ agentId: string; sessionId: string; launchId: string }> = [];
const { mgr, getSession } = makeManager({
@@ -246,15 +309,15 @@ describe("AgentProcessManager.switchModel", () => {
});
mgr.register("a1", { launchId: "wake-l1" });
mgr.deliver("a1", { seq: 1, text: "hi" });
- getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-123" });
+ await getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-123" });
expect(sessionsSeen).toEqual([
{ agentId: "a1", sessionId: "sess-123", launchId: "wake-l1" },
]);
await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "switch-l2", rewakePrompt: REWAKE });
- getSession().fire("exit");
+ await getSession().fire("exit");
// Respawn is live; driver resume path emits session_init again (same or new id).
- getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-123" });
+ await getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-123" });
expect(sessionsSeen).toHaveLength(2);
expect(sessionsSeen[1]).toEqual({
@@ -270,7 +333,7 @@ describe("AgentProcessManager.switchModel", () => {
onAgentSession: (info) => sessionsSeen.push(info),
});
await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "switch-l1", rewakePrompt: REWAKE });
- getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-new" });
+ await getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-new" });
expect(sessionsSeen).toEqual([
{ agentId: "a1", sessionId: "sess-new", launchId: "switch-l1" },
]);
diff --git a/src/daemon/src/manager/managerTimeline.test.ts b/src/daemon/src/manager/managerTimeline.test.ts
index 79b53e77e..6e9f712ef 100644
--- a/src/daemon/src/manager/managerTimeline.test.ts
+++ b/src/daemon/src/manager/managerTimeline.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect } from "vitest";
import { AgentProcessManager, type TimelineRecorder } from "./managerRuntime";
-import type { LaunchContext } from "../types";
+import type { HostLaunchContext as LaunchContext } from "./hostContext.js";
+import type { AgentEvent, AgentSessionResult, BuiltinBackendSpecs } from "@alook/agent-driver";
/** A recorder that records calls + can supply a resume session id. */
function fakeRecorder(resume: Record<string, string> = {}) {
@@ -15,7 +16,17 @@ function fakeRecorder(resume: Record<string, string> = {}) {
}
function manager(rec: TimelineRecorder, capture: { ctx?: LaunchContext }) {
- const handlers: Record<string, ((arg?: unknown) => void)[]> = {};
+ type Event = AgentEvent<BuiltinBackendSpecs, "codex">;
+ const queued: Event[] = [];
+ const waiters: Array<(value: IteratorResult<Event>) => void> = [];
+ let resolveClosed!: (result: AgentSessionResult) => void;
+ const closed = new Promise<AgentSessionResult>((resolve) => { resolveClosed = resolve; });
+ let sequence = 0;
+ const publish = (event: Event) => {
+ const waiter = waiters.shift();
+ if (waiter) waiter({ done: false, value: event });
+ else queued.push(event);
+ };
const mgr = new AgentProcessManager({
driverFor: () =>
({ lifecycle: { kind: "persistent", stdin: "gated", inFlightWake: "queue" } }) as never,
@@ -23,37 +34,70 @@ function manager(rec: TimelineRecorder, capture: { ctx?: LaunchContext }) {
sessionFactory: ({ ctx }) => {
capture.ctx = ctx;
return {
- on: (ev: string, cb: (arg?: unknown) => void) => ((handlers[ev] ??= []).push(cb)),
- get currentSessionId() {
- return null;
+ backend: "codex" as const,
+ capabilities: {} as never,
+ sessionInstanceId: "timeline-test",
+ events: {
+ maxBufferedBytes: 4_194_304 as const,
+ [Symbol.asyncIterator]() {
+ return {
+ next: () => queued.length > 0
+ ? Promise.resolve({ done: false as const, value: queued.shift()! })
+ : new Promise<IteratorResult<Event>>((resolve) => waiters.push(resolve)),
+ };
+ },
+ },
+ closed,
+ async start(message: { id: string }) {
+ return { status: "accepted" as const, delivery: "prompt" as const, commandId: message.id, turnId: "test-turn" };
},
- async start() {},
- send() {
- return { ok: true };
+ async send(message: { id: string }) {
+ return { status: "accepted" as const, delivery: "steer" as const, commandId: message.id, turnId: "test-turn" };
+ },
+ async interrupt() { return { status: "not_running" as const }; },
+ async stop() { return { status: "accepted" as const, requestId: "test-stop" }; },
+ snapshot() {
+ return { sessionInstanceId: "timeline-test", state: "working" as const, queuedCommands: [], lastEventSequence: sequence };
+ },
+ async invokeExtension() {
+ return { ok: false as const, error: { category: "internal" as const, code: "unsupported", message: "unsupported", retryable: false } };
},
- async stop() {},
};
},
timeline: rec,
tickIntervalMs: 10_000,
});
- const emit = (ev: string, arg?: unknown) => (handlers[ev] ?? []).forEach((h) => h(arg));
+ const emit = async (ev: string, arg?: unknown) => {
+ if (ev === "runtime_event") {
+ const event = arg as { kind: string; sessionId?: string; text?: string };
+ const base = { sequence: ++sequence, sessionInstanceId: "timeline-test", at: Date.now() };
+ if (event.kind === "session_init") {
+ publish({ ...base, type: "session_started", backendSessionId: event.sessionId ?? "test-session" });
+ } else if (event.kind === "text") {
+ publish({ ...base, type: "text_delta", turnId: "test-turn", text: event.text ?? "" });
+ }
+ } else if (ev === "exit") {
+ resolveClosed({ outcome: "crashed", requested: false, exitCode: 0, signal: null, cleanup: { status: "released" } });
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ };
return { mgr, emit };
}
describe("manager ↔ timeline (daily log + resume)", () => {
- it("annotates the latest entry on session_init / text / exit (by agent, not task id)", () => {
+ it("annotates the latest entry on session_init / text / exit (by agent, not task id)", async () => {
const { rec, calls } = fakeRecorder();
const cap: { ctx?: LaunchContext } = {};
const { mgr, emit } = manager(rec, cap);
mgr.register("agent_1");
mgr.deliver("agent_1", { seq: 1, text: "hi" });
- emit("runtime_event", { kind: "session_init", sessionId: "sess-7" });
- emit("runtime_event", { kind: "text", text: "part 1" });
- emit("runtime_event", { kind: "text", text: "part 2" });
- emit("runtime_event", { kind: "text", text: "" }); // empty text ignored
- emit("exit");
+ await emit("runtime_event", { kind: "session_init", sessionId: "sess-7" });
+ await emit("runtime_event", { kind: "text", text: "part 1" });
+ await emit("runtime_event", { kind: "text", text: "part 2" });
+ await emit("runtime_event", { kind: "text", text: "" }); // empty text ignored
+ await emit("exit");
// The manager does NOT open the entry (that's the data plane / inbox pull)
// and there's no status close — it records the session id and accumulates the
@@ -134,7 +178,7 @@ describe("manager.resetSession", () => {
// Track handlers/sends per session; a new session is created on each spawn.
const sessionsCreated: Array<{
ctx: LaunchContext;
- handlers: Record<string, ((arg?: unknown) => void)[]>;
+ finish: (result: AgentSessionResult) => void;
stopCalled: boolean;
sends: Array<{ text: string; mode: string }>;
}> = [];
@@ -143,20 +187,36 @@ describe("manager.resetSession", () => {
({ lifecycle: { kind: "persistent", stdin: "direct", inFlightWake: "steer" } }) as never,
baseContextFor: (agentId) => ({ agentId, workingDirectory: "/tmp/x", standingPrompt: "", config: {} }),
sessionFactory: ({ ctx }) => {
- const entry: (typeof sessionsCreated)[number] = { ctx, handlers: {}, stopCalled: false, sends: [] };
+ let finish!: (result: AgentSessionResult) => void;
+ const closed = new Promise<AgentSessionResult>((resolve) => { finish = resolve; });
+ const entry: (typeof sessionsCreated)[number] = { ctx, finish: (result) => finish(result), stopCalled: false, sends: [] };
sessionsCreated.push(entry);
return {
- on: (ev: string, cb: (arg?: unknown) => void) => ((entry.handlers[ev] ??= []).push(cb)),
- get currentSessionId() {
- return null;
+ backend: "codex" as const,
+ capabilities: {} as never,
+ sessionInstanceId: `reset-test-${sessionsCreated.length}`,
+ events: {
+ maxBufferedBytes: 4_194_304 as const,
+ async *[Symbol.asyncIterator]() { await new Promise(() => {}); },
+ },
+ closed,
+ async start(m: { id: string }) {
+ return { status: "accepted" as const, delivery: "prompt" as const, commandId: m.id, turnId: "test-turn" };
},
- async start() {},
- send(m: { text: string; mode: "busy" | "idle" }) {
+ async send(m: { id: string; text: string }) {
entry.sends.push({ text: m.text, mode: m.mode });
- return { ok: true };
+ return { status: "accepted" as const, delivery: "steer" as const, commandId: m.id, turnId: "test-turn" };
},
+ async interrupt() { return { status: "not_running" as const }; },
async stop() {
entry.stopCalled = true;
+ return { status: "accepted" as const, requestId: "test-stop" };
+ },
+ snapshot() {
+ return { sessionInstanceId: "reset-test", state: "working" as const, queuedCommands: [], lastEventSequence: 0 };
+ },
+ async invokeExtension() {
+ return { ok: false as const, error: { category: "internal" as const, code: "unsupported", message: "unsupported", retryable: false } };
},
};
},
@@ -192,7 +252,8 @@ describe("manager.resetSession", () => {
expect(mgr.snapshot().agents.agent_run.inbox.map((m) => m.text)).toEqual(["REWAKE"]);
// Fire the session exit → onExit drains rewake into a fresh spawn.
- first.handlers["exit"]!.forEach((h) => h());
+ first.finish({ outcome: "stopped", requested: true, exitCode: 0, signal: null, cleanup: { status: "released" } });
+ await Promise.resolve();
await Promise.resolve();
expect(sessionsCreated).toHaveLength(2);
diff --git a/src/daemon/src/manager/rootLeaseIntegration.test.ts b/src/daemon/src/manager/rootLeaseIntegration.test.ts
new file mode 100644
index 000000000..ad14eed66
--- /dev/null
+++ b/src/daemon/src/manager/rootLeaseIntegration.test.ts
@@ -0,0 +1,128 @@
+import { EventEmitter } from "node:events";
+import { PassThrough } from "node:stream";
+import { describe, expect, it, vi } from "vitest";
+import type { ChildProcess } from "node:child_process";
+import type { BuiltinBackendSpecs, PreparedExecutionResource } from "@alook/agent-driver";
+import { createBuiltinAgentDriverRegistry } from "@alook/agent-driver/adapter-author";
+import { createFakeAgentDriverHost } from "@alook/agent-driver/testing";
+import { CodexDriver } from "../../agent-driver/src/adapters/codex/index.js";
+import { LogicalAgentSession } from "../../agent-driver/src/controller/logical-session.js";
+import { AgentProcessManager } from "./managerRuntime.js";
+import type { HostLaunchContext } from "./hostContext.js";
+
+function fakeProcess() {
+ return Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ stdin: new PassThrough(),
+ pid: undefined,
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn(() => true),
+ }) as unknown as ChildProcess & { stdout: PassThrough; stderr: PassThrough; stdin: PassThrough };
+}
+
+async function flushEvents(): Promise<void> {
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ await Promise.resolve();
+}
+
+describe("raw adapter → public session → manager root lease", () => {
+ it("contains a false terminal, ignores unowned work/duplicates, and permits a proven re-close", async () => {
+ let now = 0;
+ const adapter = new CodexDriver();
+ const childProcess = fakeProcess();
+ vi.spyOn(adapter, "spawn").mockResolvedValue({ process: childProcess });
+ const host = createFakeAgentDriverHost();
+ const prepared: PreparedExecutionResource = {
+ environmentLayers: {
+ base: {}, hostStatic: {}, identityProtected: {}, platformProtected: {},
+ runtimeProtected: {}, networkProtected: {}, credentialSensitive: {},
+ },
+ async release() {},
+ };
+ const session = new LogicalAgentSession<BuiltinBackendSpecs, "codex">(
+ "codex",
+ { model: { kind: "default" }, mode: "default" },
+ { workingDirectory: process.cwd(), instructions: "", launchId: "integration" },
+ adapter,
+ createBuiltinAgentDriverRegistry().get("codex").capabilities,
+ host,
+ prepared,
+ 100,
+ );
+ const trace: Array<{ event?: string; recordKind?: string }> = [];
+ const manager = new AgentProcessManager({
+ driverFor: () => ({ id: "codex" }),
+ baseContextFor: () => ({
+ workingDirectory: process.cwd(),
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as HostLaunchContext["config"],
+ credentialProxy: {} as HostLaunchContext["credentialProxy"],
+ }),
+ sessionFactory: () => session,
+ now: () => now,
+ onFsmTransition: (row) => trace.push(row),
+ });
+ const raw = async (method: string, params: unknown) => {
+ childProcess.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
+ await flushEvents();
+ };
+
+ manager.register("a1");
+ manager.deliver("a1", { id: "command-one", text: "work" });
+ await flushEvents();
+ childProcess.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: 2, result: { thread: { id: "root-thread" } } })}\n`);
+ await raw("turn/started", {
+ threadId: "root-thread",
+ turn: { id: "root-vendor-turn", status: "inProgress" },
+ });
+ const turnId = session.snapshot().activeTurn?.turnId;
+ expect(turnId).toBeTruthy();
+ expect(manager.snapshot().agents.a1.execution.lease).toMatchObject({ state: "active", identity: { turnId } });
+
+ now = 10;
+ await raw("turn/completed", {
+ threadId: "root-thread",
+ turn: { id: "root-vendor-turn", status: "completed" },
+ });
+ expect(manager.snapshot().agents.a1).toMatchObject({ idleSince: 10, turnActive: false });
+
+ now = 20;
+ await raw("turn/completed", {
+ threadId: "root-thread",
+ turn: { id: "root-vendor-turn", status: "completed" },
+ });
+ await raw("rawResponseItem/completed", { threadId: "child-thread", turnId: "root-vendor-turn" });
+ await raw("rawResponseItem/completed", { threadId: "root-thread", turnId: "stale-turn" });
+ expect(manager.snapshot().agents.a1).toMatchObject({ idleSince: 10, turnActive: false });
+
+ now = 30;
+ await raw("rawResponseItem/completed", { threadId: "root-thread", turnId: "root-vendor-turn" });
+ expect(manager.snapshot().agents.a1.execution.lease).toMatchObject({
+ state: "suspect_active",
+ identity: { sessionInstanceId: session.sessionInstanceId, turnId },
+ reason: "work_after_terminal",
+ });
+ expect(manager.snapshot().agents.a1.idleSince).toBeNull();
+
+ now = 40;
+ await raw("turn/completed", {
+ threadId: "root-thread",
+ turn: { id: "root-vendor-turn", status: "completed" },
+ });
+ await raw("turn/completed", {
+ threadId: "root-thread",
+ turn: { id: "root-vendor-turn", status: "completed" },
+ });
+ expect(manager.snapshot().agents.a1.execution.lease).toMatchObject({
+ state: "none",
+ lastTerminal: { identity: { turnId }, at: 40 },
+ });
+ expect(trace.filter((row) => row.event === "turn_end" && row.recordKind === "fsm"))
+ .toHaveLength(2);
+
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ });
+});
diff --git a/src/daemon/src/manager/wakeCoordinator.test.ts b/src/daemon/src/manager/wakeCoordinator.test.ts
index c622b7687..90993b9a7 100644
--- a/src/daemon/src/manager/wakeCoordinator.test.ts
+++ b/src/daemon/src/manager/wakeCoordinator.test.ts
@@ -31,20 +31,238 @@ describe("WakeCoordinator", () => {
await expect(first).resolves.toEqual({ state: "accepted" });
});
- it("coalesces seq 5 to 6 during active work and pull coverage prevents an idle rewake", async () => {
+ it("delivers the first higher watermark into an active agent after the prior wake was seen", async () => {
+ const coordinator = new WakeCoordinator();
+ const dispatch = vi.fn(async (command: Wake) => {
+ coordinator.recordDeliveryAck(command.agentId, command.launchId, "ok");
+ });
+
+ await coordinator.run(wake("a1", "/s/c", 1), dispatch);
+ coordinator.recordAgentActivity("a1", "running");
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#1" }], 0);
+
+ await expect(coordinator.run(wake("a1", "/s/c", 2), dispatch)).resolves.toEqual({ state: "accepted" });
+ expect(dispatch.mock.calls.map(([command]) => command.unreadNotice.latestSeq)).toEqual([1, 2]);
+ });
+
+ it("coalesces a five-message busy burst into one active-agent delivery until the pull covers it", async () => {
+ const coordinator = new WakeCoordinator();
+ const dispatch = vi.fn(async (command: Wake) => {
+ coordinator.recordDeliveryAck(command.agentId, command.launchId, "ok");
+ });
+
+ await coordinator.run(wake("a1", "/s/c", 1), dispatch);
+ coordinator.recordAgentActivity("a1", "running");
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#1" }], 0);
+
+ await expect(coordinator.run(wake("a1", "/s/c", 2), dispatch)).resolves.toEqual({ state: "accepted" });
+ for (let seq = 3; seq <= 6; seq++) {
+ await expect(coordinator.run(wake("a1", "/s/c", seq), dispatch)).resolves.toMatchObject({
+ state: "suppressed",
+ });
+ }
+ expect(dispatch.mock.calls.map(([command]) => command.unreadNotice.latestSeq)).toEqual([1, 2]);
+
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#6" }], 0);
+ await tick();
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it("re-arms one active delivery when a pull covers the admitted wake but not a newer desired watermark", async () => {
+ const coordinator = new WakeCoordinator();
+ const dispatch = vi.fn(async (command: Wake) => {
+ coordinator.recordDeliveryAck(command.agentId, command.launchId, "ok");
+ });
+
+ await coordinator.run(wake("a1", "/s/c", 1), dispatch);
+ coordinator.recordAgentActivity("a1", "running");
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#1" }], 0);
+ await coordinator.run(wake("a1", "/s/c", 2), dispatch);
+ await coordinator.run(wake("a1", "/s/c", 3), dispatch);
+ expect(dispatch.mock.calls.map(([command]) => command.unreadNotice.latestSeq)).toEqual([1, 2]);
+
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#2" }], 0);
+ await tick();
+ expect(dispatch.mock.calls.map(([command]) => command.unreadNotice.latestSeq)).toEqual([1, 2, 3]);
+ });
+
+ it("keeps a later channel covered when the active reminder pull observes only an earlier channel", async () => {
+ const coordinator = new WakeCoordinator();
+ const dispatch = vi.fn(async (command: Wake) => {
+ coordinator.recordDeliveryAck(command.agentId, command.launchId, "ok");
+ });
+
+ await coordinator.run(wake("a1", "/s/root", 1), dispatch);
+ coordinator.recordAgentActivity("a1", "running");
+ coordinator.recordModelSeen("a1", [{ channel: "/s/root", seq: "#1" }], 0);
+
+ await coordinator.run(wake("a1", "/s/c1", 2), dispatch);
+ await coordinator.run(wake("a1", "/s/c2", 7), dispatch);
+ expect(dispatch.mock.calls.map(([command]) => command.unreadNotice.channel)).toEqual(["/s/root", "/s/c1"]);
+
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c1", seq: "#2" }], 0);
+ await tick();
+ expect(dispatch.mock.calls.map(([command]) => command.unreadNotice.channel)).toEqual([
+ "/s/root",
+ "/s/c1",
+ "/s/c2",
+ ]);
+ });
+
+ it("re-arms an unseen channel when a multi-channel admission pull observes only its sibling", async () => {
+ const coordinator = new WakeCoordinator();
+ let releaseInitial!: () => void;
+ const initialBlocked = new Promise<void>((resolve) => { releaseInitial = resolve; });
+ const dispatch = vi.fn(async (command: Wake) => {
+ coordinator.recordDeliveryAck(command.agentId, command.launchId, "ok");
+ if (command.launchId === "initial") await initialBlocked;
+ });
+
+ const initial = coordinator.run(wake("a1", "/s/root", 1, "initial"), dispatch);
+ await tick();
+ await coordinator.run(wake("a1", "/s/c1", 2, "c1"), dispatch);
+ await coordinator.run(wake("a1", "/s/c2", 7, "c2"), dispatch);
+ coordinator.recordModelSeen("a1", [{ channel: "/s/root", seq: "#1" }], 0);
+ releaseInitial();
+ await initial;
+
+ expect(dispatch.mock.calls.map(([command]) => command.unreadNotice.channel)).toEqual([
+ "/s/root",
+ "/s/c2",
+ ]);
+
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c1", seq: "#2" }], 0);
+ await tick();
+ expect(dispatch.mock.calls.map(([command]) => command.unreadNotice.channel)).toEqual([
+ "/s/root",
+ "/s/c2",
+ "/s/c2",
+ ]);
+
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c2", seq: "#7" }], 0);
+ await tick();
+ expect(dispatch).toHaveBeenCalledTimes(3);
+ });
+
+ it("replaces a failed working delivery without dropping the runtime-active lane", async () => {
+ const coordinator = new WakeCoordinator();
+ const dispatch = vi.fn(async (command: Wake) => {
+ if (command.launchId === "initial") coordinator.recordDeliveryAck("a1", "initial", "ok");
+ });
+
+ await coordinator.run(wake("a1", "/s/c", 1, "initial"), dispatch);
+ coordinator.recordAgentActivity("a1", "running");
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#1" }], 0);
+
+ await coordinator.run(wake("a1", "/s/c", 2, "working_failed"), dispatch);
+ await coordinator.run(wake("a1", "/s/c", 3, "working_replacement"), dispatch);
+ coordinator.recordDeliveryAck("a1", "working_failed", "error");
+ await tick();
+
+ expect(dispatch.mock.calls.map(([command]) => command.launchId)).toEqual([
+ "initial",
+ "working_failed",
+ "working_replacement",
+ ]);
+ });
+
+ it("reconciles a pending active wake when model-seen beats the delivery ack", async () => {
const coordinator = new WakeCoordinator();
const dispatch = vi.fn(async () => {});
- await coordinator.run(wake("a1", "/s/c", 5), dispatch);
+
+ await coordinator.run(wake("a1", "/s/c", 1, "launch_1"), dispatch);
+ coordinator.recordAgentActivity("a1", "running");
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#1" }], 0);
+ await coordinator.run(wake("a1", "/s/c", 2, "launch_2"), dispatch);
+ expect(dispatch.mock.calls.map(([command]) => command.launchId)).toEqual(["launch_1"]);
+
+ coordinator.recordDeliveryAck("a1", "launch_1", "ok");
+ await tick();
+ expect(dispatch.mock.calls.map(([command]) => command.launchId)).toEqual(["launch_1", "launch_2"]);
+ });
+
+ it("lets the first reminder pull cover a higher pre-observation burst even when its ack is delayed", async () => {
+ const coordinator = new WakeCoordinator();
+ const dispatch = vi.fn(async () => {});
+ await coordinator.run(wake("a1", "/s/c", 5, "initial"), dispatch);
await coordinator.run(wake("a1", "/s/c", 6), dispatch);
expect(dispatch).toHaveBeenCalledTimes(1);
const generation = coordinator.modelSeenGeneration("a1");
expect(coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#6" }], generation)).toBe(true);
+ coordinator.recordDeliveryAck("a1", "initial", "ok");
coordinator.recordAgentActivity("a1", "idle");
await tick();
expect(dispatch).toHaveBeenCalledTimes(1);
});
+ it("does not strand an acknowledged but unobserved admission across idle", async () => {
+ const coordinator = new WakeCoordinator();
+ const dispatch = vi.fn(async (command: Wake) => {
+ coordinator.recordDeliveryAck(command.agentId, command.launchId, "ok");
+ });
+
+ await coordinator.run(wake("a1", "/s/c", 5, "initial"), dispatch);
+ coordinator.recordAgentActivity("a1", "idle");
+ await tick();
+ await coordinator.run(wake("a1", "/s/c", 5, "durable_retry"), dispatch);
+ await tick();
+
+ expect(dispatch).toHaveBeenCalledTimes(2);
+
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#5" }], 0);
+ coordinator.recordAgentActivity("a1", "idle");
+ await tick();
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not strand an unobserved admission when idle precedes its delivery ack", async () => {
+ const coordinator = new WakeCoordinator();
+ let releaseInitial!: () => void;
+ const initialBlocked = new Promise<void>((resolve) => { releaseInitial = resolve; });
+ const dispatch = vi.fn(async (command: Wake) => {
+ if (command.launchId === "initial") await initialBlocked;
+ coordinator.recordDeliveryAck(command.agentId, command.launchId, "ok");
+ });
+
+ const initial = coordinator.run(wake("a1", "/s/c", 5, "initial"), dispatch);
+ await tick();
+ coordinator.recordAgentActivity("a1", "idle");
+ releaseInitial();
+ await initial;
+ await coordinator.run(wake("a1", "/s/c", 5, "durable_retry"), dispatch);
+ await tick();
+
+ expect(dispatch).toHaveBeenCalledTimes(2);
+
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#5" }], 0);
+ coordinator.recordAgentActivity("a1", "idle");
+ await tick();
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it("promotes a same-watermark replacement already coalesced before idle", async () => {
+ const coordinator = new WakeCoordinator();
+ const dispatch = vi.fn(async (command: Wake) => {
+ coordinator.recordDeliveryAck(command.agentId, command.launchId, "ok");
+ });
+
+ await coordinator.run(wake("a1", "/s/c", 5, "initial"), dispatch);
+ await coordinator.run(wake("a1", "/s/c", 5, "durable_retry"), dispatch);
+ coordinator.recordAgentActivity("a1", "idle");
+ await tick();
+
+ expect(dispatch.mock.calls.map(([command]) => command.launchId)).toEqual([
+ "initial",
+ "durable_retry",
+ ]);
+
+ coordinator.recordModelSeen("a1", [{ channel: "/s/c", seq: "#5" }], 0);
+ coordinator.recordAgentActivity("a1", "idle");
+ await tick();
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
it("suppresses an old wake when inbox pull arrived first", async () => {
const coordinator = new WakeCoordinator();
const dispatch = vi.fn(async () => {});
diff --git a/src/daemon/src/manager/wakeCoordinator.ts b/src/daemon/src/manager/wakeCoordinator.ts
index f81e1a452..31383fdf3 100644
--- a/src/daemon/src/manager/wakeCoordinator.ts
+++ b/src/daemon/src/manager/wakeCoordinator.ts
@@ -21,6 +21,9 @@ interface AdmissionCoverage {
interface ActiveAdmission {
launchId: string;
coverage: Map<string, AdmissionCoverage>;
+ acknowledged: boolean;
+ observed: boolean;
+ whileActive: boolean;
}
interface AgentState {
@@ -36,8 +39,9 @@ interface AgentState {
}
/**
- * One active wake/turn admission per agent. Channels carry only desired and
- * model-seen watermarks; they never become independent steer lanes.
+ * One outstanding unread-notification admission per agent. Channels carry
+ * desired and model-seen watermarks; they never become independent steer
+ * lanes.
*/
export class WakeCoordinator {
private readonly agents = new Map<string, AgentState>();
@@ -69,10 +73,11 @@ export class WakeCoordinator {
if (desiredAdvanced) onDesiredAdvance?.(command);
state.dispatch = dispatch;
- // The active agent will pull the global inbox. Higher watermarks only
- // advance desired state; idle reconciliation decides whether one rewake is
- // needed after observing what the turn actually pulled.
- if (state.active || state.admitting) {
+ // One unread notification may be outstanding at a time. An active runtime
+ // still needs the first higher watermark delivered into its current
+ // logical session; later watermarks coalesce behind that admission until
+ // the resulting inbox pull proves what the model actually saw.
+ if (state.admitting || state.activeAdmission) {
this.rememberReplacement(state, command);
return { state: "suppressed", coveredSeq: seq };
}
@@ -95,6 +100,9 @@ export class WakeCoordinator {
for (const message of messages) {
const seq = Number(message.seq.startsWith("#") ? message.seq.slice(1) : message.seq);
if (!Number.isSafeInteger(seq) || seq <= 0) continue;
+ if (state.activeAdmission?.coverage.has(message.channel)) {
+ state.activeAdmission.observed = true;
+ }
const scope = state.scopes.get(message.channel);
if (scope) {
scope.modelSeenSeq = Math.max(scope.modelSeenSeq, seq);
@@ -109,6 +117,9 @@ export class WakeCoordinator {
});
}
}
+ if (this.finishObservedAdmission(state)) {
+ void this.reconcile(agentId, state).catch(() => {});
+ }
return true;
}
@@ -117,11 +128,26 @@ export class WakeCoordinator {
const state = this.agent(agentId);
if (activity === "starting" || activity === "running") {
state.active = true;
+ void this.reconcile(agentId, state).catch(() => {});
return;
}
if (activity !== "idle") return;
state.active = false;
+ const admission = state.activeAdmission;
+ if (admission) {
+ this.releaseUnobservedCoverage(state, admission);
+ // The logical turn ended before this coverage was observed. Fence the
+ // old launch so reconciliation cannot spin the same provisional command;
+ // a newer coalesced command or durable replay may take responsibility.
+ state.failedAdmissionLaunchId = admission.launchId;
+ state.retryAfterFailure = state.coalescedReplacement;
+ state.coalescedReplacement = null;
+ }
state.activeAdmission = null;
+ if (!state.admitting && state.retryAfterFailure) {
+ void this.retryFailedAdmission(agentId, state).catch(() => {});
+ return;
+ }
const next = this.nextPending(state);
if (next && state.dispatch) void this.admit(agentId, next);
}
@@ -130,7 +156,13 @@ export class WakeCoordinator {
const state = this.agents.get(agentId);
const admission = state?.activeAdmission;
if (!state || !admission || admission.launchId !== launchId) return;
- if (status === "ok") return;
+ if (status === "ok") {
+ admission.acknowledged = true;
+ if (this.finishObservedAdmission(state)) {
+ void this.reconcile(agentId, state).catch(() => {});
+ }
+ return;
+ }
// A failed delivery never occupies admission coverage. Desired watermarks
// remain, so a later transport retry or idle reconciliation can re-arm.
for (const [channel, coverage] of admission.coverage) {
@@ -139,7 +171,7 @@ export class WakeCoordinator {
scope.admittedSeq = coverage.previousSeq;
}
}
- state.active = false;
+ state.active = admission.whileActive && state.active;
state.failedAdmissionLaunchId = launchId;
state.retryAfterFailure = state.coalescedReplacement;
state.coalescedReplacement = null;
@@ -202,8 +234,9 @@ export class WakeCoordinator {
private async admit(agentId: string, preferred?: WakeCommand): Promise<void> {
const state = this.agent(agentId);
- if (state.active || state.admitting || !state.dispatch) return;
+ if (state.admitting || state.activeAdmission || !state.dispatch) return;
const admissionGeneration = state.observationGeneration;
+ const wasActive = state.active;
const command = preferred ?? this.nextPending(state);
if (!command) return;
const commandScope = state.scopes.get(command.unreadNotice.channel);
@@ -225,7 +258,13 @@ export class WakeCoordinator {
state.active = true;
state.failedAdmissionLaunchId = null;
state.coalescedReplacement = null;
- state.activeAdmission = { launchId: command.launchId, coverage };
+ state.activeAdmission = {
+ launchId: command.launchId,
+ coverage,
+ acknowledged: false,
+ observed: false,
+ whileActive: wasActive,
+ };
let dispatchError: unknown;
try {
await state.dispatch(command);
@@ -237,7 +276,7 @@ export class WakeCoordinator {
scope.admittedSeq = admitted.previousSeq;
}
}
- state.active = false;
+ state.active = wasActive && state.active;
state.failedAdmissionLaunchId = command.launchId;
state.retryAfterFailure = state.coalescedReplacement;
state.coalescedReplacement = null;
@@ -251,10 +290,7 @@ export class WakeCoordinator {
}
if (state.observationGeneration === admissionGeneration) {
await this.retryFailedAdmission(agentId, state);
- if (!state.active && !state.admitting) {
- const next = this.nextPending(state);
- if (next) await this.admit(agentId, next);
- }
+ await this.reconcile(agentId, state);
}
if (dispatchError) throw dispatchError;
}
@@ -272,11 +308,37 @@ export class WakeCoordinator {
}
private async retryFailedAdmission(agentId: string, state: AgentState): Promise<void> {
- if (state.active || state.admitting) return;
+ if (state.admitting || state.activeAdmission) return;
const replacement = state.retryAfterFailure;
state.retryAfterFailure = null;
if (!replacement) return;
state.failedAdmissionLaunchId = null;
await this.admit(agentId, replacement);
}
+
+ private finishObservedAdmission(state: AgentState): boolean {
+ const admission = state.activeAdmission;
+ if (!admission?.acknowledged || !admission.observed) return false;
+ this.releaseUnobservedCoverage(state, admission);
+ state.activeAdmission = null;
+ return true;
+ }
+
+ private releaseUnobservedCoverage(state: AgentState, admission: ActiveAdmission): void {
+ for (const [channel, coverage] of admission.coverage) {
+ const scope = state.scopes.get(channel);
+ if (
+ scope?.admittedSeq === coverage.admittedSeq
+ && scope.modelSeenSeq < coverage.admittedSeq
+ ) {
+ scope.admittedSeq = Math.max(coverage.previousSeq, scope.modelSeenSeq);
+ }
+ }
+ }
+
+ private async reconcile(agentId: string, state: AgentState): Promise<void> {
+ if (state.admitting || state.activeAdmission || !state.dispatch) return;
+ const next = this.nextPending(state);
+ if (next) await this.admit(agentId, next);
+ }
}
diff --git a/src/daemon/src/runtime/apmStateMachine.test.ts b/src/daemon/src/runtime/apmStateMachine.test.ts
deleted file mode 100644
index 50c1f07c1..000000000
--- a/src/daemon/src/runtime/apmStateMachine.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- createInitialApmGatedSteeringState,
- reduceApmGatedToolUse,
- reduceApmGatedCompaction,
- reduceApmGatedReview,
- reduceApmGatedFlushReadiness,
- type ApmGatedSteeringState,
-} from "./apmStateMachine";
-
-const init = createInitialApmGatedSteeringState;
-
-describe("reduceApmGatedToolUse", () => {
- it("tool_call increments outstanding + enters tool_wait", () => {
- const { nextState } = reduceApmGatedToolUse(init(), { kind: "tool_call" });
- expect(nextState.phase).toBe("tool_wait");
- expect(nextState.outstandingToolUses).toBe(1);
- });
-
- it("closing the LAST outstanding tool signals a batch flush", () => {
- let s = reduceApmGatedToolUse(init(), { kind: "tool_call" }).nextState;
- const r = reduceApmGatedToolUse(s, { kind: "tool_result" });
- expect(r.nextState.outstandingToolUses).toBe(0);
- expect(r.nextState.phase).toBe("tool_boundary");
- expect(r.shouldFlushToolBatch).toBe(true);
- });
-
- it("closing one of several tools does NOT flush yet", () => {
- let s = reduceApmGatedToolUse(init(), { kind: "tool_call" }).nextState;
- s = reduceApmGatedToolUse(s, { kind: "tool_call" }).nextState; // 2 outstanding
- const r = reduceApmGatedToolUse(s, { kind: "tool_result" });
- expect(r.nextState.outstandingToolUses).toBe(1);
- expect(r.shouldFlushToolBatch).toBe(false);
- });
-});
-
-describe("reduceApmGatedReview", () => {
- it("review_started enters reviewing; review_finished leaves it for assistant_continuation", () => {
- const started = reduceApmGatedReview(init(), { kind: "review_started" }).nextState;
- expect(started.phase).toBe("reviewing");
- expect(started.reviewing).toBe(true);
- const finished = reduceApmGatedReview(started, { kind: "review_finished" }).nextState;
- expect(finished.reviewing).toBe(false);
- expect(finished.phase).toBe("assistant_continuation");
- });
-});
-
-describe("reduceApmGatedFlushReadiness — the gate", () => {
- const ready = { isGated: true, hasSession: true, inboxLength: 1, reason: "test" };
-
- it("notifies when gated, has session, inbox non-empty, and no blockers", () => {
- const r = reduceApmGatedFlushReadiness(init(), ready);
- expect(r.shouldNotify).toBe(true);
- expect(r.blockedReason).toBeNull();
- expect(r.effects[0]).toMatchObject({ kind: "notify_stdin", clauseId: "SMR-002", stdinMode: "busy" });
- });
-
- it("blocks: non-gated / missing session / empty inbox", () => {
- expect(reduceApmGatedFlushReadiness(init(), { ...ready, isGated: false }).blockedReason).toBe("non_gated");
- expect(reduceApmGatedFlushReadiness(init(), { ...ready, hasSession: false }).blockedReason).toBe("missing_session");
- expect(reduceApmGatedFlushReadiness(init(), { ...ready, inboxLength: 0 }).blockedReason).toBe("empty_inbox");
- });
-
- it("blocks while compacting / reviewing / outstanding tools", () => {
- const compacting: ApmGatedSteeringState = { ...init(), compacting: true };
- expect(reduceApmGatedFlushReadiness(compacting, ready).blockedReason).toBe("compacting");
-
- const reviewing: ApmGatedSteeringState = { ...init(), reviewing: true };
- expect(reduceApmGatedFlushReadiness(reviewing, ready).blockedReason).toBe("reviewing");
-
- const busyTools: ApmGatedSteeringState = { ...init(), outstandingToolUses: 2 };
- expect(reduceApmGatedFlushReadiness(busyTools, ready).blockedReason).toBe("outstanding_tool_uses");
- });
-
- it("compaction_started sets compacting; compaction_finished clears it", () => {
- const started = reduceApmGatedCompaction(init(), { kind: "compaction_started" }).nextState;
- expect(started.compacting).toBe(true);
- expect(reduceApmGatedFlushReadiness(started, ready).blockedReason).toBe("compacting");
- const finished = reduceApmGatedCompaction(started, { kind: "compaction_finished" }).nextState;
- expect(finished.compacting).toBe(false);
- expect(reduceApmGatedFlushReadiness(finished, ready).shouldNotify).toBe(true);
- });
-});
diff --git a/src/daemon/src/runtime/apmStateMachine.ts b/src/daemon/src/runtime/apmStateMachine.ts
deleted file mode 100644
index af1f281e0..000000000
--- a/src/daemon/src/runtime/apmStateMachine.ts
+++ /dev/null
@@ -1,366 +0,0 @@
-/**
- * APM (Agent Process Manager) gated-steering state machine.
- *
- * This reducer set is the coarse-grained policy layer that decides WHEN to
- * flush queued inbox notices into a `gated` runtime, and emits the concrete
- * delivery effects (`notify_stdin` / `deliver_stdin`).
- *
- * It is a pure reducer: `(state, input) -> { nextState?, effects?, ... }`. The
- * orchestrator owns the mutable copy and applies the effects.
- *
- * Phases: idle → tool_wait → tool_boundary → assistant_continuation →
- * compacting → error → idle. Notices flush only at safe phases.
- *
- * Clause `SMR-002` tags every stdin-delivery effect (a stable marker used in
- * telemetry to identify the steering-message rule).
- */
-
-export const MAX_APM_GATED_STEERING_EVENTS = 12;
-
-export type ApmPhase =
- | "idle"
- | "tool_wait"
- | "tool_boundary"
- | "assistant_continuation"
- | "compacting"
- | "reviewing"
- | "error";
-
-export interface ApmGatedSteeringState {
- isIdle: boolean;
- expectedTerminationReason: string | null;
- phase: ApmPhase;
- outstandingToolUses: number;
- compacting: boolean;
- /** True while the runtime is in review mode (Codex) — flushes are held. */
- reviewing?: boolean;
- toolBoundaryFlushDisabled: boolean;
- lastFlushReason: string | null;
- recentEvents: string[];
-}
-
-export type StdinDeliveryEffect = {
- kind: "notify_stdin" | "deliver_stdin";
- reason: string;
- stdinMode: "busy" | "idle";
- clauseId: "SMR-002";
-};
-
-export function createInitialApmGatedSteeringState(): ApmGatedSteeringState {
- return {
- isIdle: false,
- expectedTerminationReason: null,
- phase: "idle",
- outstandingToolUses: 0,
- compacting: false,
- toolBoundaryFlushDisabled: false,
- lastFlushReason: null,
- recentEvents: [],
- };
-}
-
-/* ------------------------------------------------------------------ */
-/* Phase transitions */
-/* ------------------------------------------------------------------ */
-
-export function reduceApmIdleState(
- state: ApmGatedSteeringState,
- input: { isIdle: boolean },
-): { nextState: ApmGatedSteeringState } {
- return { nextState: { ...state, isIdle: input.isIdle } };
-}
-
-/**
- * Tool-call open/close. A `tool_call` increments the outstanding count and
- * enters `tool_wait`. Anything else (a tool result) decrements and lands on a
- * `tool_boundary`; when the LAST outstanding tool closes, we signal a batch
- * flush opportunity.
- */
-export function reduceApmGatedToolUse(
- state: ApmGatedSteeringState,
- input: { kind: string },
-): {
- nextState: ApmGatedSteeringState;
- hadOutstandingToolUse: boolean;
- shouldFlushToolBatch: boolean;
-} {
- if (input.kind === "tool_call") {
- return {
- nextState: {
- ...state,
- isIdle: false,
- phase: "tool_wait",
- outstandingToolUses: state.outstandingToolUses + 1,
- },
- hadOutstandingToolUse: state.outstandingToolUses > 0,
- shouldFlushToolBatch: false,
- };
- }
- const hadOutstandingToolUse = state.outstandingToolUses > 0;
- const outstandingToolUses = Math.max(0, state.outstandingToolUses - 1);
- return {
- nextState: {
- ...state,
- isIdle: false,
- phase: "tool_boundary",
- outstandingToolUses,
- },
- hadOutstandingToolUse,
- shouldFlushToolBatch: hadOutstandingToolUse && outstandingToolUses === 0,
- };
-}
-
-export function reduceApmGatedCompaction(
- state: ApmGatedSteeringState,
- input: { kind: "compaction_started" | "compaction_interrupted" | string },
-): { nextState: ApmGatedSteeringState } {
- if (input.kind === "compaction_started") {
- return { nextState: { ...state, isIdle: false, phase: "compacting", compacting: true } };
- }
- if (input.kind === "compaction_interrupted") {
- return { nextState: { ...state, isIdle: false, compacting: false } };
- }
- // compaction_finished
- return {
- nextState: { ...state, isIdle: false, phase: "assistant_continuation", compacting: false },
- };
-}
-
-export function reduceApmGatedAssistantContinuation(state: ApmGatedSteeringState): {
- nextState: ApmGatedSteeringState;
-} {
- return { nextState: { ...state, isIdle: false, phase: "assistant_continuation" } };
-}
-
-/**
- * Codex review mode. `review_started` enters the `reviewing` phase (flushes are
- * held — see `reduceApmGatedFlushReadiness`); `review_finished` leaves it and
- * lands on `assistant_continuation`, a safe boundary to flush at.
- */
-export function reduceApmGatedReview(
- state: ApmGatedSteeringState,
- input: { kind: "review_started" | "review_finished" | string },
-): { nextState: ApmGatedSteeringState } {
- if (input.kind === "review_started") {
- return { nextState: { ...state, isIdle: false, phase: "reviewing", reviewing: true } };
- }
- return {
- nextState: { ...state, isIdle: false, phase: "assistant_continuation", reviewing: false },
- };
-}
-
-/* ------------------------------------------------------------------ */
-/* Delivery decisions (emit effects) */
-/* ------------------------------------------------------------------ */
-
-/**
- * After a compaction completes, if there is a session, the runtime supports
- * stdin, the inbox is non-empty AND a notification is pending — deliver a busy
- * notice. (Compaction is a natural safe boundary.)
- */
-export function reduceApmGatedCompactionBoundaryFlush(
- _state: ApmGatedSteeringState,
- input: {
- hasSession: boolean;
- supportsStdinNotification: boolean;
- inboxLength: number;
- pendingNotificationCount: number;
- },
-): { effects: StdinDeliveryEffect[] } {
- if (!input.hasSession || !input.supportsStdinNotification || input.inboxLength === 0) {
- return { effects: [] };
- }
- if (input.pendingNotificationCount === 0) return { effects: [] };
- return {
- effects: [{ kind: "notify_stdin", reason: "compaction_finished", stdinMode: "busy", clauseId: "SMR-002" }],
- };
-}
-
-/** Symmetric to compaction: review exit is also a safe flush boundary. */
-export function reduceApmGatedReviewBoundaryFlush(
- _state: ApmGatedSteeringState,
- input: {
- hasSession: boolean;
- supportsStdinNotification: boolean;
- inboxLength: number;
- pendingNotificationCount: number;
- },
-): { effects: StdinDeliveryEffect[] } {
- if (!input.hasSession || !input.supportsStdinNotification || input.inboxLength === 0) {
- return { effects: [] };
- }
- if (input.pendingNotificationCount === 0) return { effects: [] };
- return {
- effects: [{ kind: "notify_stdin", reason: "review_finished", stdinMode: "busy", clauseId: "SMR-002" }],
- };
-}
-
-/**
- * Turn ended. If there are queued messages and the runtime can take them, go
- * NOT-idle and deliver them as an `idle`-mode prompt (the cleanest boundary —
- * a fresh turn). Otherwise mark idle.
- */
-export function reduceApmGatedTurnEnd(
- state: ApmGatedSteeringState,
- input: {
- inboxLength?: number;
- supportsStdinNotification?: boolean;
- hasSession?: boolean;
- terminateProcessOnTurnEnd?: boolean;
- } = {},
-): { nextState: ApmGatedSteeringState; effects: StdinDeliveryEffect[] } {
- const shouldDeliverQueuedMessages = Boolean(
- input.inboxLength && input.inboxLength > 0 && input.supportsStdinNotification && input.hasSession,
- );
- return {
- nextState: {
- ...state,
- isIdle: !shouldDeliverQueuedMessages,
- expectedTerminationReason:
- input.terminateProcessOnTurnEnd === true ? "turn_end" : state.expectedTerminationReason,
- phase: "idle",
- outstandingToolUses: 0,
- compacting: false,
- },
- effects: shouldDeliverQueuedMessages
- ? [{ kind: "deliver_stdin", reason: "turn_end", stdinMode: "idle", clauseId: "SMR-002" }]
- : [],
- };
-}
-
-export function reduceApmGatedError(
- state: ApmGatedSteeringState,
- input: { terminalWakeable?: boolean; disableToolBoundaryFlush?: boolean } = {},
-): { nextState: ApmGatedSteeringState; shouldDisableToolBoundaryFlush: boolean } {
- const shouldDisableToolBoundaryFlush = input.disableToolBoundaryFlush === true;
- return {
- nextState: {
- ...state,
- isIdle: input.terminalWakeable === true,
- phase: "error",
- compacting: false,
- toolBoundaryFlushDisabled: state.toolBoundaryFlushDisabled || shouldDisableToolBoundaryFlush,
- },
- shouldDisableToolBoundaryFlush,
- };
-}
-
-/**
- * The central "can I flush a tool-boundary notice now?" gate. Returns
- * `shouldNotify` plus a structured `blockedReason` for telemetry, and the
- * busy-mode `notify_stdin` effect when clear.
- */
-export function reduceApmGatedFlushReadiness(
- state: ApmGatedSteeringState,
- input: { isGated: boolean; hasSession: boolean; inboxLength: number; reason: string },
-): { shouldNotify: boolean; blockedReason: string | null; effects: StdinDeliveryEffect[] } {
- if (!input.isGated) return { shouldNotify: false, blockedReason: "non_gated", effects: [] };
- if (!input.hasSession) return { shouldNotify: false, blockedReason: "missing_session", effects: [] };
- if (input.inboxLength === 0) return { shouldNotify: false, blockedReason: "empty_inbox", effects: [] };
- if (state.toolBoundaryFlushDisabled) {
- return { shouldNotify: false, blockedReason: "tool_boundary_flush_disabled", effects: [] };
- }
- if (state.compacting) return { shouldNotify: false, blockedReason: "compacting", effects: [] };
- if (state.reviewing) return { shouldNotify: false, blockedReason: "reviewing", effects: [] };
- if (state.outstandingToolUses > 0) {
- return { shouldNotify: false, blockedReason: "outstanding_tool_uses", effects: [] };
- }
- return {
- shouldNotify: true,
- blockedReason: null,
- effects: [{ kind: "notify_stdin", reason: input.reason, stdinMode: "busy", clauseId: "SMR-002" }],
- };
-}
-
-export function reduceApmGatedFlush(
- state: ApmGatedSteeringState,
- input: { reason: string },
-): { nextState: ApmGatedSteeringState } {
- return { nextState: { ...state, lastFlushReason: input.reason } };
-}
-
-export function reduceApmGatedRecentEvent(
- state: ApmGatedSteeringState,
- input: { event: string },
-): { nextState: ApmGatedSteeringState } {
- const summary = `${input.event}:${state.phase}:tools=${state.outstandingToolUses}:compact=${state.compacting}`;
- return {
- nextState: {
- ...state,
- recentEvents: [...state.recentEvents, summary].slice(-MAX_APM_GATED_STEERING_EVENTS),
- },
- };
-}
-
-/* ------------------------------------------------------------------ */
-/* Recovery / termination */
-/* ------------------------------------------------------------------ */
-
-/** Decide whether to terminate-and-restart a stalled process for recovery. */
-export function reduceApmStalledRecoveryTermination(
- state: ApmGatedSteeringState,
- input: {
- inboxLength: number;
- supportsStdinNotification: boolean;
- busyDeliveryMode: string;
- hasSession: boolean;
- hasDirectStdinRecoveryEvidence: boolean;
- staleForMs: number;
- staleThresholdMs: number;
- runtimeProgressIsStale: boolean;
- },
-): {
- nextState: ApmGatedSteeringState;
- shouldTerminate: boolean;
- alreadyRecovering: boolean;
- blockedReason: string | null;
-} {
- if (input.inboxLength === 0) {
- return { nextState: state, shouldTerminate: false, alreadyRecovering: false, blockedReason: "empty_inbox" };
- }
- if (state.expectedTerminationReason === "stalled_recovery") {
- return { nextState: state, shouldTerminate: false, alreadyRecovering: true, blockedReason: null };
- }
- const directStdinRuntime = input.supportsStdinNotification && input.busyDeliveryMode === "direct";
- const canRestartDirectStdinProcess =
- directStdinRuntime &&
- input.hasSession &&
- (state.outstandingToolUses === 0 || input.hasDirectStdinRecoveryEvidence);
- const canRestartStalledProcess = !input.supportsStdinNotification || canRestartDirectStdinProcess;
- if (!canRestartStalledProcess) {
- return {
- nextState: state,
- shouldTerminate: false,
- alreadyRecovering: false,
- blockedReason: "runtime_not_restartable",
- };
- }
- if (input.staleForMs < input.staleThresholdMs && !input.runtimeProgressIsStale) {
- return {
- nextState: state,
- shouldTerminate: false,
- alreadyRecovering: false,
- blockedReason: "runtime_progress_recent",
- };
- }
- return {
- nextState: { ...state, expectedTerminationReason: "stalled_recovery" },
- shouldTerminate: true,
- alreadyRecovering: false,
- blockedReason: null,
- };
-}
-
-export function reduceApmStartupTimeoutTermination(
- state: ApmGatedSteeringState,
- input: { hasRuntimeProgressEvent: boolean },
-): { nextState: ApmGatedSteeringState; shouldTerminate: boolean; blockedReason: string | null } {
- if (input.hasRuntimeProgressEvent) {
- return { nextState: state, shouldTerminate: false, blockedReason: "runtime_progress_started" };
- }
- return {
- nextState: { ...state, isIdle: false, expectedTerminationReason: "startup_timeout" },
- shouldTerminate: true,
- blockedReason: null,
- };
-}
diff --git a/src/daemon/src/runtime/errorDiagnostics.ts b/src/daemon/src/runtime/errorDiagnostics.ts
index 42f6e7a5c..8664c17ab 100644
--- a/src/daemon/src/runtime/errorDiagnostics.ts
+++ b/src/daemon/src/runtime/errorDiagnostics.ts
@@ -10,6 +10,7 @@
* 4. Fallback: `RuntimeError`.
*/
import { createHash } from "crypto";
+import { scrubAgentDriverDiagnosticText } from "@alook/agent-driver/host";
/** Excerpt cap for the runtime-error diagnostic envelope's `runtime_error_message_excerpt`. */
const ERROR_EXCERPT_MAX_BYTES = 4000;
@@ -134,12 +135,7 @@ export function classifyRuntimeErrorAction(
/** Redact tokens, keys, emails, URL creds and filesystem paths for telemetry. */
export function scrubRuntimeErrorDiagnosticText(value: string): string {
- return value
- .replace(/Bearer\s+[A-Za-z0-9._\-]+/g, "Bearer [redacted]")
- .replace(/\b(?:sk|sk-ant|sk-proj|xox[abprs])-[A-Za-z0-9._\-]+/g, "[redacted-token]")
- .replace(/[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/g, "[redacted-email]")
- .replace(/(\?|&)([^=\s]+)=([^&\s]+)/g, "$1$2=[redacted]")
- .replace(/(\/[^\s]*){2,}/g, "[redacted-path]");
+ return scrubAgentDriverDiagnosticText(value);
}
function messageLengthBucket(len: number): string {
diff --git a/src/daemon/src/runtime/killTree.test.ts b/src/daemon/src/runtime/killTree.test.ts
deleted file mode 100644
index d5e0b6cdf..000000000
--- a/src/daemon/src/runtime/killTree.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { describe, it, expect, afterEach } from "vitest";
-import { spawn, type ChildProcess } from "child_process";
-import { spawnAgentProcess, killProcessTree, isAlive } from "./killTree.js";
-
-/**
- * These tests spawn real child processes rather than mocking
- * `child_process` — the bug this file guards against (silent no-op kill on
- * a non-detached child, see plans/fix-daemon-agent-process-kill.md) is a
- * real OS process-group interaction that a mock would trivially hide.
- */
-
-const spawned: ChildProcess[] = [];
-
-/** A child that just idles until signaled. */
-function spawnIdleChild(opts: { detached?: boolean } = {}): ChildProcess {
- const proc = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
- stdio: "ignore",
- detached: opts.detached,
- });
- spawned.push(proc);
- return proc;
-}
-
-/** A child that installs a no-op SIGTERM handler, so only SIGKILL kills it. */
-function spawnSigtermImmuneChild(opts: { detached?: boolean } = {}): ChildProcess {
- const proc = spawn(
- process.execPath,
- ["-e", "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)"],
- { stdio: "ignore", detached: opts.detached },
- );
- spawned.push(proc);
- return proc;
-}
-
-afterEach(() => {
- // Belt-and-suspenders cleanup in case a test fails before its own kill.
- for (const proc of spawned.splice(0)) {
- if (proc.pid && isAlive(proc.pid)) {
- try {
- process.kill(proc.pid, "SIGKILL");
- } catch {
- // already dead
- }
- }
- }
-});
-
-describe("killProcessTree", () => {
- it("kills a detached child via the process-group signal", async () => {
- const proc = spawnAgentProcess(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
- cwd: process.cwd(),
- env: process.env,
- });
- spawned.push(proc);
- await new Promise((r) => proc.once("spawn", r));
- expect(isAlive(proc.pid!)).toBe(true);
-
- await killProcessTree(proc.pid!, { graceMs: 1000 });
-
- expect(isAlive(proc.pid!)).toBe(false);
- });
-
- it("still kills a NON-detached child — regression test for the ESRCH-treated-as-dead bug", async () => {
- // Deliberately spawned WITHOUT detached, reproducing every driver's
- // pre-fix spawn() call. `process.kill(-pid, sig)` throws ESRCH here
- // because the child isn't its own process-group leader; killProcessTree
- // must fall back to signaling the pid directly instead of assuming
- // ESRCH means "already dead".
- const proc = spawnIdleChild({ detached: false });
- await new Promise((r) => proc.once("spawn", r));
- expect(isAlive(proc.pid!)).toBe(true);
-
- await killProcessTree(proc.pid!, { graceMs: 1000 });
-
- expect(isAlive(proc.pid!)).toBe(false);
- });
-
- it("resolves immediately for an already-dead pid without throwing", async () => {
- const proc = spawnIdleChild({ detached: false });
- await new Promise((r) => proc.once("spawn", r));
- const pid = proc.pid!;
- process.kill(pid, "SIGKILL");
- await new Promise((r) => proc.once("exit", r));
- expect(isAlive(pid)).toBe(false);
-
- await expect(killProcessTree(pid, { graceMs: 1000 })).resolves.toBeUndefined();
- });
-
- it("no-ops on an invalid pid (0 or negative)", async () => {
- await expect(killProcessTree(0)).resolves.toBeUndefined();
- await expect(killProcessTree(-1)).resolves.toBeUndefined();
- });
-
- it("escalates to SIGKILL after graceMs when the child ignores SIGTERM", async () => {
- const proc = spawnSigtermImmuneChild({ detached: false });
- await new Promise((r) => proc.once("spawn", r));
- expect(isAlive(proc.pid!)).toBe(true);
-
- await killProcessTree(proc.pid!, { graceMs: 300 });
-
- expect(isAlive(proc.pid!)).toBe(false);
- });
-});
-
-describe("spawnAgentProcess", () => {
- it("spawns detached on POSIX so killProcessTree's group signal has a group to hit", async () => {
- if (process.platform === "win32") return;
- const proc = spawnAgentProcess(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
- cwd: process.cwd(),
- env: process.env,
- });
- spawned.push(proc);
- await new Promise((r) => proc.once("spawn", r));
-
- // A detached child is its own process-group leader: pgid === pid.
- const { execFileSync } = await import("child_process");
- const out = execFileSync("ps", ["-o", "pgid=", "-p", String(proc.pid)], { encoding: "utf8" }).trim();
- expect(Number(out)).toBe(proc.pid);
-
- process.kill(proc.pid!, "SIGKILL");
- });
-
- it("pipes stdio and forwards cwd/env/shell", () => {
- const proc = spawnAgentProcess(process.execPath, ["-e", "process.exit(0)"], {
- cwd: process.cwd(),
- env: { ...process.env, FOO: "bar" },
- shell: false,
- });
- spawned.push(proc);
- expect(proc.stdin).not.toBeNull();
- expect(proc.stdout).not.toBeNull();
- expect(proc.stderr).not.toBeNull();
- });
-});
diff --git a/src/daemon/src/runtime/killTree.ts b/src/daemon/src/runtime/killTree.ts
deleted file mode 100644
index 1e242d7c1..000000000
--- a/src/daemon/src/runtime/killTree.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * Agent process spawn + process-tree termination with SIGKILL escalation.
- *
- * These two live together on purpose: they're opposite ends of the SAME
- * contract. `spawnAgentProcess` is the ONLY way a driver may start an agent
- * CLI — it always spawns `detached` on POSIX, making the child the leader of
- * its own process group (pgid = pid). That's what lets `killProcessTree`
- * signal the negative pid to reach the whole group — the CLI plus any MCP
- * servers / tool subprocesses it spawns — instead of just the leader, which
- * would otherwise leave grandchildren orphaned.
- *
- * Driver files must NOT call `child_process.spawn` directly for the agent CLI
- * — always go through `spawnAgentProcess` here, so the detached contract
- * can't be silently skipped by a new (or edited) driver.
- *
- * SIGTERM is a request; after a grace window we escalate to SIGKILL.
- */
-import { spawn, type ChildProcess } from "child_process";
-
-const POLL_MS = 100;
-/**
- * Standard grace before SIGKILL when the manager stops a running session.
- * Every session-level stop path (`ManagedSession.stop`, `SdkManagedSession.stop`,
- * `ChildProcessRuntimeSession.stop`'s fallback) shares this so the "how long
- * before we kill it hard" answer is one number, not three drifting ones.
- *
- * MUST stay strictly below `daemonStart.ts`'s `STOP_GRACE_MS` (the window
- * `alook daemon stop` gives the DAEMON before SIGKILLing it). The daemon's
- * SIGTERM handler awaits `manager.stopAll()`, which awaits these per-session
- * kills — so if the two windows were equal, an agent CLI that ignores SIGTERM
- * would still be inside its own grace when the outer SIGKILL lands, killing
- * the daemon before it ever escalates to SIGKILL on the child. The child is
- * detached (its own process group), so it would survive as an orphan.
- */
-export const SESSION_STOP_GRACE_MS = 2000;
-const DEFAULT_GRACE_MS = SESSION_STOP_GRACE_MS;
-const isPosix = process.platform !== "win32";
-
-export interface AgentSpawnOptions {
- cwd: string;
- env: NodeJS.ProcessEnv;
- /** Run through a shell — needed on Windows for `.cmd`/`.bat` shims. */
- shell?: boolean;
- /**
- * stdin disposition. Default `"pipe"` — codex/claude/pi write to stdin
- * (initial prompt, `turn/steer`), so they need it. A per-turn driver that
- * never writes stdin (cursor: prompt is a positional arg, `encodeStdinMessage`
- * returns null) must use `"ignore"`: cursor-agent BLOCKS waiting on a piped
- * stdin even though the prompt is already supplied, emitting nothing →
- * handshake_timeout. `"ignore"` lets it detect there's no interactive input
- * and run. stdout/stderr stay piped regardless (we always read stream-json).
- */
- stdin?: "pipe" | "ignore";
-}
-
-/**
- * The only sanctioned way to spawn an agent CLI child process. Always pipes
- * stdio and (on POSIX) spawns `detached` so the child becomes its own
- * process-group leader — required for `killProcessTree`'s group signal to
- * actually reach it (and its grandchildren) instead of silently no-oping.
- * See the module doc comment above for why this must be the single spawn
- * entry point rather than each driver calling `child_process.spawn` itself.
- */
-export function spawnAgentProcess(command: string, args: string[], opts: AgentSpawnOptions): ChildProcess {
- return spawn(command, args, {
- cwd: opts.cwd,
- // stdout/stderr always piped (we read the runtime's stream-json/JSON-RPC);
- // stdin defaults to pipe (writers: codex/claude/pi) but a no-stdin driver
- // (cursor) opts into "ignore" — see AgentSpawnOptions.stdin.
- stdio: [opts.stdin ?? "pipe", "pipe", "pipe"],
- env: opts.env,
- shell: opts.shell ?? false,
- detached: isPosix,
- });
-}
-
-export function isAlive(pid: number): boolean {
- try {
- process.kill(pid, 0);
- return true;
- } catch (e) {
- return (e as NodeJS.ErrnoException)?.code === "EPERM";
- }
-}
-
-/**
- * Best-effort group signal, ALWAYS followed by a direct pid signal —
- * regardless of whether the group signal succeeded, threw `ESRCH` (no such
- * process group — e.g. the child wasn't spawned detached), or threw anything
- * else. A group signal failure must never be mistaken for "the pid is dead":
- * that conflates two unrelated failure semantics and was the root cause of a
- * bug where stopped agents kept running forever (see
- * plans/fix-daemon-agent-process-kill.md). Signaling an already-dead pid is
- * safe — it just throws ESRCH too, caught and ignored below.
- */
-function signalTree(pid: number, signal: NodeJS.Signals): void {
- if (isPosix) {
- try {
- process.kill(-pid, signal);
- } catch {
- // Most commonly ESRCH (no such process group — not detached, or
- // already gone), but any failure here falls through the same way:
- // never treat it as proof the pid itself is dead.
- }
- }
- try {
- process.kill(pid, signal);
- } catch {
- // already dead
- }
-}
-
-/**
- * Terminate `pid` and its descendants: group SIGTERM, then group SIGKILL after
- * `graceMs`. Returns promptly when the target is already dead.
- */
-export async function killProcessTree(
- pid: number,
- opts?: { graceMs?: number },
-): Promise<void> {
- if (!pid || pid < 1) return;
- if (!isAlive(pid)) return;
-
- const graceMs = opts?.graceMs ?? DEFAULT_GRACE_MS;
- signalTree(pid, "SIGTERM");
-
- const deadline = Date.now() + graceMs;
- while (Date.now() < deadline) {
- if (!isAlive(pid)) return;
- await new Promise((r) => setTimeout(r, POLL_MS));
- }
-
- if (isAlive(pid)) {
- signalTree(pid, "SIGKILL");
- }
-}
diff --git a/src/daemon/src/runtime/runtimeSession.test.ts b/src/daemon/src/runtime/runtimeSession.test.ts
deleted file mode 100644
index 975882d67..000000000
--- a/src/daemon/src/runtime/runtimeSession.test.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-import { describe, it, expect, afterEach, vi } from "vitest";
-import { EventEmitter } from "events";
-import { spawn, type ChildProcess } from "child_process";
-import { PassThrough } from "stream";
-import { ChildProcessRuntimeSession } from "./runtimeSession.js";
-import type { Driver, LaunchContext } from "../types.js";
-
-/*
- * Red-line-5(b) of plans/daemon-trace-completeness-charter.md (T1): the synthetic
- * `session.fire("exit", {...})` tests in managerRuntime.test.ts prove the daemon
- * THREADS exitCode/exitSignal/abnormal into the FSM/trace. They do NOT prove the
- * SOURCE is real — that a genuinely killed subprocess actually fills `info.code`
- * / `info.signal` on the runtime session's `exit` event, which is what the
- * abnormal predicate (managerRuntime.ts) reads. A real subprocess dies here to
- * confirm that contract end-to-end (Node fills signal=SIGKILL, code=null; a
- * non-requested death → reason="runtime_exit"). Without this the "hardest to
- * reconstruct" blind spot would rest on an unverified assumption.
- */
-
-const spawned: ChildProcess[] = [];
-
-/** Minimal driver that spawns a real, long-lived child process. */
-function realSpawnDriver(): Driver {
- return {
- id: "test-real",
- lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" },
- spawn: async () => {
- const proc = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
- stdio: ["pipe", "pipe", "pipe"],
- });
- spawned.push(proc);
- return { process: proc };
- },
- parseLine: () => [],
- encodeStdinMessage: () => null,
- buildSystemPrompt: () => "",
- } as unknown as Driver;
-}
-
-function minimalCtx(): LaunchContext {
- return {
- workingDirectory: process.cwd(),
- agentId: "a1",
- standingPrompt: "",
- prompt: "",
- config: {} as LaunchContext["config"],
- credentialProxy: {} as LaunchContext["credentialProxy"],
- } as LaunchContext;
-}
-
-function controllableDriver(parseLine: Driver["parseLine"]): {
- driver: Driver;
- stdout: PassThrough;
-} {
- const stdout = new PassThrough();
- const stderr = new PassThrough();
- const stdin = new PassThrough();
- const proc = Object.assign(new EventEmitter(), {
- stdout,
- stderr,
- stdin,
- pid: undefined,
- exitCode: null,
- signalCode: null,
- kill: () => true,
- }) as unknown as ChildProcess;
- const driver = {
- ...realSpawnDriver(),
- spawn: async () => ({ process: proc }),
- parseLine,
- } as Driver;
- return { driver, stdout };
-}
-
-afterEach(() => {
- for (const p of spawned.splice(0)) {
- try { p.kill("SIGKILL"); } catch { /* already dead */ }
- }
-});
-
-describe("ChildProcessRuntimeSession — real subprocess exit fills the physical fact (T1 red-line-5b)", () => {
- it("a real SIGKILLed subprocess emits exit with signal=SIGKILL, null code, reason=runtime_exit", async () => {
- // POSIX-only: Windows has no real signals — `process.kill(pid, "SIGKILL")`
- // terminates the child but Node reports `code=1, signal=null`, so the
- // `signal === "SIGKILL"` contract this asserts can't hold there. Skip on
- // win32 (same platform-guard as killTree.test.ts). The clean-exit sibling
- // below (code=0/signal=null) is cross-platform and still runs.
- if (process.platform === "win32") return;
- const session = new ChildProcessRuntimeSession(realSpawnDriver(), minimalCtx());
- const exitInfo = await new Promise<{ code: number | null; signal: string | null; reason?: string }>(
- (resolve) => {
- session.on("exit", (...args: unknown[]) => resolve(args[0] as never));
- void session.start({ text: "go" }).then(() => {
- // Kill the real child directly (external kill, NOT session.stop()) so
- // requestedStopReason stays unset → reason="runtime_exit", the crash
- // shape the abnormal predicate must catch.
- const pid = session.pid;
- if (pid) process.kill(pid, "SIGKILL");
- });
- },
- );
- expect(exitInfo.signal).toBe("SIGKILL");
- expect(exitInfo.code).toBeNull();
- expect(exitInfo.reason).toBe("runtime_exit");
- });
-
- it("a real clean exit (code 0) emits code=0, null signal", async () => {
- const cleanDriver = {
- ...realSpawnDriver(),
- spawn: async () => {
- const proc = spawn(process.execPath, ["-e", "process.exit(0)"], { stdio: ["pipe", "pipe", "pipe"] });
- spawned.push(proc);
- return { process: proc };
- },
- } as unknown as Driver;
- const session = new ChildProcessRuntimeSession(cleanDriver, minimalCtx());
- const exitInfo = await new Promise<{ code: number | null; signal: string | null; reason?: string }>(
- (resolve) => {
- session.on("exit", (...args: unknown[]) => resolve(args[0] as never));
- void session.start({ text: "go" });
- },
- );
- expect(exitInfo.code).toBe(0);
- expect(exitInfo.signal).toBeNull();
- });
-});
-
-describe("ChildProcessRuntimeSession — raw stdout tap (P0-1)", () => {
- it("taps each complete non-empty line before parseLine and preserves the original text", async () => {
- const order: string[] = [];
- const parseLine = vi.fn((line: string) => {
- order.push(`parse:${line}`);
- return [];
- });
- const { driver, stdout } = controllableDriver(parseLine);
- const session = new ChildProcessRuntimeSession(driver, minimalCtx(), {
- onRawStdoutLine: (line) => order.push(`raw:${line}`),
- });
- await session.start({ text: "go" });
-
- stdout.write(" {\"jsonrpc\":\"2.0\"}");
- stdout.write(" \n\npartial");
-
- expect(order).toEqual([
- 'raw: {"jsonrpc":"2.0"} ',
- 'parse: {"jsonrpc":"2.0"} ',
- ]);
- expect(parseLine).toHaveBeenCalledTimes(1);
- });
-
- it("continues through parseLine and runtime_event when the tap throws", async () => {
- const parsedEvent = { kind: "text", text: "ok" } as const;
- const parseLine = vi.fn(() => [parsedEvent]);
- const { driver, stdout } = controllableDriver(parseLine);
- const session = new ChildProcessRuntimeSession(driver, minimalCtx(), {
- onRawStdoutLine: () => {
- throw new Error("sink failed");
- },
- });
- const events: unknown[] = [];
- session.on("runtime_event", (event) => events.push(event));
- await session.start({ text: "go" });
-
- expect(() => stdout.write('{"type":"message"}\n')).not.toThrow();
- expect(parseLine).toHaveBeenCalledWith('{"type":"message"}');
- expect(events).toEqual([parsedEvent]);
- });
-});
diff --git a/src/daemon/src/runtime/runtimeSession.ts b/src/daemon/src/runtime/runtimeSession.ts
deleted file mode 100644
index fcb7b312f..000000000
--- a/src/daemon/src/runtime/runtimeSession.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-/**
- * ChildProcessRuntimeSession — the generic child-process host for CLI drivers.
- *
- * It owns the spawned process, line-buffers stdout, runs each complete line
- * through `driver.parseLine`, and re-emits the resulting `ParsedEvent`s. The
- * driver supplies the runtime-specific behavior; this class is the uniform
- * plumbing (start / send / stop / event fan-out) the daemon talks to.
- *
- * In-process SDK drivers (pi) do NOT use this — they return their own
- * EventEmitter-based session from `createSession` and throw from `spawn`.
- */
-import { EventEmitter } from "events";
-import type { ChildProcess } from "child_process";
-import type { Driver, LaunchContext, StdinMode } from "../types.js";
-import { busyDeliveryModeOf, supportsStdinNotificationOf } from "../types.js";
-import { killProcessTree, SESSION_STOP_GRACE_MS } from "./killTree.js";
-
-/**
- * A flattened, daemon-facing description of how a runtime behaves, derived
- * purely from the driver's declared capabilities. Lets the daemon reason about
- * transport/lifecycle without knowing the concrete driver.
- */
-export interface RuntimeSessionDescriptor {
- transport: "child_process";
- lifecycle: "turn_based" | "persistent_stream";
- input: {
- initial: "start";
- idle: "stdin" | "unsupported";
- busy: "stdin_steer" | "unsupported";
- };
- readiness: "spawned";
- turnBoundary: "process_exit" | "parsed_event";
- startPolicy: "immediate" | "defer_until_concrete_message";
- inFlightWake: DriverInFlightWake;
- busyDelivery: string;
- postTurn: "terminate_process" | "close_stdin" | "keep_alive";
-}
-
-type DriverInFlightWake = "steer" | "queue" | "spawn_new" | "coalesce_into_pending";
-
-export function descriptorFromDriver(driver: Driver): RuntimeSessionDescriptor {
- const lifecycle = driver.lifecycle.kind === "per_turn" ? "turn_based" : "persistent_stream";
- // Derived from lifecycle (single source of truth) — see supportsStdinNotificationOf.
- const supportsStdin = supportsStdinNotificationOf(driver.lifecycle);
- const idle = supportsStdin ? "stdin" : "unsupported";
- const busy = supportsStdin ? "stdin_steer" : "unsupported";
- return {
- transport: "child_process",
- lifecycle,
- input: { initial: "start", idle, busy },
- readiness: "spawned",
- turnBoundary: driver.lifecycle.kind === "per_turn" ? "process_exit" : "parsed_event",
- startPolicy: driver.lifecycle.kind === "per_turn" ? driver.lifecycle.start : "immediate",
- inFlightWake: driver.lifecycle.inFlightWake,
- busyDelivery: busyDeliveryModeOf(driver.lifecycle),
- postTurn: driver.terminateProcessOnTurnEnd
- ? "terminate_process"
- : driver.endStdinOnTurnEnd
- ? "close_stdin"
- : "keep_alive",
- };
-}
-
-export interface StartInput {
- text: string;
- sessionId?: string;
-}
-export interface SendInput {
- text: string;
- sessionId?: string;
- mode?: StdinMode;
-}
-
-export interface ChildProcessRuntimeSessionOptions {
- /** Observability-only tap for each complete non-empty stdout line, before parsing. */
- onRawStdoutLine?: (line: string) => void;
-}
-
-export class ChildProcessRuntimeSession {
- readonly descriptor: RuntimeSessionDescriptor;
- private readonly events = new EventEmitter();
- private process: ChildProcess | null = null;
- private started = false;
- private stdoutBuffer = "";
- private requestedStopReason?: string;
-
- constructor(
- private readonly driver: Driver,
- private readonly ctx: LaunchContext,
- private readonly opts: ChildProcessRuntimeSessionOptions = {},
- ) {
- this.descriptor = descriptorFromDriver(driver);
- }
-
- get pid(): number | undefined {
- return this.process?.pid;
- }
- get currentSessionId(): string | null {
- return this.driver.currentSessionId;
- }
- get exitCode(): number | null {
- return this.process?.exitCode ?? null;
- }
- get signalCode(): NodeJS.Signals | null {
- return this.process?.signalCode ?? null;
- }
- get closed(): boolean {
- return this.process ? this.process.exitCode != null || this.process.signalCode != null : false;
- }
-
- on(event: string, cb: (...args: unknown[]) => void): void {
- this.events.on(event, cb);
- }
-
- /** Spawn the process and deliver the initial prompt (handled inside spawn). */
- async start(input: StartInput): Promise<{ ok: boolean; acceptedAs?: string; reason?: string; error?: string }> {
- if (this.started) {
- return { ok: false, reason: "runtime_error", error: "runtime session already started" };
- }
- this.started = true;
- const launchCtx: LaunchContext = {
- ...this.ctx,
- prompt: input.text,
- config: { ...this.ctx.config, sessionId: input.sessionId ?? this.ctx.config.sessionId },
- };
- const { process: proc } = await this.driver.spawn(launchCtx);
- this.process = proc;
- this.attachProcess(proc);
- return { ok: true, acceptedAs: "prompt" };
- }
-
- /** Write a mid-session message (idle prompt or busy steer) to stdin. */
- send(input: SendInput): { ok: boolean; acceptedAs?: string; reason?: string } {
- const proc = this.process;
- if (!proc || this.closed) return { ok: false, reason: "closed" };
- const encoded = this.driver.encodeStdinMessage(input.text, input.sessionId ?? null, { mode: input.mode });
- if (!encoded) return { ok: false, reason: "unsupported" };
- proc.stdin?.write(encoded + "\n");
- return { ok: true, acceptedAs: input.mode === "busy" ? "steer" : "prompt" };
- }
-
- async stop(opts?: { reason?: string; signal?: NodeJS.Signals; forceAfterMs?: number }): Promise<void> {
- const proc = this.process;
- if (!proc || this.closed) return;
- this.requestedStopReason = opts?.reason;
- const pid = proc.pid;
- if (pid) {
- await killProcessTree(pid, { graceMs: opts?.forceAfterMs ?? SESSION_STOP_GRACE_MS });
- } else {
- proc.kill(opts?.signal ?? "SIGTERM");
- }
- }
-
- /** Wire stdout line-buffering → parseLine → runtime_event, plus lifecycle. */
- private attachProcess(proc: ChildProcess): void {
- proc.stdout?.on("data", (chunk: Buffer) => {
- const chunkText = chunk.toString();
- this.events.emit("stdout", chunkText);
- this.stdoutBuffer += chunkText;
- const lines = this.stdoutBuffer.split("\n");
- this.stdoutBuffer = lines.pop() || "";
- for (const line of lines) {
- if (!line.trim()) continue;
- try {
- this.opts.onRawStdoutLine?.(line);
- } catch {
- /* an observability tap cannot alter runtime parsing */
- }
- for (const event of this.driver.parseLine(line)) {
- this.events.emit("runtime_event", event);
- }
- }
- });
- proc.stderr?.on("data", (chunk: Buffer) => {
- const text = chunk.toString().trim();
- if (text) this.events.emit("stderr", text);
- });
- proc.on("error", (err) => this.events.emit("error", err));
- proc.on("exit", (code, signal) =>
- this.events.emit("exit", { code, signal, reason: this.requestedStopReason ? "requested" : "runtime_exit" }),
- );
- proc.on("close", (code, signal) =>
- this.events.emit("close", { code, signal, reason: this.requestedStopReason ? "requested" : "runtime_exit" }),
- );
- }
-}
-
-export function createChildProcessRuntimeSession(
- driver: Driver,
- ctx: LaunchContext,
- opts?: ChildProcessRuntimeSessionOptions,
-): ChildProcessRuntimeSession {
- return new ChildProcessRuntimeSession(driver, ctx, opts);
-}
diff --git a/src/daemon/src/runtime/sdkManagedSession.test.ts b/src/daemon/src/runtime/sdkManagedSession.test.ts
deleted file mode 100644
index 068eec836..000000000
--- a/src/daemon/src/runtime/sdkManagedSession.test.ts
+++ /dev/null
@@ -1,485 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-import { SdkManagedSession } from "./sdkManagedSession.js";
-import { SdkRuntimeSession, type SdkSessionHandle } from "./sdkRuntimeSession.js";
-import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
-
-function baseCtx(overrides: Partial<LaunchContext> = {}): LaunchContext {
- return {
- agentId: "agent_1",
- workingDirectory: "/tmp/agent_1",
- standingPrompt: "You are Pi.",
- prompt: "",
- config: {},
- ...overrides,
- };
-}
-
-function fakeDeps(): SdkDriverDeps {
- return {
- buildSpawnEnv: vi.fn().mockResolvedValue({}),
- createAgentSession: vi.fn(),
- };
-}
-
-/**
- * A driver whose `createSession` mirrors `PiDriver`'s real contract: it wires
- * `handle.prompt` to push events through the returned `SdkRuntimeSession`
- * (via a real `subscribe`-style callback), and does NOT itself await/send
- * the prompt — the caller must do that via `.send()`.
- */
-function fakeSdkDriver(): { driver: Driver & { createSession: NonNullable<Driver["createSession"]> }; createSession: ReturnType<typeof vi.fn> } {
- let session: SdkRuntimeSession;
- const handle: SdkSessionHandle = {
- prompt: (text: string) => {
- session.emitEvents([{ kind: "text", text }]);
- },
- steer: (text: string) => {
- session.emitEvents([{ kind: "text", text: `steer:${text}` }]);
- },
- abort: vi.fn(),
- dispose: vi.fn(),
- };
- const createSession = vi.fn(async (_ctx: LaunchContext, _deps: SdkDriverDeps) => {
- session = new SdkRuntimeSession(handle, "sess_1");
- return session;
- });
- const driver = {
- id: "fake-sdk",
- lifecycle: { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const,
- session: { recovery: "resume_or_fresh" } as const,
- model: { detectedModelsVerifiedAs: "launchable", toLaunchSpec: () => ({ params: {} }) } as const,
- probe: () => ({ status: "healthy" as const }),
- spawn: async () => {
- throw new Error("unsupported");
- },
- createSession,
- parseLine: () => [],
- currentSessionId: null,
- encodeStdinMessage: () => null,
- buildSystemPrompt: () => "",
- } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
- return { driver, createSession };
-}
-
-describe("SdkManagedSession", () => {
- it("delivers events from the initial prompt to a listener attached before start() — the event-loss regression test", async () => {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
-
- const received: unknown[] = [];
- // Attached BEFORE start(), same as managerRuntime.doSpawn does.
- adapter.on("runtime_event", (e) => received.push(e));
-
- await adapter.start({ text: "hello" });
-
- expect(received).toEqual([
- { kind: "session_init", sessionId: "sess_1" },
- { kind: "text", text: "hello" },
- ]);
- expect(adapter.currentSessionId).toBe("sess_1");
- });
-
- it("builds the launch ctx from start()'s input, overriding the base ctx's prompt/sessionId", async () => {
- const { driver, createSession } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx({ config: { sessionId: "base-session" } }), fakeDeps());
-
- await adapter.start({ text: "steer this", sessionId: "resumed-session" });
-
- const [launchCtx] = createSession.mock.calls[0] as [LaunchContext, SdkDriverDeps];
- expect(launchCtx.prompt).toBe("steer this");
- expect(launchCtx.config.sessionId).toBe("resumed-session");
- });
-
- it("falls back to the base ctx's sessionId when start() doesn't supply one", async () => {
- const { driver, createSession } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx({ config: { sessionId: "base-session" } }), fakeDeps());
-
- await adapter.start({ text: "hi" });
-
- const [launchCtx] = createSession.mock.calls[0] as [LaunchContext, SdkDriverDeps];
- expect(launchCtx.config.sessionId).toBe("base-session");
- });
-
- it("send() delegates busy/idle mode to the inner session once started", async () => {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- const received: unknown[] = [];
- adapter.on("runtime_event", (e) => received.push(e));
-
- await adapter.start({ text: "hello" });
- adapter.send({ text: "follow up", mode: "busy" });
- // steer's handle callback emits synchronously.
- await Promise.resolve();
-
- expect(received).toContainEqual({ kind: "text", text: "steer:follow up" });
- });
-
- it("send() before start() returns not_started instead of throwing", () => {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- expect(adapter.send({ text: "too early", mode: "idle" })).toEqual({ ok: false, reason: "not_started" });
- });
-
- it("stop() delegates to the inner session's stop", async () => {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- await adapter.start({ text: "hello" });
- await expect(adapter.stop()).resolves.toBeUndefined();
- });
-
- it("stop() before start() is a safe no-op", async () => {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- await expect(adapter.stop()).resolves.toBeUndefined();
- });
-
- // Regression test: unlike ChildProcessRuntimeSession (where killing the
- // process makes the OS emit its own "exit"), there's no process here to do
- // that for us — SdkManagedSession must fire "exit" itself, or
- // managerRuntime.ts's `session.on("exit", ...)` listener never runs and the
- // agent's session is never removed from the manager's map / FSM.
- it("stop() emits \"exit\" so the manager's session-cleanup listener runs", async () => {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- const exited = vi.fn();
- adapter.on("exit", exited);
-
- await adapter.start({ text: "hello" });
- await adapter.stop();
-
- expect(exited).toHaveBeenCalledTimes(1);
- });
-
- it("stop() emits \"exit\" exactly once even when called multiple times", async () => {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- const exited = vi.fn();
- adapter.on("exit", exited);
-
- await adapter.start({ text: "hello" });
- await adapter.stop();
- await adapter.stop();
-
- expect(exited).toHaveBeenCalledTimes(1);
- });
-
- it("stop() before start() still emits \"exit\" (no inner session to dispose)", async () => {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- const exited = vi.fn();
- adapter.on("exit", exited);
-
- await adapter.stop();
-
- expect(exited).toHaveBeenCalledTimes(1);
- });
-
- it("stop() emits \"exit\" even when the inner session's dispose rejects", async () => {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- const exited = vi.fn();
- adapter.on("exit", exited);
- await adapter.start({ text: "hello" });
-
- // Force the inner session's own stop() to reject — the manager must
- // still be notified via "exit" so the agent doesn't get stuck in
- // "stopping" forever just because disposal failed.
- const inner = (adapter as unknown as { inner: SdkRuntimeSession }).inner;
- vi.spyOn(inner, "stop").mockRejectedValueOnce(new Error("dispose failed"));
-
- await expect(adapter.stop()).rejects.toThrow("dispose failed");
- expect(exited).toHaveBeenCalledTimes(1);
- });
-
- // Batch S (plans/daemon-fsm-desync.md): SDK has no SIGKILL backstop, so a
- // vendor SDK whose `inner.stop()` never settles would otherwise pin the
- // adapter — `emitExit` sits behind an await that never returns and the FSM
- // is stuck "stopping" forever. `stop()` bounds the disposal wait; past the
- // deadline it forces "exit" and abandons the inner session.
- it("stop() forces \"exit\" within the deadline when inner.stop() hangs forever", async () => {
- vi.useFakeTimers();
- try {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- const exited = vi.fn();
- adapter.on("exit", exited);
- await adapter.start({ text: "hello" });
-
- const inner = (adapter as unknown as { inner: SdkRuntimeSession }).inner;
- // Never settles — the wedged-dispose case the bound exists for.
- vi.spyOn(inner, "stop").mockReturnValueOnce(new Promise<void>(() => { }));
-
- const stopPromise = adapter.stop({ forceAfterMs: 2000 });
- // Before the deadline: still pending, no exit yet.
- await vi.advanceTimersByTimeAsync(1999);
- expect(exited).not.toHaveBeenCalled();
- // Deadline elapses → forced exit, stop() resolves.
- await vi.advanceTimersByTimeAsync(1);
- await expect(stopPromise).resolves.toBeUndefined();
- expect(exited).toHaveBeenCalledTimes(1);
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("stop() best-effort aborts the inner session on the forced (timeout) path", async () => {
- vi.useFakeTimers();
- try {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- await adapter.start({ text: "hello" });
-
- const inner = (adapter as unknown as { inner: SdkRuntimeSession }).inner;
- vi.spyOn(inner, "stop").mockReturnValueOnce(new Promise<void>(() => { }));
- const abort = vi.fn();
- (inner as unknown as { abort?: () => void }).abort = abort;
-
- const stopPromise = adapter.stop({ forceAfterMs: 2000 });
- await vi.advanceTimersByTimeAsync(2000);
- await stopPromise;
- expect(abort).toHaveBeenCalledTimes(1);
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("stop() that disposes cleanly before the deadline does NOT wait out the timer", async () => {
- vi.useFakeTimers();
- try {
- const { driver } = fakeSdkDriver();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- const exited = vi.fn();
- adapter.on("exit", exited);
- await adapter.start({ text: "hello" });
-
- // inner.stop() resolves immediately — the real fakeSdkDriver handle's
- // dispose is synchronous, so no timer advance is needed for exit.
- await adapter.stop({ forceAfterMs: 60_000 });
- expect(exited).toHaveBeenCalledTimes(1);
- } finally {
- vi.useRealTimers();
- }
- });
-
- // Regression test: `managerRuntime.ts::doSpawn` registers the session in
- // its map (and a `stop`/`terminate_stalled` effect can look it up and call
- // `.stop()`) BEFORE `start()`'s `driver.createSession()` has resolved. If
- // `stop()` disposed nothing and emitted "exit" immediately in that window,
- // the still in-flight `start()` would go on to wire up the SDK session and
- // fire the first prompt into it — an orphaned session the manager already
- // believes has exited.
- it("a stop() that races an in-flight start() disposes the session instead of leaving it orphaned, and skips the first prompt", async () => {
- let resolveCreateSession!: (session: SdkRuntimeSession) => void;
- const disposed = vi.fn();
- const promptSent = vi.fn();
- const handle: SdkSessionHandle = {
- prompt: (text: string) => promptSent(text),
- steer: vi.fn(),
- dispose: disposed,
- };
- const createSession = vi.fn(
- () =>
- new Promise<SdkRuntimeSession>((resolve) => {
- resolveCreateSession = (session) => resolve(session);
- }),
- );
- const driver = {
- id: "fake-sdk",
- lifecycle: { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const,
- session: { recovery: "resume_or_fresh" } as const,
- model: { detectedModelsVerifiedAs: "launchable", toLaunchSpec: () => ({ params: {} }) } as const,
- probe: () => ({ status: "healthy" as const }),
- spawn: async () => {
- throw new Error("unsupported");
- },
- createSession,
- parseLine: () => [],
- currentSessionId: null,
- encodeStdinMessage: () => null,
- buildSystemPrompt: () => "",
- } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
-
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- const exited = vi.fn();
- adapter.on("exit", exited);
-
- const startPromise = adapter.start({ text: "hello" }); // createSession() still pending
- const stopPromise = adapter.stop(); // races the in-flight start()
-
- // Let `driver.createSession()` resolve now that both calls are in flight.
- resolveCreateSession(new SdkRuntimeSession(handle, "sess_1"));
- await Promise.all([startPromise, stopPromise]);
-
- expect(disposed).toHaveBeenCalledTimes(1); // the session got cleaned up, not orphaned
- expect(promptSent).not.toHaveBeenCalled(); // no turn fired into a stopped session
- expect(exited).toHaveBeenCalledTimes(1);
- });
-
- // Regression test: it's not enough for the racing stop() to eventually
- // dispose and emit "exit" — `start()` must not resolve "successfully"
- // BEFORE that happens. `doSpawn` dispatches `{type: "spawned"}` the
- // instant `start()` resolves; if that happened while `stop()`'s own
- // disposal (e.g. a slow vendor `dispose()`) was still pending, the manager
- // would see a session still in its map and (correctly, per its own
- // identity check) dispatch `spawned` — a real, if brief, "running" state
- // for a session that's already mid-teardown and never ran a turn.
- it("start() does not resolve until a racing stop()'s disposal has fully finished (exit fires strictly before start() resolves)", async () => {
- let resolveCreateSession!: (session: SdkRuntimeSession) => void;
- let resolveDispose!: () => void;
- const order: string[] = [];
- const handle: SdkSessionHandle = {
- prompt: vi.fn(),
- steer: vi.fn(),
- dispose: () =>
- new Promise<void>((resolve) => {
- resolveDispose = () => {
- order.push("dispose-settled");
- resolve();
- };
- }),
- };
- const createSession = vi.fn(
- () =>
- new Promise<SdkRuntimeSession>((resolve) => {
- resolveCreateSession = (session) => resolve(session);
- }),
- );
- const driver = {
- id: "fake-sdk",
- lifecycle: { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const,
- session: { recovery: "resume_or_fresh" } as const,
- model: { detectedModelsVerifiedAs: "launchable", toLaunchSpec: () => ({ params: {} }) } as const,
- probe: () => ({ status: "healthy" as const }),
- spawn: async () => {
- throw new Error("unsupported");
- },
- createSession,
- parseLine: () => [],
- currentSessionId: null,
- encodeStdinMessage: () => null,
- buildSystemPrompt: () => "",
- } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
-
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- adapter.on("exit", () => order.push("exit-emitted"));
-
- const startPromise = adapter.start({ text: "hello" }).then(() => order.push("start-resolved"));
- const stopPromise = adapter.stop();
- resolveCreateSession(new SdkRuntimeSession(handle, "sess_1"));
-
- // Give both chains plenty of microtasks to progress WITHOUT resolving
- // dispose() yet — start() must still be pending at this point.
- for (let i = 0; i < 10; i++) await Promise.resolve();
- expect(order).toEqual([]); // neither exit nor start-resolved yet — dispose() is still pending
-
- resolveDispose();
- await Promise.all([startPromise, stopPromise]);
-
- expect(order).toEqual(["dispose-settled", "exit-emitted", "start-resolved"]);
- });
-});
-
-describe("SdkManagedSession — start() does not block on the whole first turn", () => {
- /**
- * Regression test for the production crash:
- * Error: Agent is already processing. Specify streamingBehavior
- * ('steer' or 'followUp') to queue the message.
- *
- * `start()` used to `await` the whole first `send()` (a vendor SDK's
- * `prompt()` doesn't resolve until the entire turn, including tool calls,
- * finishes). That meant `AgentProcessManager` didn't dispatch
- * `{type: "spawned"}` — and so didn't consider the agent "busy" — until
- * long after the turn had actually started, so a wake that arrived mid-turn
- * got queued instead of routed as an immediate "steer", then misrouted as
- * an `idle` send once the turn finally ended.
- */
- function fakeSdkDriverWithSlowFirstTurn(): {
- driver: Driver & { createSession: NonNullable<Driver["createSession"]> };
- resolveFirstTurn: () => void;
- rejectFirstTurn: (err: unknown) => void;
- steerCalls: string[];
- } {
- let session: SdkRuntimeSession;
- const steerCalls: string[] = [];
- let resolveFirstTurn!: () => void;
- let rejectFirstTurn!: (err: unknown) => void;
- const handle: SdkSessionHandle = {
- prompt: () =>
- new Promise<void>((resolve, reject) => {
- resolveFirstTurn = resolve;
- rejectFirstTurn = reject;
- }),
- steer: (text: string) => {
- steerCalls.push(text);
- },
- };
- const createSession = vi.fn(async () => {
- session = new SdkRuntimeSession(handle, "sess_1");
- return session;
- });
- const driver = {
- id: "fake-sdk",
- lifecycle: { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const,
- session: { recovery: "resume_or_fresh" } as const,
- model: { detectedModelsVerifiedAs: "launchable", toLaunchSpec: () => ({ params: {} }) } as const,
- probe: () => ({ status: "healthy" as const }),
- spawn: async () => {
- throw new Error("unsupported");
- },
- createSession,
- parseLine: () => [],
- currentSessionId: null,
- encodeStdinMessage: () => null,
- buildSystemPrompt: () => "",
- } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
- return {
- driver,
- resolveFirstTurn: () => resolveFirstTurn(),
- rejectFirstTurn: (err) => rejectFirstTurn(err),
- steerCalls,
- };
- }
-
- it("start() resolves before the first turn's prompt() promise settles", async () => {
- const { driver } = fakeSdkDriverWithSlowFirstTurn();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
-
- // If start() awaited the whole turn, this would hang forever (the turn's
- // prompt() promise is never resolved in this test) — the fact it resolves
- // at all is the assertion.
- await adapter.start({ text: "hello" });
- });
-
- it("a wake that arrives while the first turn is still in flight is delivered as a real steer, not queued until turn_end", async () => {
- const { driver, steerCalls } = fakeSdkDriverWithSlowFirstTurn();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
-
- await adapter.start({ text: "hello" }); // first turn still pending underneath
- const result = adapter.send({ text: "mid-turn wake", mode: "busy" });
-
- expect(result).toEqual({ ok: true });
- expect(steerCalls).toEqual(["mid-turn wake"]);
- });
-
- it("a first-turn rejection surfaces as a runtime_event error instead of an unhandled rejection", async () => {
- // As of plans/sdk-runtime-session-live-isstreaming-guard.md,
- // SdkRuntimeSession.send() itself catches a vendor SDK rejection and
- // reports it as a normal `runtime_event: {kind: "error"}` — visible on
- // the agent's own event stream — rather than rejecting and relying on
- // this adapter's `.catch()` → `"error"` EventEmitter event (that path
- // still exists as a last-resort net, but no longer fires for this case).
- const { driver, rejectFirstTurn } = fakeSdkDriverWithSlowFirstTurn();
- const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
- const events: unknown[] = [];
- const errors: unknown[] = [];
- adapter.on("runtime_event", (e) => events.push(e));
- adapter.on("error", (e) => errors.push(e));
-
- await adapter.start({ text: "hello" });
- rejectFirstTurn(new Error("Agent is already processing"));
- await new Promise((r) => setTimeout(r, 0));
-
- expect(errors).toEqual([]);
- expect(events).toContainEqual({ kind: "error", message: "Agent is already processing" });
- });
-});
diff --git a/src/daemon/src/runtime/sdkManagedSession.ts b/src/daemon/src/runtime/sdkManagedSession.ts
deleted file mode 100644
index 4394ccd77..000000000
--- a/src/daemon/src/runtime/sdkManagedSession.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-/**
- * SdkManagedSession — bridges an in-process SDK driver's `createSession` into
- * the `ManagedSession` contract `AgentProcessManager.doSpawn` drives, the same
- * way `ChildProcessRuntimeSession` does for CLI drivers.
- *
- * The manager subscribes to `"runtime_event"`/`"error"`/`"exit"` right after
- * construction, BEFORE calling `.start()` (see `managerRuntime.ts::doSpawn`).
- * This class's own `EventEmitter` exists from construction for exactly that
- * reason: `.on()` calls made before `.start()` resolves are never missed.
- *
- * `.start()` then does, in order: (1) call `driver.createSession()` — which
- * builds and wires the vendor SDK session but does NOT fire the first turn —
- * (2) proxy the returned session's events through to this adapter's emitter,
- * (3) only THEN send the first turn via `.send(text, "idle")`. That ordering
- * is what fixes the event-loss bug a driver could otherwise hit: a plain
- * `EventEmitter.emit()` (unlike a child process's buffered stdout pipe) drops
- * events fired before any listener is attached.
- *
- * `.start()` does NOT await that first `.send()` to completion — it resolves
- * as soon as the turn is ACCEPTED, mirroring `ChildProcessRuntimeSession`
- * (whose `.start()` resolves once the process is spawned, not once it exits).
- * `AgentProcessManager` only dispatches `{type: "spawned"}` after `.start()`
- * resolves, and only *that* dispatch makes the manager treat the agent as
- * "busy" for the duration of the turn. Awaiting the whole turn here — a
- * vendor SDK's `prompt()` doesn't resolve until the turn (incl. tool calls)
- * finishes — delayed that dispatch by the entire turn length, so a wake that
- * arrived mid-turn wasn't recognized as "steer a running agent" and instead
- * got queued until turn_end, where it was misrouted as an `idle` send into an
- * agent the vendor SDK still considered mid-turn — throwing "Agent is
- * already processing". A rejected first turn is reported via the `"error"`
- * event instead (same path `doSpawn`'s pre-handshake `error` listener uses).
- */
-import { EventEmitter } from "events";
-import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
-import type { SdkRuntimeSession } from "./sdkRuntimeSession.js";
-import { SESSION_STOP_GRACE_MS } from "./killTree.js";
-
-type SdkCapableDriver = Driver & { createSession: NonNullable<Driver["createSession"]> };
-
-export class SdkManagedSession {
- private readonly events = new EventEmitter();
- private inner: SdkRuntimeSession | null = null;
- private startedSessionId: string | null = null;
- private exited = false;
- // Set synchronously (before any `await`) by `start()`. `stop()` awaits
- // this so it never disposes/exits while `driver.createSession()` is still
- // in flight — see `stop()`'s doc comment for why that matters.
- private starting: Promise<void> | null = null;
- private stopRequested = false;
- // Set synchronously (before any `await`) by `stop()`. `start()` awaits
- // this — when it sees `stopRequested` — before resolving, so it can never
- // resolve "successfully" in the gap between a racing `stop()` skipping the
- // first turn and that same `stop()` actually finishing disposal + emitting
- // `"exit"`. Without this, `doSpawn`'s `.then()` would see `start()`
- // resolve WHILE the session is still tracked in the manager's map (`stop()`
- // hasn't reached `emitExit()`'s synchronous `this.sessions.delete()` yet)
- // and dispatch `{type: "spawned"}` — a real, if brief, "running" state for
- // a session that never actually ran a turn and is already being torn down.
- private stopping: Promise<void> | null = null;
-
- constructor(
- private readonly driver: SdkCapableDriver,
- private readonly ctx: LaunchContext,
- private readonly deps: SdkDriverDeps,
- ) { }
-
- on(event: string, cb: (...args: unknown[]) => void): void {
- this.events.on(event, cb);
- }
-
- async start(input: { text: string; sessionId?: string }): Promise<{ ok: boolean }> {
- const launchCtx: LaunchContext = {
- ...this.ctx,
- prompt: input.text,
- config: { ...this.ctx.config, sessionId: input.sessionId ?? this.ctx.config.sessionId },
- };
- // `managerRuntime.ts::doSpawn` puts this session into its map BEFORE
- // this promise settles, so a `stop()` (effect-driven or the public
- // `AgentProcessManager.stop()`) can legitimately race a still-in-flight
- // `driver.createSession()`. Stashing the promise lets `stop()` wait for
- // `this.inner` to actually exist instead of disposing nothing and
- // leaving this call free to wire up and prompt a session nobody tracks
- // anymore.
- this.starting = (async () => {
- const inner = await this.driver.createSession(launchCtx, this.deps);
- this.inner = inner;
- this.startedSessionId = inner.currentSessionId;
- inner.on("runtime_event", (...args: unknown[]) => this.events.emit("runtime_event", ...args));
- })();
- await this.starting;
- if (this.stopRequested) {
- // A stop() raced this start() — don't fire a turn into a session
- // that's already being torn down, and don't resolve until that
- // teardown (disposal + `"exit"`) has fully finished (see `stopping`'s
- // doc comment above for why resolving any earlier is unsafe).
- if (this.stopping) await this.stopping.catch(() => { });
- return { ok: true };
- }
- // Fire-and-forget — see the class doc comment for why this must NOT be
- // awaited. A rejection (e.g. the vendor SDK throwing before any
- // runtime_event ever fires) surfaces as an "error" event instead.
- void this.inner!.send(input.text, "idle").catch((err: unknown) => this.events.emit("error", err));
- return { ok: true };
- }
-
- send(input: { text: string; mode: "busy" | "idle" }): { ok: boolean; reason?: string } {
- if (!this.inner) return { ok: false, reason: "not_started" };
- void this.inner.send(input.text, input.mode).catch((err: unknown) => this.events.emit("error", err));
- return { ok: true };
- }
-
- /**
- * Unlike `ChildProcessRuntimeSession` — where killing the process makes the
- * OS emit its own `exit` shortly after, which is what actually notifies
- * `managerRuntime.ts`'s `session.on("exit", ...)` listener — there's no
- * underlying process here to do that for us. `inner.dispose()` just frees
- * SDK resources; it doesn't fire anything on `this.events`. So `stop()`
- * must emit `"exit"` itself once disposal settles (even if it throws),
- * or the manager's exit listener never runs: the session is never removed
- * from `AgentProcessManager`'s map and the FSM never leaves "stopping".
- *
- * BOUNDED FORCE (plans/daemon-fsm-desync.md batch S): a child process has a
- * physical backstop — `killProcessTree` escalates to SIGKILL, which an
- * unresponsive process cannot survive, so its `exit` is guaranteed. An
- * in-process SDK has no such backstop: if `inner.stop()` never settles (a
- * vendor SDK wedged mid-dispose), the `finally` below never runs and the FSM
- * is stuck `stopping` forever — the same "recovery never completes" failure
- * this whole plan attacks, one layer down. So we bound the wait: `inner.stop()`
- * races a `forceAfterMs` deadline (default `SESSION_STOP_GRACE_MS`, matching
- * the child grace the manager already passes), and whichever settles first,
- * `emitExit()` fires. This is SDK's SIGKILL-equivalent: a GUARANTEED exit.
- * On the timeout path the inner session is abandoned (best-effort `abort`) —
- * we stop awaiting it, so a wedged dispose can't pin the agent.
- *
- * `stopRequested` is set synchronously (before awaiting `starting`) so a
- * `start()` that's still mid-flight sees it as soon as `driver.createSession()`
- * resolves and skips firing the first turn (see `start()`).
- */
- async stop(opts?: { reason?: string; forceAfterMs?: number }): Promise<void> {
- this.stopRequested = true;
- const forceAfterMs = opts?.forceAfterMs ?? SESSION_STOP_GRACE_MS;
- this.stopping = (async () => {
- try {
- if (this.starting) await this.starting.catch(() => { });
- const inner = this.inner;
- if (!inner) return;
- // Race disposal against the force deadline. `inner.stop()` may reject
- // promptly (surfaced to the caller — see the dispose-rejects test) or
- // hang indefinitely (the wedged-SDK case this bound exists for). A
- // timeout WIN means we abandon the inner session rather than await it.
- let timer: ReturnType<typeof setTimeout> | undefined;
- const forced = new Promise<"forced">((resolve) => {
- timer = setTimeout(() => resolve("forced"), forceAfterMs);
- timer.unref?.();
- });
- const stopped = inner.stop().then(() => "stopped" as const);
- // If the deadline wins the race, `stopped` becomes the loser and its
- // eventual rejection (a wedged dispose that later throws) would be
- // unhandled — attach a no-op catch so it's marked handled. This does
- // NOT swallow a PROMPT rejection from the race itself: `Promise.race`
- // still sees `stopped` reject first in that case and rethrows it, so
- // `stop()` rejects (dispose-rejects test) while `emitExit` still fires.
- stopped.catch(() => { });
- try {
- const outcome = await Promise.race([stopped, forced]);
- if (outcome === "forced") {
- // Wedged dispose — abandon the inner session so it can't pin us.
- // Best-effort abort; ignore anything it throws.
- try {
- (inner as unknown as { abort?: () => void }).abort?.();
- } catch {
- // no-op: abort is best-effort on a session we're already dropping
- }
- }
- } finally {
- if (timer) clearTimeout(timer);
- }
- } finally {
- this.emitExit();
- }
- })();
- await this.stopping;
- }
-
- private emitExit(): void {
- if (this.exited) return;
- this.exited = true;
- this.events.emit("exit");
- }
-
- get currentSessionId(): string | null {
- return this.inner?.currentSessionId ?? this.startedSessionId;
- }
-}
diff --git a/src/daemon/src/runtime/sdkRuntimeSession.ts b/src/daemon/src/runtime/sdkRuntimeSession.ts
deleted file mode 100644
index 7e112f7ba..000000000
--- a/src/daemon/src/runtime/sdkRuntimeSession.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-/**
- * SdkRuntimeSession — the in-process counterpart to ChildProcessRuntimeSession.
- *
- * `pi` doesn't spawn a child process; it runs the agent in-process
- * via a vendor SDK. They share this thin EventEmitter wrapper: the driver wires
- * the SDK's event callback to `emitEvent`, and `prompt`/`steer`/`abort`/`dispose`
- * are delegated to the SDK session. The daemon consumes the same `runtime_event`
- * stream it gets from child-process sessions, so the rest of the system is
- * transport-agnostic.
- *
- * `send()`'s idle path is a second, independent line of defense against
- * "Agent is already processing" (the manager's own busy/idle bookkeeping in
- * `managerPolicy.ts` is the first — see `plans/wire-pi-runtime-execution.md`'s
- * follow-up section). It doesn't trust the caller's `mode: "idle"` at face
- * value; it re-checks the vendor SDK's live `isStreaming` at the moment of
- * delivery and degrades to a `steer()` instead of ever calling `prompt()` on
- * a session that's actually still busy. That way a future FSM bug (a
- * different driver, a race we haven't hit yet) can't reach the vendor SDK's
- * own throw — worst case it steers instead of prompting, which is always a
- * legal call. See plans/sdk-runtime-session-live-isstreaming-guard.md.
- */
-import { EventEmitter } from "events";
-import type { ParsedEvent, StdinMode } from "../types.js";
-
-/** What a vendor SDK session must expose for the wrapper to drive it. */
-export interface SdkSessionHandle {
- prompt(text: string): void | Promise<void>;
- steer(text: string): void | Promise<void>;
- abort?(): void | Promise<void>;
- dispose?(): void | Promise<void>;
- readonly isStreaming?: boolean;
-}
-
-/** How long, and how often, to poll `isStreaming` before giving up and
- * steering instead of prompting a still-busy session.
- *
- * `IDLE_PROMPT_RETRY_MS = 25` is short enough that a session which finishes
- * within one turn boundary (~100-300ms) is caught on the first or second
- * poll, and small enough that the busy-wait cost is negligible.
- * `IDLE_PROMPT_MAX_WAIT_MS = 1000` is the ceiling before we accept the
- * session is "genuinely still working" and fall through to `steer` — anything
- * higher measurably delays first-token latency without changing outcomes in
- * the traces we've captured.
- */
-const IDLE_PROMPT_RETRY_MS = 25;
-const IDLE_PROMPT_MAX_WAIT_MS = 1000;
-
-function delay(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-function errorMessage(err: unknown): string {
- return err instanceof Error ? err.message : String(err);
-}
-
-export class SdkRuntimeSession {
- private readonly events = new EventEmitter();
- private sentInit = false;
-
- constructor(
- private readonly handle: SdkSessionHandle,
- private readonly sessionId: string,
- ) {}
-
- on(event: string, cb: (...args: unknown[]) => void): void {
- this.events.on(event, cb);
- }
-
- /** Driver calls this from the SDK's event callback with mapped events. */
- emitEvents(events: ParsedEvent[]): void {
- if (!this.sentInit && events.length > 0) {
- this.sentInit = true;
- this.events.emit("runtime_event", { kind: "session_init", sessionId: this.sessionId } as ParsedEvent);
- }
- for (const e of events) this.events.emit("runtime_event", e);
- }
-
- /**
- * busy → SDK steer, always. idle → SDK prompt, UNLESS the handle reports
- * it's still streaming right now, in which case wait briefly for it to
- * clear and fall back to steer() if it doesn't — see the class doc comment.
- * Never rejects: a vendor SDK exception is reported as a normal
- * `runtime_event` (`{kind: "error"}`) instead, so callers can treat
- * `send()` as fire-and-forget without an unhandled rejection.
- *
- * A failed `prompt()` also gets a synthetic `turn_end` right behind its
- * `error` event — unlike a failed `steer()` (which injects into an
- * *already-running* turn that will still emit its own real `turn_end`
- * later regardless of whether the steer landed), a `prompt()` call IS the
- * attempted turn: if it throws, no turn ever started and nothing else
- * will ever say this one is over. Without this, the caller (see
- * `SdkManagedSession.start()`, which fires the first turn this way) keeps
- * treating the agent as busy/running until the stall watchdog eventually
- * notices no progress and terminates it minutes later.
- */
- async send(text: string, mode: StdinMode): Promise<{ ok: boolean }> {
- try {
- if (mode === "busy") {
- await this.handle.steer(text);
- return { ok: true };
- }
- const stillStreaming = this.handle.isStreaming && !(await this.waitForStreamingToClear());
- if (stillStreaming) {
- await this.handle.steer(text);
- return { ok: true };
- }
- try {
- await this.handle.prompt(text);
- } catch (err) {
- this.emitEvents([
- { kind: "error", message: errorMessage(err) },
- { kind: "turn_end", sessionId: this.sessionId },
- ]);
- }
- } catch (err) {
- this.emitEvents([{ kind: "error", message: errorMessage(err) }]);
- }
- return { ok: true };
- }
-
- /** Polls `handle.isStreaming` until it clears or the deadline passes. Returns true once cleared. */
- private async waitForStreamingToClear(): Promise<boolean> {
- const deadline = Date.now() + IDLE_PROMPT_MAX_WAIT_MS;
- while (this.handle.isStreaming) {
- if (Date.now() >= deadline) return false;
- await delay(IDLE_PROMPT_RETRY_MS);
- }
- return true;
- }
-
- async stop(): Promise<void> {
- if (this.handle.isStreaming && this.handle.abort) await this.handle.abort();
- await this.handle.dispose?.();
- }
-
- get currentSessionId(): string {
- return this.sessionId;
- }
-}
diff --git a/src/daemon/src/runtimeConfig.test.ts b/src/daemon/src/runtimeConfig.test.ts
index 1adb7b168..5299974ff 100644
--- a/src/daemon/src/runtimeConfig.test.ts
+++ b/src/daemon/src/runtimeConfig.test.ts
@@ -1,46 +1,60 @@
import { describe, it, expect } from "vitest";
-import { resolveLaunchFields } from "./runtimeConfig";
+import { runtimeModelName, toAgentBackendSelection } from "./runtimeConfig";
import { makeRuntimeConfig } from "./runtimeConfig";
-import { buildAntigravityArgs } from "./drivers/antigravity";
-import type { LaunchContext } from "./types";
-describe("resolveLaunchFields — model id resolution across runtimes", () => {
- for (const runtime of ["claude", "codex", "gemini", "kimi"]) {
- it(`${runtime}: {kind:"named",name:"opus"} → f.model === "opus"`, () => {
- const f = resolveLaunchFields(makeRuntimeConfig({ runtime, model: { kind: "named", name: "opus" } }));
- expect(f.model).toBe("opus");
+describe("runtimeModelName", () => {
+ for (const runtime of ["claude", "codex", "cursor", "opencode", "pi"]) {
+ it(`${runtime}: projects a named model without interpreting the backend`, () => {
+ expect(runtimeModelName(makeRuntimeConfig({ runtime, model: { kind: "named", name: "opus" } })))
+ .toBe("opus");
});
}
- it("claude: a custom model additionally sets ANTHROPIC_CUSTOM_MODEL_OPTION", () => {
- const f = resolveLaunchFields(makeRuntimeConfig({ runtime: "claude", model: { kind: "custom", name: "my-ft" } }));
- expect(f.model).toBe("my-ft");
- expect(f.providerEnv.ANTHROPIC_CUSTOM_MODEL_OPTION).toBe("my-ft");
+ it("projects custom models without provider or environment interpretation", () => {
+ expect(runtimeModelName(makeRuntimeConfig({ runtime: "claude", model: { kind: "custom", name: "my-ft" } })))
+ .toBe("my-ft");
});
- it("codex: a custom model does NOT set the claude-specific env", () => {
- const f = resolveLaunchFields(makeRuntimeConfig({ runtime: "codex", model: { kind: "custom", name: "my-ft" } }));
- expect(f.model).toBe("my-ft");
- expect(f.providerEnv.ANTHROPIC_CUSTOM_MODEL_OPTION).toBeUndefined();
+ it("returns undefined for absent and default selections", () => {
+ expect(runtimeModelName(undefined)).toBeUndefined();
+ expect(runtimeModelName(makeRuntimeConfig({ runtime: "cursor" }))).toBeUndefined();
});
+});
- it("default model → f.model is undefined", () => {
- const f = resolveLaunchFields(makeRuntimeConfig({ runtime: "gemini" }));
- expect(f.model).toBeUndefined();
+describe("toAgentBackendSelection", () => {
+ it("maps every runtime into the agent-driver contract", () => {
+ expect(toAgentBackendSelection(makeRuntimeConfig({ runtime: "codex" }))).toMatchObject({ backend: "codex" });
+ expect(toAgentBackendSelection(makeRuntimeConfig({ runtime: "cursor" }))).toMatchObject({ backend: "cursor" });
+ expect(toAgentBackendSelection(makeRuntimeConfig({ runtime: "opencode" }))).toMatchObject({ backend: "opencode" });
+ expect(toAgentBackendSelection(makeRuntimeConfig({ runtime: "pi" }))).toMatchObject({
+ backend: "pi",
+ config: { provider: { kind: "default" } },
+ });
+ });
+
+ it("maps Claude custom endpoints and Pi built-in providers", () => {
+ expect(toAgentBackendSelection(makeRuntimeConfig({
+ runtime: "claude",
+ provider: { kind: "custom", apiUrl: "https://example.invalid", apiKey: "claude-key" },
+ }))).toMatchObject({
+ backend: "claude",
+ config: {
+ provider: { kind: "custom_endpoint", apiUrl: "https://example.invalid", apiKey: "claude-key" },
+ },
+ });
+ expect(toAgentBackendSelection(makeRuntimeConfig({
+ runtime: "pi",
+ provider: { kind: "pi-builtin", providerId: "openai", apiKey: "pi-key" },
+ }))).toMatchObject({
+ backend: "pi",
+ config: { provider: { kind: "builtin", providerId: "openai", apiKey: "pi-key" } },
+ });
});
-});
-describe("antigravity — discards the model at launch", () => {
- it("buildAntigravityArgs emits no model arg even when a model is set", () => {
- const ctx = {
- workingDirectory: "/tmp",
- agentId: "a1",
- standingPrompt: "",
- prompt: "hi",
- config: { runtimeConfig: makeRuntimeConfig({ runtime: "antigravity", model: { kind: "named", name: "opus" } }) },
- } as unknown as LaunchContext;
- const args = buildAntigravityArgs(ctx);
- expect(args).not.toContain("--model");
- expect(args.join(" ")).not.toContain("opus");
+ it("rejects unknown runtimes", () => {
+ expect(() => toAgentBackendSelection({
+ ...makeRuntimeConfig({ runtime: "claude" }),
+ runtime: "unknown",
+ } as never)).toThrow("Unknown runtime: unknown");
});
});
diff --git a/src/daemon/src/runtimeConfig.ts b/src/daemon/src/runtimeConfig.ts
index f264aaef3..8c4c8b6ab 100644
--- a/src/daemon/src/runtimeConfig.ts
+++ b/src/daemon/src/runtimeConfig.ts
@@ -9,11 +9,9 @@
* `plans/minimal-wake-queue-unread-notice.md`). Re-exported here so existing
* daemon call sites keep importing from `./runtimeConfig.js` unchanged.
*
- * This file keeps `resolveLaunchFields`/`ResolvedLaunchFields` — daemon-only,
- * host-side resolution of a `RuntimeConfig` into flat launch fields (CLI args +
- * env) that each driver consumes. Config is start-time: changing it means
- * relaunching the agent with a new RuntimeConfig (there is no live-reconfigure
- * path — model/effort are spawn-time args).
+ * The daemon only translates the shared wire shape into the public agent-driver
+ * contract and projects backend-neutral display fields. Backend launch/provider
+ * interpretation belongs exclusively to `@alook/agent-driver`.
*/
export {
@@ -28,93 +26,19 @@ export type {
RuntimeConfig,
} from "@alook/shared/runtime-config";
-import type { ReasoningEffort, RuntimeConfig } from "@alook/shared/runtime-config";
+import type { RuntimeConfig } from "@alook/shared/runtime-config";
+import {
+ toBuiltinBackendSelection,
+ type BuiltinBackendSelection,
+} from "@alook/agent-driver";
-/* ------------------------------------------------------------------ */
-/* Resolution — RuntimeConfig → flat launch fields */
-/* ------------------------------------------------------------------ */
+export type AgentBackendSelection = BuiltinBackendSelection;
-/**
- * Flat fields drivers consume, derived from a RuntimeConfig. `model` is the
- * resolved model id (or undefined ⇒ runtime default); `fastMode` is the mode
- * flattened to a bool; `envVars` carries provider-derived env (custom endpoint
- * keys, custom-model option, Pi provider key).
- */
-export interface ResolvedLaunchFields {
- /** Resolved model id, or undefined to mean "runtime default". */
- model?: string;
- reasoningEffort?: ReasoningEffort;
- fastMode: boolean;
- command?: string;
- disallowedTools?: string;
- /** User-supplied env (controlled keys stripped). Lower-precedence layer. */
- envVars: Record<string, string>;
- /**
- * Provider/model-DERIVED env (custom endpoint keys, Claude custom-model option,
- * Pi provider key). Kept separate from `envVars` so the spawn-env merge can put
- * these in a protected layer that user/driver env can't accidentally shadow.
- */
- providerEnv: Record<string, string>;
-}
-
-/** Env key per Pi built-in provider id. Extend as providers are added. */
-const PI_BUILTIN_PROVIDER_ENV_KEYS: Record<string, string> = {
- google: "GEMINI_API_KEY",
- openai: "OPENAI_API_KEY",
- openrouter: "OPENROUTER_API_KEY",
-};
-
-/** Env keys the host must not set directly — provider config owns them. */
-const CONTROLLED_ENV_KEYS = new Set([
- "ANTHROPIC_BASE_URL",
- "ANTHROPIC_API_KEY",
- "ANTHROPIC_CUSTOM_MODEL_OPTION",
- ...Object.values(PI_BUILTIN_PROVIDER_ENV_KEYS),
-]);
-
-/**
- * Resolve from a possibly-absent RuntimeConfig (test contexts may omit it):
- * returns runtime-default fields when `config` is undefined.
- */
-export function resolveLaunchFieldsOrDefault(config: RuntimeConfig | undefined): ResolvedLaunchFields {
- if (!config) return { fastMode: false, envVars: {}, providerEnv: {} };
- return resolveLaunchFields(config);
+export function toAgentBackendSelection(config: RuntimeConfig): AgentBackendSelection {
+ return toBuiltinBackendSelection(config);
}
-export function resolveLaunchFields(config: RuntimeConfig): ResolvedLaunchFields {
- const envVars: Record<string, string> = {};
- const providerEnv: Record<string, string> = {};
-
- // User env, minus the keys provider config controls.
- for (const [k, v] of Object.entries(config.envVars ?? {})) {
- if (!CONTROLLED_ENV_KEYS.has(k)) envVars[k] = v;
- }
-
- // Model → id + custom-model env (Claude custom models go via env, not --model).
- let model: string | undefined;
- if (config.model.kind === "named") model = config.model.name;
- else if (config.model.kind === "custom") {
- model = config.model.name;
- if (config.runtime === "claude") providerEnv.ANTHROPIC_CUSTOM_MODEL_OPTION = config.model.name;
- }
-
- // Provider → endpoint / key env.
- const p = config.provider;
- if (p?.kind === "custom" && config.runtime === "claude") {
- providerEnv.ANTHROPIC_BASE_URL = p.apiUrl;
- providerEnv.ANTHROPIC_API_KEY = p.apiKey;
- } else if (p?.kind === "pi-builtin") {
- const key = PI_BUILTIN_PROVIDER_ENV_KEYS[p.providerId];
- if (key) providerEnv[key] = p.apiKey;
- }
-
- return {
- model,
- reasoningEffort: config.reasoningEffort,
- fastMode: config.mode.kind === "fast",
- command: config.command,
- disallowedTools: config.disallowedTools,
- envVars,
- providerEnv,
- };
+/** Backend-neutral projection used only for manager logs and trace metadata. */
+export function runtimeModelName(config: RuntimeConfig | undefined): string | undefined {
+ return config?.model.kind === "default" ? undefined : config?.model.name;
}
diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.ts
index ef02d0d39..5240d37c9 100644
--- a/src/daemon/src/server/wsControlChannel.test.ts
+++ b/src/daemon/src/server/wsControlChannel.test.ts
@@ -485,6 +485,42 @@ describe("WsControlChannel — downlink HostCommand validation (convergence #6)"
await stopping;
});
+ it("routes one active-session delivery for a five-wake burst until model-seen covers the watermark", async () => {
+ const { ch } = makeChannel();
+ const received: Array<Extract<HostCommand, { type: "agent:wake" }>> = [];
+ ch.onCommand(async (command) => {
+ if (command.type !== "agent:wake") return;
+ received.push(command);
+ await ch.reportWakeAck({
+ agentId: command.agentId,
+ launchId: command.launchId,
+ status: "ok",
+ });
+ });
+ const command = (seq: number): Extract<HostCommand, { type: "agent:wake" }> => ({
+ type: "agent:wake",
+ agentId: "bot_1",
+ config: { runtime: "codex" } as never,
+ launchId: `launch_${seq}`,
+ unreadNotice: {
+ kind: "unread_notice",
+ channel: "/demo#1234/general",
+ latestSeq: seq,
+ },
+ });
+
+ await ch.ingestCommand(command(1));
+ await ch.reportAgentActivity({ agentId: "bot_1", state: "running" });
+ ch.recordModelSeen("bot_1", [{ channel: "/demo#1234/general", seq: "#1" }]);
+
+ for (let seq = 2; seq <= 6; seq++) await ch.ingestCommand(command(seq));
+ expect(received.map((wake) => wake.unreadNotice.latestSeq)).toEqual([1, 2]);
+
+ ch.recordModelSeen("bot_1", [{ channel: "/demo#1234/general", seq: "#6" }]);
+ await Promise.resolve();
+ expect(received.map((wake) => wake.unreadNotice.latestSeq)).toEqual([1, 2]);
+ });
+
it("dispatches each valid arm unchanged (happy path — the transparent gate)", () => {
for (const frame of [realWake, realReset, realNap, realModelSwitch, realStop]) {
const { sockets, received } = driven();
diff --git a/src/daemon/src/types.ts b/src/daemon/src/types.ts
deleted file mode 100644
index 9d91d7120..000000000
--- a/src/daemon/src/types.ts
+++ /dev/null
@@ -1,389 +0,0 @@
-/**
- * Core types for the daemon's driver layer.
- *
- * A *driver* adapts one AI coding runtime (Claude Code, Codex, Gemini, Kimi,
- * Pi, …) to a single uniform interface the daemon drives. The daemon never
- * speaks a runtime's native protocol directly — it goes through a driver, which
- * knows how to:
- * - spawn / create the runtime session,
- * - encode an outgoing user message onto the runtime's input channel,
- * - normalize the runtime's stdout (or SDK event stream) into a small set of
- * `ParsedEvent`s the daemon understands.
- *
- * This file is a clean-room reconstruction of the shapes observed in
- * a production agent-runtime daemon. Names and structure are reverse-engineered to
- * document the protocol, not copied from source.
- */
-
-/* ------------------------------------------------------------------ */
-/* Lifecycle & capability descriptors */
-/* ------------------------------------------------------------------ */
-
-/**
- * How the runtime process maps onto "turns".
- *
- * - `persistent`: one long-lived process spans many turns. New user messages
- * are written onto its still-open input channel (stdin / SDK call).
- * - `per_turn`: the process handles exactly one turn and exits. A new message
- * means a brand-new process.
- */
-export type DriverLifecycle =
- | {
- kind: "persistent";
- /**
- * How busy-time stdin writes are timed:
- * - `direct`: write immediately (runtime tolerates injection any time).
- * - `gated`: hold writes until a safe stream boundary (Claude — avoids
- * colliding with in-flight signed thinking blocks).
- */
- stdin: "direct" | "gated";
- /** What to do if a message arrives while a turn is in flight. */
- inFlightWake: "steer" | "queue";
- }
- | {
- kind: "per_turn";
- /**
- * When to spawn:
- * - `immediate`: spawn as soon as woken.
- * - `defer_until_concrete_message`: don't spawn for bookkeeping-only
- * wakes (e.g. a system task event); wait for a real message.
- */
- start: "immediate" | "defer_until_concrete_message";
- /** How the per-turn process ends. */
- exit: "natural" | "terminate_on_turn_end";
- /** A wake mid-turn either starts a new process or folds into the pending run. */
- inFlightWake: "spawn_new" | "coalesce_into_pending";
- };
-
-/** Session recovery strategy across restarts. */
-export interface DriverSession {
- /** `resume_or_fresh`: resume by sessionId if we have one, else start fresh. */
- recovery: "resume_or_fresh";
-}
-
-/**
- * How a model id is turned into launch configuration. CLI drivers emit `args`;
- * in-process SDK drivers emit `params`.
- */
-export interface DriverModel {
- /**
- * - `launchable`: detected models are real and can be launched as-is.
- * - `suggestion_only`: detected models are hints; not passed at launch.
- */
- detectedModelsVerifiedAs: "launchable" | "suggestion_only";
- toLaunchSpec: (
- modelId: string,
- ctx?: LaunchContext,
- opts?: unknown,
- ) => { args: string[] } | { params: Record<string, unknown> };
-}
-
-/**
- * Busy-delivery mode — how a message is delivered while the agent is working.
- * - `direct`: write straight to the input channel.
- * - `gated`: queue until a safe boundary (see `ApmGatedSteering`).
- * - `none`: not supported (per-turn runtimes); the agent polls instead.
- */
-export type BusyDeliveryMode = "direct" | "gated" | "none";
-
-/**
- * `busyDeliveryMode` and `supportsStdinNotification` are DERIVED from `lifecycle`
- * — `lifecycle` is the single source of truth for a driver's delivery model, so
- * the two facts can never drift from it (the pre-convergence duplicate `Driver`
- * fields could — e.g. codex once declared `busyDeliveryMode: "direct"` against a
- * `gated` lifecycle). Verified identity (not approximation) across all 9 drivers.
- *
- * These take `DriverLifecycle` (not the whole `Driver`) to stay a pure data
- * function with no `Driver`-interface cycle.
- *
- * If a future runtime genuinely needs a delivery mode its lifecycle doesn't
- * imply (e.g. persistent-but-poll), express it as a NEW `DriverLifecycle` shape
- * — the canonical source — not a side-channel override field. That keeps the
- * single-source-of-truth invariant this convergence (#4) established.
- */
-export function busyDeliveryModeOf(lifecycle: DriverLifecycle): BusyDeliveryMode {
- return lifecycle.kind === "persistent" ? lifecycle.stdin : "none";
-}
-
-export function supportsStdinNotificationOf(lifecycle: DriverLifecycle): boolean {
- return lifecycle.kind === "persistent";
-}
-
-/**
- * Declarative description of which `RuntimeConfig` fields a driver actually
- * consumes at launch. Enables the platform to render accurate per-driver
- * config surfaces and (in a follow-up) warn on ignored fields.
- *
- * `sessionResumeMode`:
- * - `by-id`: resume the specific `sessionId` the caller asked for.
- * - `most-recent`: driver has no by-id resume — falls back to the CLI's
- * "continue most recent" (see AntigravityDriver).
- * - `none`: no resume support at all.
- *
- * `model` is intentionally omitted here because every driver either uses the
- * model field or explicitly suppresses it; the flag would be trivially true
- * for all drivers except antigravity — a special case documented in comments
- * on that driver's `capabilities` const.
- */
-export interface DriverCapabilities {
- readonly reasoningEffort: boolean;
- readonly fastMode: boolean;
- readonly disallowedTools: boolean;
- readonly command: boolean;
- readonly sessionResumeMode: "by-id" | "most-recent" | "none";
-}
-
-/* ------------------------------------------------------------------ */
-/* Normalized runtime events */
-/* ------------------------------------------------------------------ */
-
-/**
- * The uniform event vocabulary every driver's `parseLine` (or SDK mapper)
- * collapses its native protocol into. The daemon only ever sees these.
- */
-export type ParsedEvent =
- | { kind: "session_init"; sessionId: string }
- | { kind: "thinking"; text: string }
- | { kind: "text"; text: string }
- | { kind: "tool_call"; name: string; input: unknown }
- | { kind: "tool_output"; name: string }
- | { kind: "compaction_started" }
- | { kind: "compaction_finished" }
- | { kind: "review_started" }
- | { kind: "review_finished" }
- | {
- kind: "internal_progress";
- source?: string;
- itemType?: string;
- payloadBytes?: number;
- }
- | {
- kind: "runtime_diagnostic";
- severity?: string;
- source?: string;
- message: string;
- }
- | { kind: "turn_end"; sessionId?: string }
- | { kind: "error"; message: string }
- | {
- kind: "telemetry";
- name: "token_usage" | "rate_limits";
- source: string;
- usageKind?: string;
- attrs: Record<string, unknown>;
- };
-
-/* ------------------------------------------------------------------ */
-/* Launch context & stdin encoding */
-/* ------------------------------------------------------------------ */
-
-/** Everything a driver needs to launch (or create) a runtime session. */
-export interface LaunchContext {
- agentId: string;
- launchId?: string;
- workingDirectory: string;
- /** The fully-assembled system / standing prompt for this agent. */
- standingPrompt: string;
- /** The first user message to deliver (initial turn text). */
- prompt: string;
- /** Path to the injected Alook CLI wrapper (host-supplied; see cliTransport). */
- agentCliPath?: string;
- /**
- * Positive opt-in for a launch that has NO host CLI on purpose (test / mock
- * harness): `prepareCliTransport` then skips the agent-CLI shim silently
- * instead of failing loud. Real launches MUST NOT set this — a real launch
- * with no resolvable CLI path is a hard fault (the agent's `alook` would fall
- * through to the host CLI, which lacks the agent subcommands). The flag, not
- * "agentCliPath is empty", is the mock signal: an empty path is exactly the
- * bug shape we want to catch, so it can't also mean "mock".
- */
- mockCliTransport?: boolean;
- daemonApiKey?: string;
- cliTransportTraceDir?: string;
- /**
- * Zero-trust credential handoff (REQUIRED to spawn a CLI runtime). The host
- * starts one `startCredentialProxy` and passes its `broker` + `proxyUrl` here;
- * `cliTransport` mints a per-launch `vch_` voucher and the agent never sees the
- * real key. There is no plaintext fallback — see `src/credentials`.
- */
- credentialProxy?: CredentialProxyHandoff;
- config: LaunchConfig;
-}
-
-/** What the host passes so `cliTransport` can mint a voucher for the child. */
-export interface CredentialProxyHandoff {
- /** Mints/validates the per-launch voucher (bound to the agent's runner key). */
- broker: import("./credentials").CredentialBroker;
- /** URL of the already-running proxy (from `startCredentialProxy`). */
- proxyUrl: string;
- /**
- * The agent's tier-2 runner key the proxy swaps in for this launch's voucher.
- * The daemon obtains it from the server's enrollment (`mintAgentCredential`,
- * authed by the machine key) before spawning the agent.
- */
- runnerKey: string;
- /**
- * Capability scope for this launch's voucher — the host owns the list and
- * passes it in with the rest of the handoff so the driver doesn't carry a
- * parallel default. Injected as `<PREFIX>_ACTIVE_CAPABILITIES` (comma-joined)
- * and stamped into the voucher registration; the proxy enforces per-request.
- */
- capabilities: string[];
-}
-
-export interface LaunchConfig {
- /** Resume target. Absent ⇒ fresh session. */
- sessionId?: string;
- authToken?: string;
- serverUrl?: string;
- /**
- * The structured, versioned runtime configuration (model / provider / mode /
- * reasoningEffort / command). Drivers call `resolveLaunchFields(runtimeConfig)`
- * to turn it into CLI args + env — see `src/runtimeConfig.ts`. Optional only so
- * minimal test contexts can omit it (drivers then use the runtime's default
- * model with no provider/mode overrides).
- */
- runtimeConfig?: import("./runtimeConfig").RuntimeConfig;
- description?: string;
- runtimeContext?: RuntimeContext;
- /** Agent display name (e.g. "Gus"). */
- agentName?: string;
- /**
- * Agent's 4-digit discriminator (the `0042` in `@Gus#4821`). Carried
- * explicitly alongside `agentName` so the git-identity builder doesn't have
- * to re-parse it out of `agentHandle`. See `drivers/gitIdentityEnv.ts`.
- */
- agentDiscriminator?: string;
- /**
- * Agent's global @mention handle, `@name#0042` (e.g. "@Gus#4821"). Every
- * account in Alook — human or agent — has a name plus a 4-digit
- * discriminator; this is the `@`-prefixed pair, unique even when names
- * collide.
- */
- agentHandle?: string;
- /**
- * The global handle (`@name#0042`) of the human user who owns this bot.
- * Sourced from the daemon's `botsById` cache (see `createDaemon.ts`), not
- * server-pushed via `RuntimeConfig` — ownership is immutable post-creation,
- * so it never needs the wake path's live-config precedence.
- */
- ownerHandle?: string;
-}
-
-export interface RuntimeContext {
- agentId: string;
- serverId: string;
- computerId: string;
- computerName: string;
- hostname: string;
- os: string;
- daemonVersion: string;
- workspacePath: string;
-}
-
-/** Mode for an outgoing message written onto the input channel. */
-export type StdinMode = "busy" | "idle";
-
-export interface EncodeOpts {
- mode?: StdinMode;
-}
-
-/* ------------------------------------------------------------------ */
-/* The Driver interface */
-/* ------------------------------------------------------------------ */
-
-export interface SpawnResult {
- process: import("child_process").ChildProcess;
-}
-
-/**
- * What an in-process SDK driver's `createSession` needs injected, so the
- * driver file itself stays dependency-free (no hard dep on the vendor SDK
- * package) — the host builds the real implementations per-launch (they close
- * over the `LaunchContext`) and passes them in. See
- * `drivers/piSdkDeps.ts::createPiSdkDriverDeps` for the only real
- * implementation today.
- */
-export interface SdkDriverDeps {
- /** Build the per-launch spawn env (credential voucher, PATH link, …). */
- buildSpawnEnv: () => Promise<NodeJS.ProcessEnv>;
- /** Create the vendor SDK's session object. Shape is driver-specific. */
- createAgentSession: (
- opts: Record<string, unknown>,
- ) => Promise<{ session: unknown; sessionId: string }>;
-}
-
-/**
- * The contract every runtime adapter implements. Child-process drivers
- * implement `spawn`; in-process SDK drivers implement `createSession` instead
- * (and throw from `spawn`).
- */
-export interface Driver {
- readonly id: string;
- readonly lifecycle: DriverLifecycle;
- readonly session: DriverSession;
- readonly model: DriverModel;
-
- // `supportsStdinNotification` and `busyDeliveryMode` are NOT declared here —
- // they are derived from `lifecycle` via `supportsStdinNotificationOf` /
- // `busyDeliveryModeOf` (single source of truth; see those helpers).
-
- /** True if the runtime takes the standing prompt natively (vs. inline). */
- readonly supportsNativeStandingPrompt?: boolean;
-
- /** Which `RuntimeConfig` fields this driver actually consumes at launch. */
- readonly capabilities: DriverCapabilities;
-
- /** Per-turn runtimes only: terminate the process when the turn ends. */
- readonly terminateProcessOnTurnEnd?: boolean;
- /** Persistent runtimes only: close stdin (rather than keep-alive) on turn end. */
- readonly endStdinOnTurnEnd?: boolean;
- /** Per-turn runtimes only: skip spawning for bookkeeping-only wakes. */
- readonly deferSpawnUntilMessage?: boolean;
-
- /** Detect whether the runtime CLI is installed and its version. */
- probe(): ProbeResult | Promise<ProbeResult>;
-
- /** Spawn the child process (child-process drivers). */
- spawn(ctx: LaunchContext): Promise<SpawnResult>;
-
- /**
- * Create the runtime session for in-process SDK drivers (Pi). Builds and
- * wires the session but does NOT fire the initial prompt — the caller
- * (`SdkManagedSession.start`) attaches its own `"runtime_event"` listener
- * to the returned session first, then sends the first turn, so no early
- * events are lost. Absent on child-process drivers.
- */
- createSession?(
- ctx: LaunchContext,
- deps: SdkDriverDeps,
- ): Promise<import("./runtime/sdkRuntimeSession.js").SdkRuntimeSession>;
-
- /** Parse one stdout line into zero or more normalized events. */
- parseLine(line: string): ParsedEvent[];
-
- /** The active session id, learned from the runtime's init/result events. */
- readonly currentSessionId: string | null;
-
- /**
- * Encode an outgoing user message for the input channel.
- * Returns the wire string (a `\n` is appended by the caller), or `null` if
- * this runtime cannot accept mid-session input.
- */
- encodeStdinMessage(
- text: string,
- sessionId: string | null,
- opts?: EncodeOpts,
- ): string | null;
-
- /** Build the standing/system prompt for this runtime. */
- buildSystemPrompt(config: LaunchConfig, agentId?: string): string;
-}
-
-export interface ProbeResult {
- /** Explicit health signal reported by the daemon. */
- status: "healthy" | "unhealthy";
- version?: string;
- /** Short reason code when unhealthy — e.g. "version_probe_failed". */
- lastError?: string;
-}
diff --git a/src/daemon/src/util/traceSampler.test.ts b/src/daemon/src/util/traceSampler.test.ts
index d4fe08432..1c836915f 100644
--- a/src/daemon/src/util/traceSampler.test.ts
+++ b/src/daemon/src/util/traceSampler.test.ts
@@ -57,7 +57,7 @@ function operationalRow(
resetting: false,
resettingSince: null,
stoppingSince: null,
- apmPhase: "idle",
+ deliveryPhase: "idle",
effects: [],
nowMs,
timeIso: new Date(nowMs).toISOString(),
@@ -142,19 +142,19 @@ describe("traceSampler — ② reconstruction: a wedge is reconstructable from r
it("stuck run → retained rows reconstruct which phase, how long, and the kill", () => {
const { s, out } = collect(30_000);
// Enter the stuck state (edge).
- s.offer(tick("a", 0, { apmPhase: "tool_wait", sinceProgressMs: 0 }));
+ s.offer(tick("a", 0, { deliveryPhase: "tool_wait", sinceProgressMs: 0 }));
// Long unchanged run, no progress — a hang. Ticks every 2s, sinceProgressMs climbs.
for (let t = 2000; t < 121000; t += 2000) {
- s.offer(tick("a", t, { apmPhase: "tool_wait", sinceProgressMs: t }));
+ s.offer(tick("a", t, { deliveryPhase: "tool_wait", sinceProgressMs: t }));
}
// Watchdog fires at 121846ms of no progress → terminate_stalled (sacrosanct).
- s.offer(tick("a", 121846, { apmPhase: "tool_wait", effects: ["terminate_stalled"], sinceProgressMs: 121846 }));
+ s.offer(tick("a", 121846, { deliveryPhase: "tool_wait", effects: ["terminate_stalled"], sinceProgressMs: 121846 }));
// The kill's terminal transition.
s.offer({ agentId: "a", event: "turn_end", status: "stopping", turnActive: true, nowMs: 121850, sinceProgressMs: 0, effects: [] });
const ticks = out.filter((r) => r.event === "tick");
// (a) which phase: the retained ticks show tool_wait.
- expect(ticks.every((r) => r.apmPhase === "tool_wait")).toBe(true);
+ expect(ticks.every((r) => r.deliveryPhase === "tool_wait")).toBe(true);
// (b) how long: the peak sinceProgressMs is retained (on the effects frame),
// self-contained on that row — no join needed.
const peak = Math.max(...out.map((r) => (typeof r.sinceProgressMs === "number" ? r.sinceProgressMs : 0)));
@@ -287,17 +287,17 @@ describe("B1 red gate — turn-span sacred rows", () => {
Math.floor(offsetMs / TICK_EVERY_MS),
PHASES.length - 1,
);
- sampler.offer(operationalRow(agentId, "progress", turnBaseMs + offsetMs + 100, {
- apmPhase: PHASES[phaseIndex],
+ sampler.offer(operationalRow(agentId, "root_work", turnBaseMs + offsetMs + 100, {
+ deliveryPhase: PHASES[phaseIndex],
...spanFields,
}));
sampler.offer(operationalRow(agentId, "runtime_signal", turnBaseMs + offsetMs + 200, {
- apmPhase: PHASES[phaseIndex],
+ deliveryPhase: PHASES[phaseIndex],
...spanFields,
}));
sampler.offer(operationalRow(agentId, "tick", turnBaseMs + offsetMs + 300, {
turnActive: true,
- apmPhase: PHASES[phaseIndex],
+ deliveryPhase: PHASES[phaseIndex],
...spanFields,
}));
}
@@ -327,7 +327,7 @@ describe("B1 red gate — turn-span sacred rows", () => {
) {
sampler.offer(operationalRow(agentId, "tick", turnBaseMs + offsetMs + 300, {
turnActive: false,
- apmPhase: PHASES.at(-1),
+ deliveryPhase: PHASES.at(-1),
}));
}
}
@@ -354,7 +354,7 @@ describe("B1 red gate — turn-span sacred rows", () => {
expect(DEFAULT_TRACE_SAMPLE_MS).toBe(30_000);
expect(PHASES.length - 1).toBe(6);
expect(count("runtime_signal")).toBe(AGENTS * TURNS_PER_AGENT_HOUR * PHASES.length);
- expect(count("progress")).toBe(AGENTS * TURNS_PER_AGENT_HOUR);
+ expect(count("root_work")).toBe(AGENTS * TURNS_PER_AGENT_HOUR);
// Five retained ticks per turn mechanically includes state-change edges,
// throttle survivors, and the pending tail flushed by the next boundary.
expect(count("tick")).toBe(AGENTS * TURNS_PER_AGENT_HOUR * 5);
@@ -362,7 +362,7 @@ describe("B1 red gate — turn-span sacred rows", () => {
expect(count("turn_end", "turn_span")).toBe(AGENTS * CLEAN_TURNS_PER_AGENT_HOUR);
expect(count("turn_abort", "turn_span")).toBe(AGENTS * FAILED_TURNS_PER_AGENT_HOUR);
expect(survivors).toHaveLength(8_168);
- expect(serializedBytesPerHour).toBe(4_010_728);
+ expect(serializedBytesPerHour).toBe(4_052_048);
expect(productionPerFileCap).toBe(32 * 1024 * 1024);
if (typeof productionPerFileCap !== "number") return;
diff --git a/src/daemon/src/util/traceSampler.ts b/src/daemon/src/util/traceSampler.ts
index ea4369eb5..8026e185a 100644
--- a/src/daemon/src/util/traceSampler.ts
+++ b/src/daemon/src/util/traceSampler.ts
@@ -24,7 +24,7 @@
* `effects:['terminate_stalled']` tick; the following turn_end had
* already reset it to 0). Dropping it would shorten the reconstructed
* "stuck for how long". (Cecilia 架构#423 ④.)
- * - SAMPLEABLE (throttled): unchanged-state `tick`, plus `progress` /
+ * - SAMPLEABLE (throttled): unchanged-state `tick`, plus `root_work` /
* `runtime_signal` heartbeats. An unchanged-state tick is one with
* `effects==[]` AND status/turnActive/inbox/resetting/stopping unchanged
* from the previous emitted tick for that agent.
@@ -37,7 +37,7 @@
* next emitted tick-stream row), and the terminating frame (effects tick / a
* transition) is sacrosanct. `sinceProgressMs` is self-contained on each tick
* row, so duration reconstructs from the tick stream alone even when the
- * `progress` stream is fully folded.
+ * `root_work` stream is fully folded.
*/
/** Sampler-visible subset of the manager's explicitly allowlisted trace rows. */
@@ -52,7 +52,7 @@ interface TraceRec {
inbox?: unknown;
resetting?: unknown;
stoppingSince?: unknown;
- apmPhase?: unknown;
+ deliveryPhase?: unknown;
}
export interface TraceSampler {
@@ -61,7 +61,7 @@ export interface TraceSampler {
}
/** Streams that are throttled rather than always-emitted. */
-const SAMPLEABLE_EVENTS = new Set(["tick", "progress", "runtime_signal"]);
+const SAMPLEABLE_EVENTS = new Set(["tick", "root_work", "runtime_signal"]);
const SACRED_TURN_SPAN_EVENTS = new Set(["turn_begin", "turn_end", "turn_abort"]);
/** Default heartbeat throttle: at most one folded-stream row per agent per this. */
@@ -76,9 +76,9 @@ interface AgentSamplerState {
lastTickEmitAt: number;
/** The most recent throttled (folded) unchanged tick, held for tail-flush. */
pendingTick: TraceRec | null;
- /** Last emitted `progress` nowMs. */
+ /** Last emitted `root_work` nowMs. */
lastProgressEmitAt: number;
- /** Last emitted `runtime_signal` apmPhase (edge detection) + nowMs. */
+ /** Last emitted `runtime_signal` deliveryPhase (edge detection) + nowMs. */
lastSignalPhase: string | null;
lastSignalEmitAt: number;
}
@@ -202,7 +202,7 @@ export function createTraceSampler(
return;
}
- if (event === "progress") {
+ if (event === "root_work") {
// Redundant with the next tick's sinceProgressMs; keep a sparse sample
// for a coarse liveness pulse, fold the rest.
const now = nowOf(rec);
@@ -215,7 +215,7 @@ export function createTraceSampler(
// runtime_signal: keep phase-change EDGES, throttle same-phase runs.
if (event === "runtime_signal") {
- const phase = typeof rec.apmPhase === "string" ? rec.apmPhase : "";
+ const phase = typeof rec.deliveryPhase === "string" ? rec.deliveryPhase : "";
const now = nowOf(rec);
if (phase !== s.lastSignalPhase || now - s.lastSignalEmitAt >= throttleMs) {
s.lastSignalPhase = phase;
diff --git a/src/daemon/src/version.ts b/src/daemon/src/version.ts
index dfc1c1219..8aecc1f1c 100644
--- a/src/daemon/src/version.ts
+++ b/src/daemon/src/version.ts
@@ -3,8 +3,8 @@
*
* These are read from `@alook/daemon`'s own `package.json` across the source,
* library bundle, and nested CLI bundle layouts. Everything on the wire that
- * identifies the daemon to a remote runtime CLI (Kimi's `initialize.client`,
- * Codex's `initialize.clientInfo`)
+ * identifies the daemon to a remote runtime CLI (for example Codex's
+ * `initialize.clientInfo`)
* flows through `getDaemonClientInfo()` so nobody hand-types the pre-alook
* daemon-identity strings anymore.
*/
diff --git a/src/shared/src/community/bot-model.test.ts b/src/shared/src/community/bot-model.test.ts
index eca6bc98f..73ec455be 100644
--- a/src/shared/src/community/bot-model.test.ts
+++ b/src/shared/src/community/bot-model.test.ts
@@ -22,7 +22,7 @@ describe("resolveModelConfig", () => {
});
expect(resolveModelConfig("claude", "my-ft")).toEqual({ kind: "custom", name: "my-ft" });
// Empty catalog ⇒ always custom.
- expect(resolveModelConfig("gemini", "anything")).toEqual({ kind: "custom", name: "anything" });
+ expect(resolveModelConfig("cursor", "anything")).toEqual({ kind: "custom", name: "anything" });
// Null runtime ⇒ fallback empty catalog ⇒ custom.
expect(resolveModelConfig(null, "x")).toEqual({ kind: "custom", name: "x" });
});
diff --git a/src/shared/src/constants/runtime-models.test.ts b/src/shared/src/constants/runtime-models.test.ts
index 4e21a9694..6e1accbad 100644
--- a/src/shared/src/constants/runtime-models.test.ts
+++ b/src/shared/src/constants/runtime-models.test.ts
@@ -2,44 +2,28 @@ import { describe, it, expect } from "vitest";
import {
RUNTIME_MODEL_CATALOG,
getRuntimeModelCatalog,
- runtimeSupportsModel,
} from "./runtime-models";
const SEEDED_RUNTIMES = [
"claude",
"codex",
- "gemini",
- "kimi",
- "copilot",
"cursor",
"opencode",
"pi",
- "antigravity",
];
describe("getRuntimeModelCatalog", () => {
- it("returns the seeded entry for each of the 9 runtime ids", () => {
+ it("returns the seeded entry for each of the 5 supported runtime ids", () => {
for (const id of SEEDED_RUNTIMES) {
expect(getRuntimeModelCatalog(id)).toBe(RUNTIME_MODEL_CATALOG[id]);
}
expect(getRuntimeModelCatalog("claude").models).toContain("claude-opus-4-6");
expect(getRuntimeModelCatalog("codex").models).toContain("gpt-5.4");
- expect(getRuntimeModelCatalog("gemini").models).toEqual([]);
+ expect(getRuntimeModelCatalog("cursor").models).toEqual([]);
});
- it("falls back to {supportsModel:true, models:[]} for an unknown id and null", () => {
- expect(getRuntimeModelCatalog("does-not-exist")).toEqual({ supportsModel: true, models: [] });
- expect(getRuntimeModelCatalog(null)).toEqual({ supportsModel: true, models: [] });
- });
-});
-
-describe("runtimeSupportsModel", () => {
- it("is false only for antigravity", () => {
- expect(runtimeSupportsModel("antigravity")).toBe(false);
- for (const id of SEEDED_RUNTIMES.filter((r) => r !== "antigravity")) {
- expect(runtimeSupportsModel(id)).toBe(true);
- }
- expect(runtimeSupportsModel(null)).toBe(true);
- expect(runtimeSupportsModel("unknown-runtime")).toBe(true);
+ it("falls back to {models:[]} for an unknown id and null", () => {
+ expect(getRuntimeModelCatalog("does-not-exist")).toEqual({ models: [] });
+ expect(getRuntimeModelCatalog(null)).toEqual({ models: [] });
});
});
diff --git a/src/shared/src/constants/runtime-models.ts b/src/shared/src/constants/runtime-models.ts
index 4abefa37e..1ce367ace 100644
--- a/src/shared/src/constants/runtime-models.ts
+++ b/src/shared/src/constants/runtime-models.ts
@@ -16,51 +16,36 @@
*/
export interface RuntimeModelCatalogEntry {
- /** false ⇒ the driver ignores the model at launch; hide the field. */
- readonly supportsModel: boolean;
/** Known-good ids for the picker. Empty ⇒ Default + free text only. */
readonly models: readonly string[];
}
/**
* Seeded from what each driver does today. `claude`/`codex` mirror the ids
- * already in `RUNTIME_MODEL_OPTIONS`; the runtimes that accept a model but
- * have no curated list get `{ supportsModel: true, models: [] }` (Default +
- * free text); `antigravity` alone is `supportsModel: false` — its driver
- * discards the model at launch, so offering the field would be a lie.
+ * already in `RUNTIME_MODEL_OPTIONS`; runtimes with no curated list get
+ * `{ models: [] }` (Default + free text).
*/
export const RUNTIME_MODEL_CATALOG: Record<string, RuntimeModelCatalogEntry> = {
claude: {
- supportsModel: true,
models: ["claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"],
},
codex: {
- supportsModel: true,
models: ["gpt-5.4", "gpt-5.3-codex"],
},
- gemini: { supportsModel: true, models: [] },
- kimi: { supportsModel: true, models: [] },
- copilot: { supportsModel: true, models: [] },
- cursor: { supportsModel: true, models: [] },
- opencode: { supportsModel: true, models: [] },
- pi: { supportsModel: true, models: [] },
- antigravity: { supportsModel: false, models: [] },
+ cursor: { models: [] },
+ opencode: { models: [] },
+ pi: { models: [] },
};
/** Fallback for unknown/`null` runtime ids — a usable free-text field. */
-const FALLBACK_ENTRY: RuntimeModelCatalogEntry = { supportsModel: true, models: [] };
+const FALLBACK_ENTRY: RuntimeModelCatalogEntry = { models: [] };
/**
* Catalog entry for a runtime id. Unknown or `null` runtimes fall back to
- * `{ supportsModel: true, models: [] }` so a runtime added to the daemon
- * before the catalog still gets a usable free-text field.
+ * `{ models: [] }` so a runtime added to the daemon before the catalog still
+ * gets a usable free-text field.
*/
export function getRuntimeModelCatalog(runtime: string | null): RuntimeModelCatalogEntry {
if (runtime === null) return FALLBACK_ENTRY;
return RUNTIME_MODEL_CATALOG[runtime] ?? FALLBACK_ENTRY;
}
-
-/** Whether a runtime's driver honors a launch model. `null` ⇒ allow (unknown). */
-export function runtimeSupportsModel(runtime: string | null): boolean {
- return getRuntimeModelCatalog(runtime).supportsModel;
-}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 567571281..f5edd5f88 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -484,7 +484,6 @@ export type { RuntimeModelCatalogEntry } from "./constants/runtime-models";
export {
RUNTIME_MODEL_CATALOG,
getRuntimeModelCatalog,
- runtimeSupportsModel,
} from "./constants/runtime-models";
export {
diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.ts
index 160826f84..22473f9d2 100644
--- a/src/shared/src/runtime-config.ts
+++ b/src/shared/src/runtime-config.ts
@@ -45,7 +45,7 @@ export type ModeConfig = { kind: "default" | "fast" };
export interface RuntimeConfig {
version: number;
- /** "claude" | "codex" | "gemini" | "kimi" | "pi" | "copilot" | "cursor" | "opencode" | "antigravity" | "mock" */
+ /** "claude" | "codex" | "cursor" | "opencode" | "pi" | "mock" */
runtime: string;
model: ModelConfig;
mode: ModeConfig;
diff --git a/src/shared/test/schemas/community-runtime.test.ts b/src/shared/test/schemas/community-runtime.test.ts
index c5e932e75..cc0c2e7b9 100644
--- a/src/shared/test/schemas/community-runtime.test.ts
+++ b/src/shared/test/schemas/community-runtime.test.ts
@@ -69,7 +69,7 @@ describe("CommunityMachineRuntimeSchema", () => {
});
it("rejects an id with a disallowed character (colon)", () => {
- expect(() => CommunityMachineRuntimeSchema.parse({ id: "kimi:sdk" })).toThrow();
+ expect(() => CommunityMachineRuntimeSchema.parse({ id: "invalid:runtime" })).toThrow();
});
it("accepts the full charset — alnum + `._@/-`", () => {
diff --git a/src/web/src/app/api/community/bots/[id]/route.test.ts b/src/web/src/app/api/community/bots/[id]/route.test.ts
index 30800619d..5fe176d6f 100644
--- a/src/web/src/app/api/community/bots/[id]/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.test.ts
@@ -191,6 +191,31 @@ describe("PATCH /api/community/bots/[id]", () => {
expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()
})
+ it("switches a stored removed runtime to a supported runtime without rewriting the row first", async () => {
+ mockGetBotOwnedBy.mockResolvedValue({
+ id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",
+ runtime: "gemini", modelName: "legacy-model",
+ })
+ mockUpdateBot.mockResolvedValue({
+ id: "b1", name: "Old", discriminator: "0001", description: "old desc", image: null,
+ })
+
+ const res = await PATCH(patchReq({ runtime: "codex" }), ctx)
+
+ expect(res.status).toBe(200)
+ expect(mockPushAgentProviderSwitchToMachine).toHaveBeenCalledWith(
+ expect.anything(),
+ "mac1",
+ expect.objectContaining({
+ agentId: "b1",
+ from: "gemini",
+ to: "codex",
+ config: expect.objectContaining({ runtime: "codex", model: { kind: "default" } }),
+ }),
+ )
+ expect(mockUpdateBotRuntime).toHaveBeenCalledWith(expect.anything(), "b1", "u1", "codex", null)
+ })
+
it("changed model, daemon offline (isBotOnline false): 409, no column write, no push", async () => {
mockIsBotOnline.mockResolvedValue(false)
const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)
@@ -315,15 +340,8 @@ describe("PATCH /api/community/bots/[id]", () => {
expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalled()
})
- it("model on an antigravity bot → 400", async () => {
- mockGetBotOwnedBy.mockResolvedValue({ id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1", runtime: "antigravity", modelName: null })
- const res = await PATCH(patchReq({ model: "whatever" }), ctx)
- expect(res.status).toBe(400)
- expect(mockUpdateBotModel).not.toHaveBeenCalled()
- })
-
it("runtime not on machine → 400", async () => {
- const res = await PATCH(patchReq({ runtime: "gemini" }), ctx)
+ const res = await PATCH(patchReq({ runtime: "unknown-runtime" }), ctx)
expect(res.status).toBe(400)
expect(mockUpdateBotRuntime).not.toHaveBeenCalled()
expect(mockPushAgentProviderSwitchToMachine).not.toHaveBeenCalled()
diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.ts
index 878f8bb25..ba1ffbe8f 100644
--- a/src/web/src/app/api/community/bots/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.ts
@@ -7,7 +7,6 @@ import {
WS_EVENTS,
makeRuntimeConfig,
resolveModelConfig,
- runtimeSupportsModel,
formatHandle,
createLogger,
} from "@alook/shared"
@@ -67,9 +66,6 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
if (runtime.status === "unhealthy") {
return writeError(`runtime ${targetRuntime} is currently unavailable on this machine`, 400)
}
- if (nextModel !== null && nextModel !== undefined && !runtimeSupportsModel(targetRuntime)) {
- return writeError(`runtime ${targetRuntime} does not support a model selection`, 400)
- }
}
// Will we push bot:updated to the daemon? (Iff name/description changed —
// image-only is display-only and doesn't affect the system prompt.) If so,
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index 37ca75c21..b5f2752a9 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -88,7 +88,7 @@ describe("POST /api/community/bots — model", () => {
mockCountLiveBotsForOwner.mockResolvedValue(0)
mockGetMachineForOwner.mockResolvedValue({
id: "mac1",
- availableRuntimes: [{ id: "claude", status: "healthy" }, { id: "antigravity", status: "healthy" }],
+ availableRuntimes: [{ id: "claude", status: "healthy" }, { id: "codex", status: "healthy" }],
})
mockCreateBot.mockResolvedValue({ botId: "b1", name: "MyBot", discriminator: "0001", description: "", image: null })
mockGetUserPublic.mockResolvedValue({ id: "u1", name: "Owner", discriminator: "9999" })
@@ -141,8 +141,8 @@ describe("POST /api/community/bots — model", () => {
expect(mockPushBotEventToMachine).toHaveBeenCalledOnce()
})
- it("rejects a model on runtime antigravity with 400", async () => {
- const res = await POST(postReq(base("some-model", "antigravity")), ctx)
+ it("rejects a removed runtime that is absent from the machine report with 400", async () => {
+ const res = await POST(postReq(base(undefined, "gemini")), ctx)
expect(res.status).toBe(400)
expect(mockCreateBot).not.toHaveBeenCalled()
})
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index a6e04d61f..61716452f 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -3,7 +3,6 @@ import {
queries,
CommunityBotCreateRequestSchema,
COMMUNITY_BOT_LIMIT_PER_OWNER,
- runtimeSupportsModel,
utcDayKeyDaysAgo,
} from "@alook/shared"
import { getDb } from "@/lib/db"
@@ -69,12 +68,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
)
}
- // antigravity discards the model at launch; storing an inert value would make
- // the card lie. Reject a non-null model on a runtime that doesn't honor it.
const modelName = body.model ?? null
- if (modelName !== null && !runtimeSupportsModel(body.runtime)) {
- return writeError(`runtime ${body.runtime} does not support a model selection`, 400)
- }
const created = await queries.communityBot.createBot(db, {
ownerId: ctx.userId,
diff --git a/src/web/src/components/community/bots/bot-runtime-fields.test.ts b/src/web/src/components/community/bots/bot-runtime-fields.test.ts
index 5c831ac59..7b7c07f02 100644
--- a/src/web/src/components/community/bots/bot-runtime-fields.test.ts
+++ b/src/web/src/components/community/bots/bot-runtime-fields.test.ts
@@ -25,7 +25,7 @@ import { BotRuntimeFields } from "./bot-runtime-fields"
const OPTIONS = [
{ id: "claude", unhealthy: true },
{ id: "codex", unhealthy: false },
- { id: "gemini", unhealthy: true },
+ { id: "cursor", unhealthy: true },
]
function renderFields(overrides: Partial<React.ComponentProps<typeof BotRuntimeFields>> = {}) {
@@ -58,7 +58,7 @@ describe("BotRuntimeFields", () => {
const { renderer } = renderFields()
expect(radio(renderer, "claude").props.disabled).toBe(false)
expect(radio(renderer, "codex").props.disabled).toBe(false)
- expect(radio(renderer, "gemini").props.disabled).toBe(true)
+ expect(radio(renderer, "cursor").props.disabled).toBe(true)
})
it("changes runtime and clears the previous provider model together", () => {
diff --git a/src/web/src/components/community/bots/edit-bot-sheet.test.ts b/src/web/src/components/community/bots/edit-bot-sheet.test.ts
index f2f43d5b0..7d8302dd4 100644
--- a/src/web/src/components/community/bots/edit-bot-sheet.test.ts
+++ b/src/web/src/components/community/bots/edit-bot-sheet.test.ts
@@ -292,7 +292,7 @@ describe("EditBotSheet — current unhealthy runtime stays selectable (Alli #128
availableRuntimes: [
{ id: "claude", status: "unhealthy" },
{ id: "codex", status: "healthy" },
- { id: "gemini", status: "unhealthy" },
+ { id: "cursor", status: "unhealthy" },
],
},
],
@@ -302,11 +302,27 @@ describe("EditBotSheet — current unhealthy runtime stays selectable (Alli #128
it("selected current runtime is not disabled even when unhealthy; other unhealthy candidates are", () => {
const renderer = renderSheet({ ...BOT, runtime: "claude" })
const current = runtimeRadio(renderer, "claude")
- const otherUnhealthy = runtimeRadio(renderer, "gemini")
+ const otherUnhealthy = runtimeRadio(renderer, "cursor")
const healthy = runtimeRadio(renderer, "codex")
expect(current.props.checked).toBe(true)
expect(current.props.disabled).toBe(false)
expect(otherUnhealthy.props.disabled).toBe(true)
expect(healthy.props.disabled).toBe(false)
})
+
+ it("shows a stored removed runtime as unavailable and allows switching without changing bot data first", () => {
+ useMachinesMock.mockReturnValue(HEALTHY_MACHINES)
+ const renderer = renderSheet({ ...BOT, runtime: "gemini", modelName: "legacy-model" })
+ const removed = runtimeRadio(renderer, "gemini")
+ const healthy = runtimeRadio(renderer, "codex")
+
+ expect(removed.props.checked).toBe(true)
+ expect(removed.props.disabled).toBe(false)
+ expect(renderer.root.findAll((n) => n.type === "span" && n.props.children === "unavailable")).toHaveLength(1)
+ expect(healthy.props.disabled).toBe(false)
+
+ act(() => healthy.props.onChange())
+ expect(runtimeRadio(renderer, "codex").props.checked).toBe(true)
+ expect(updateMutateAsync).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/components/community/bots/model-field.test.ts b/src/web/src/components/community/bots/model-field.test.ts
index 40c4f422a..a048c4e25 100644
--- a/src/web/src/components/community/bots/model-field.test.ts
+++ b/src/web/src/components/community/bots/model-field.test.ts
@@ -67,16 +67,11 @@ describe("ModelField", () => {
expect(values).toContain("__custom__")
})
- it("renders only Default + Custom… for gemini (empty catalog)", () => {
- const values = itemValues(render({ runtime: "gemini", value: null }))
+ it("renders only Default + Custom… for cursor (empty catalog)", () => {
+ const values = itemValues(render({ runtime: "cursor", value: null }))
expect(values).toEqual(["__default__", "__custom__"])
})
- it("renders nothing for antigravity", () => {
- const renderer = render({ runtime: "antigravity", value: null })
- expect(renderer.root.findAll((n) => n.props?.["data-mock"] === "select")).toHaveLength(0)
- })
-
it("selecting a catalog entry emits that id; selecting Default emits null", () => {
const onChange = vi.fn()
selectCalls.length = 0
diff --git a/src/web/src/components/community/bots/model-field.tsx b/src/web/src/components/community/bots/model-field.tsx
index a683ad35c..1e22214d0 100644
--- a/src/web/src/components/community/bots/model-field.tsx
+++ b/src/web/src/components/community/bots/model-field.tsx
@@ -3,7 +3,6 @@
import { useEffect, useMemo, useState } from "react"
import {
getRuntimeModelCatalog,
- runtimeSupportsModel,
modelSelectState,
modelNameFromSelect,
MODEL_SELECT_DEFAULT,
@@ -25,9 +24,6 @@ import {
* conditionally-rendered custom text input. All model-name ↔ Select translation
* goes through the shared `bot-model` helpers — never ad-hoc string logic.
*
- * Renders nothing when the runtime doesn't honor a launch model (antigravity):
- * offering the choice would be a lie.
- *
* The picker keeps its OWN Select/custom-text state rather than deriving purely
* from `value`, because "Custom… selected with an empty name" and "Default" both
* map to a `null` stored value — only local state can tell them apart, so the
@@ -64,8 +60,6 @@ export function ModelField({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [runtime, value])
- if (!runtimeSupportsModel(runtime)) return null
-
const isCustom = selectValue === MODEL_SELECT_CUSTOM
const defaultLabel = runtime ? `Default (${runtime}'s own default)` : "Default"
diff --git a/src/web/src/components/community/machines/machine-runtimes.test.ts b/src/web/src/components/community/machines/machine-runtimes.test.ts
index f85465118..453335f03 100644
--- a/src/web/src/components/community/machines/machine-runtimes.test.ts
+++ b/src/web/src/components/community/machines/machine-runtimes.test.ts
@@ -110,11 +110,11 @@ describe("MachineRuntimes", () => {
{ id: "codex", status: "unhealthy" as const },
{ id: "claude" },
{ id: "pi", status: "unhealthy" as const },
- { id: "gemini" },
+ { id: "cursor" },
],
})
const chips = collectChips(tree)
- expect(chips.map((c) => c.key)).toEqual([".$claude", ".$gemini", ".$codex", ".$pi"])
+ expect(chips.map((c) => c.key)).toEqual([".$claude", ".$cursor", ".$codex", ".$pi"])
})
it("unhealthy without lastError falls back to a generic 'Unavailable — check daemon logs' tooltip", () => {
diff --git a/src/web/src/lib/runtime-display.test.ts b/src/web/src/lib/runtime-display.test.ts
index 1db3b5932..543f826ca 100644
--- a/src/web/src/lib/runtime-display.test.ts
+++ b/src/web/src/lib/runtime-display.test.ts
@@ -15,7 +15,7 @@ describe("runtimeDisplayName", () => {
});
it("falls back to the generic label for unknown slugs", () => {
- expect(runtimeDisplayName("gemini")).toBe(GENERIC_RUNTIME_NAME);
+ expect(runtimeDisplayName("unknown-runtime")).toBe(GENERIC_RUNTIME_NAME);
expect(runtimeDisplayName("CLAUDE")).toBe(GENERIC_RUNTIME_NAME); // case-sensitive by design
});
diff --git a/src/ws-do/src/ws-durable/machine-control.test.ts b/src/ws-do/src/ws-durable/machine-control.test.ts
index 44e32e8e8..ba956919a 100644
--- a/src/ws-do/src/ws-durable/machine-control.test.ts
+++ b/src/ws-do/src/ws-durable/machine-control.test.ts
@@ -70,7 +70,7 @@ describe("WebSocketDurableObject", () => {
})
store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
store.set("community-machine-runtime-error", {
- requested: "gemini",
+ requested: "unknown-runtime",
available: [],
at: "2026-07-06T00:00:00.000Z",
})
diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.ts
index a1c717c79..642d8a616 100644
--- a/src/ws-do/src/ws-durable/machine-frames.test.ts
+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts
@@ -89,7 +89,7 @@ describe("WebSocketDurableObject", () => {
type: "session.error",
code: "runtime_not_available",
agentId: "a1",
- payload: { requested: "gemini", available: ["codex"] },
+ payload: { requested: "unknown-runtime", available: ["codex"] },
})
await durable.webSocketMessage(ws as any, frame)
@@ -97,7 +97,7 @@ describe("WebSocketDurableObject", () => {
| { requested: string; available: string[]; at: string }
| undefined
expect(overlay).toBeDefined()
- expect(overlay?.requested).toBe("gemini")
+ expect(overlay?.requested).toBe("unknown-runtime")
expect(overlay?.available).toEqual(["codex"])
// Fan-out went to the user DO with the overlay attached.
@@ -111,7 +111,7 @@ describe("WebSocketDurableObject", () => {
}
expect(body.type).toBe("community:machine.updated")
expect(body.machine.lastRuntimeError).toMatchObject({
- requested: "gemini",
+ requested: "unknown-runtime",
available: ["codex"],
})
})
diff --git a/vitest.config.ts b/vitest.config.ts
index f1f38f1da..caa2f5ad7 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -2,7 +2,7 @@ import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
- projects: ["src/shared", "src/web", "src/cli", "src/daemon", "src/email-worker", "src/ws-do", "src/app", "tests/utils", "scripts/ci"],
+ projects: ["src/shared", "src/web", "src/cli", "src/daemon", "src/daemon/agent-driver", "src/email-worker", "src/ws-do", "src/app", "tests/utils", "scripts/ci"],
coverage: {
provider: "v8",
include: ["src/**/*.{ts,tsx,js,jsx}", "scripts/ci/**/*.mjs"],