Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

chore: remove legacy CLI package and CI targets (#788)

Gustavo Ye8cfbd5333c74
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index 8ef4df8e2..aa0473c0e 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -17,7 +17,7 @@ A clear description of what the bug is.
What you expected to happen.
## Environment
-- **Package**: [e.g., @alook/web, @alook/cli]
+- **Package**: [e.g., @alook/web, @alook/app]
- **OS**: [e.g., macOS, Ubuntu]
- **Node Version**: [e.g., 20.x]
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
index 6011c22b1..c464d4d7b 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -12,7 +12,7 @@ A clear description of what you want to happen.
## Impact Area
- [ ] Shared library (`@alook/shared`)
- [ ] Web app (`@alook/web`)
-- [ ] CLI (`@alook/cli`)
+- [ ] App (`@alook/app`)
- [ ] Email Worker (`@alook/email-worker`)
- [ ] WebSocket DO (`@alook/ws-do`)
- [ ] Other: ...
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 4b6fc0fce..9198afb65 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -12,7 +12,7 @@
## Impact Areas
- [ ] Shared library (`@alook/shared`)
- [ ] Web app (`@alook/web`)
-- [ ] CLI (`@alook/cli`)
+- [ ] App (`@alook/app`)
- [ ] Email Worker (`@alook/email-worker`)
- [ ] WebSocket DO (`@alook/ws-do`)
- [ ] CI/CD
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b6cf7d8c5..426c5fefb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -475,13 +475,13 @@ jobs:
VITEST_MAX_WORKERS: 1
run: pnpm --filter @alook/daemon test
- name: Run selected Windows workspace tests
- if: contains(fromJSON(needs.scope.outputs.windows_suites), 'app') || contains(fromJSON(needs.scope.outputs.windows_suites), 'cli') || contains(fromJSON(needs.scope.outputs.windows_suites), 'shared')
+ if: contains(fromJSON(needs.scope.outputs.windows_suites), 'app') || contains(fromJSON(needs.scope.outputs.windows_suites), 'shared')
shell: bash
env:
WINDOWS_SUITES: ${{ needs.scope.outputs.windows_suites }}
run: |
filters=()
- for suite in app cli shared; do
+ for suite in app shared; do
if node -e 'process.exit(JSON.parse(process.env.WINDOWS_SUITES).includes(process.argv[1]) ? 0 : 1)' "$suite"; then
filters+=("--filter=@alook/$suite")
fi
@@ -594,8 +594,6 @@ jobs:
wait_for http://localhost:3000/api/health
- if: contains(fromJSON(needs.scope.outputs.integration_suites), 'web')
run: pnpm test:e2e
- - if: contains(fromJSON(needs.scope.outputs.integration_suites), 'cli')
- run: pnpm --filter @alook/cli run test:integration
- if: contains(fromJSON(needs.scope.outputs.integration_suites), 'daemon')
run: pnpm --filter @alook/daemon run test:integration
diff --git a/.github/workflows/publish-cli.yml b/.github/workflows/publish-cli.yml
deleted file mode 100644
index 78c07678c..000000000
--- a/.github/workflows/publish-cli.yml
+++ /dev/null
@@ -1,70 +0,0 @@
-name: Publish CLI
-
-on:
- push:
- branches: [main]
- paths: [src/cli/package.json]
-
-concurrency:
- group: publish-cli
- cancel-in-progress: false
-
-jobs:
- publish:
- name: Publish @alook/cli to npm
- runs-on: ubuntu-latest
- timeout-minutes: 10
- permissions:
- contents: read
- id-token: write
- steps:
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
-
- - name: Detect version
- id: version
- run: |
- VERSION=$(node -p "require('./src/cli/package.json').version")
- echo "version=$VERSION" >> "$GITHUB_OUTPUT"
-
- - name: Check if version already published
- id: check
- run: |
- if npm view "@alook/cli@${{ steps.version.outputs.version }}" version >/dev/null 2>&1; then
- echo "skip=true" >> "$GITHUB_OUTPUT"
- echo "::notice::@alook/cli@${{ steps.version.outputs.version }} already on npm — skipping"
- else
- echo "skip=false" >> "$GITHUB_OUTPUT"
- fi
-
- - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6
- if: steps.check.outputs.skip == 'false'
-
- - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
- if: steps.check.outputs.skip == 'false'
- with:
- bun-version: 1.3.11
-
- - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
- if: steps.check.outputs.skip == 'false'
- with:
- node-version: 22
- registry-url: https://registry.npmjs.org
- cache: pnpm
-
- - name: Upgrade npm for Trusted Publishers
- if: steps.check.outputs.skip == 'false'
- run: |
- npm install -g --prefix="$RUNNER_TEMP/npm-new" npm@latest
- echo "$RUNNER_TEMP/npm-new/bin" >> "$GITHUB_PATH"
-
- - run: pnpm install --frozen-lockfile
- if: steps.check.outputs.skip == 'false'
-
- - name: Build CLI bundle
- if: steps.check.outputs.skip == 'false'
- run: pnpm -C src/cli run build
-
- - name: Publish to npm (OIDC)
- if: steps.check.outputs.skip == 'false'
- working-directory: src/cli
- run: npm publish --access public
diff --git a/.gitignore b/.gitignore
index 988682006..cdebc1a47 100644
--- a/.gitignore
+++ b/.gitignore
@@ -29,6 +29,5 @@ src/videos/**/out/
.impeccable.md
.playwright-mcp/
.lighthouseci/
-src/cli/LICENSE
src/daemon/LICENSE
.superpowers/
diff --git a/AGENTS.md b/AGENTS.md
index e1540e9c1..323c195ce 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,7 +5,8 @@ Alook's main purpose is to make the cli agent always on, and give it a email add
- `plans/`: place your dev plans (gitignored, local only)
- `src/shared`: shared types, schema, queries, validators
- `src/web`: main Next.js app on Cloudflare Workers (D1 + R2); the independently built Blog app lives at `src/web/blog`
-- `src/cli`: CLI + daemon
+- `src/app`: local app CLI
+- `src/daemon`: agent runtime and daemon CLI
- `src/email-worker`: inbound email Cloudflare Worker
- `src/ws-do`: WebSocket Durable Object worker
@@ -38,7 +39,6 @@ git push origin main
This triggers:
- **CI** — typecheck, lint, tests, coverage (uploaded to Codecov)
- **Auto-Tag & Release** — CI detects the `release: vX.Y.Z` commit message, creates the git tag, and creates a GitHub Release with generated changelog (`auto-tag-release.yml`)
-- **@alook/cli** → auto-published to npm via `publish-cli.yml` (watches `src/cli/package.json`)
- **@alook/app** → auto-published to npm via `publish-app.yml` (watches `src/app/package.json`)
- **@alook/daemon** → auto-published to npm via `publish-daemon.yml` (watches `src/daemon/package.json`)
- **CF Workers** → each module redeploys when its own `package.json` changes
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3afb59b45..0ae6a3bf0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -31,7 +31,6 @@ Alook is a monorepo with nine packages:
| Package | Location | What it does |
|---------|----------|-------------|
| `@alook/web` | `src/web` | Next.js dashboard, REST API, auth, database |
-| `@alook/cli` | `src/cli` | Runtime daemon, task execution, agent orchestration |
| `@alook/shared` | `src/shared` | Types, constants, DB schema, validation |
| `@alook/email-worker` | `src/email-worker` | Inbound email parsing and storage |
| `@alook/ws-do` | `src/ws-do` | Real-time WebSocket channels |
diff --git a/codecov.yml b/codecov.yml
index 5169b1abc..c4654f562 100644
--- a/codecov.yml
+++ b/codecov.yml
@@ -5,10 +5,6 @@ coverage:
target: 50%
paths:
- src/shared/**
- cli:
- target: 60%
- paths:
- - src/cli/**
email-worker:
target: 70%
paths:
diff --git a/package.json b/package.json
index 25dad44aa..a08c7f428 100644
--- a/package.json
+++ b/package.json
@@ -14,7 +14,6 @@
"lint": "turbo run lint",
"knip": "turbo run knip",
"dev:web": "pnpm --filter @alook/web dev",
- "dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 ALOOK_PROJECT_ROOT=$PWD/.alook ALOOK_HEALTH_PORT=19515 pnpm --filter @alook/cli dev",
"daemon": "pnpm --filter @alook/daemon exec tsx src/cli/index.ts daemon",
"dev:desktop": "pnpm --filter @alook/desktop dev",
"build:desktop": "pnpm --filter @alook/desktop build",
@@ -25,7 +24,6 @@
"dev:meeting": "node scripts/dev-meeting.mjs",
"dev:send": "node -e \"const c=require('crypto');const a=process.argv.slice(1);const[f,t,s='Test',b='Hello from dev']=a;if(!f||!t){console.error('Usage: pnpm dev:send <from> <to> [subject] [body]');process.exit(1)}const raw=['From: '+f,'To: '+t,'Subject: '+s,'Message-ID: <'+c.randomUUID()+'@dev.local>','Date: '+new Date().toUTCString(),'MIME-Version: 1.0','Content-Type: text/plain; charset=utf-8','',b].join('\\r\\n');fetch('http://localhost:8787/cdn-cgi/handler/email?from='+encodeURIComponent(f)+'&to='+encodeURIComponent(t),{method:'POST',headers:{'Content-Type':'application/json'},body:raw}).then(r=>{if(r.ok)console.log('Email delivered to worker');else return r.text().then(t=>{throw new Error(t)})}).catch(e=>console.error('Email worker not running?',e.message))\"",
"test:shared": "pnpm --filter @alook/shared test",
- "test:cli": "pnpm --filter @alook/cli test",
"test:daemon": "pnpm --filter @alook/daemon test",
"test:web": "pnpm --filter @alook/web test",
"test:e2e": "pnpm --filter @alook/web test:e2e",
@@ -50,6 +48,7 @@
},
"devDependencies": {
"@vitest/coverage-istanbul": "4.1.11",
+ "sharp": "^0.35.4",
"simple-git-hooks": "^2.14.0",
"turbo": "^2.10.12",
"typescript": "^6.0.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 05bec799e..a471aa339 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -20,6 +20,9 @@ importers:
'@vitest/coverage-istanbul':
specifier: 4.1.11
version: 4.1.11([email protected])
+ sharp:
+ specifier: ^0.35.4
+ version: 0.35.4(@types/[email protected])
simple-git-hooks:
specifier: ^2.14.0
version: 2.14.0
@@ -73,46 +76,6 @@ importers:
specifier: 4.1.11
- src/cli:
- dependencies:
- citty:
- specifier: ^0.2.2
- version: 0.2.2
- commander:
- specifier: ^14.0.3
- version: 14.0.3
- playwright-core:
- specifier: ^1.62.1
- version: 1.62.1
- postal-mime:
- specifier: ^2.7.6
- version: 2.7.6
- sharp:
- specifier: ^0.35.4
- version: 0.35.4(@types/[email protected])
- devDependencies:
- '@alook/shared':
- specifier: workspace:*
- version: link:../shared
- '@types/bun':
- specifier: ^1.4.0
- version: 1.4.0
- eslint:
- specifier: ^9.39.5
- version: 9.39.5([email protected])
- knip:
- specifier: ^6.32.2
- version: 6.32.2
- typescript:
- specifier: ^6.0.3
- version: 6.0.3
- typescript-eslint:
- specifier: ^8.69.0
- vitest:
- specifier: 4.1.11
-
src/daemon:
dependencies:
commander:
@@ -5132,9 +5095,6 @@ packages:
resolution: {integrity: sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==}
-
resolution: {integrity: sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==}
@@ -14156,8 +14116,6 @@ snapshots:
-
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 6afe4780c..db47e95d2 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,6 +1,5 @@
packages:
- "src/shared"
- - "src/cli"
- "src/daemon"
- "src/daemon/agent-driver"
- "src/web"
diff --git a/scripts/bump-version.mjs b/scripts/bump-version.mjs
index 0dcf2800d..17f01f29f 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/daemon/agent-driver", "src/web", "src/email-worker", "src/ws-do", "src/queue-worker", "src/desktop"];
+const WORKSPACE_DIRS = ["src/shared", "src/app", "src/daemon", "src/daemon/agent-driver", "src/web", "src/email-worker", "src/ws-do", "src/queue-worker", "src/desktop"];
const DEPLOY_TRIGGER_DIRS = ["src/web", "src/email-worker", "src/ws-do", "src/queue-worker"];
function readPkg(dir) {
diff --git a/scripts/ci/change-scope-manifest.json b/scripts/ci/change-scope-manifest.json
index 0776992e0..b24a0548e 100644
--- a/scripts/ci/change-scope-manifest.json
+++ b/scripts/ci/change-scope-manifest.json
@@ -32,22 +32,6 @@
"lighthouse": false,
"app_artifact": true
},
- {
- "name": "@alook/cli",
- "root": "src/cli",
- "static": true,
- "build": true,
- "knip": true,
- "unit_root": "src/cli",
- "coverage_roots": ["src/cli/**/*.{ts,tsx,js,jsx}"],
- "codecov_target": "cli",
- "windows_suites": ["cli"],
- "integration_suites": ["cli"],
- "linux_suites": [],
- "ui": false,
- "lighthouse": false,
- "app_artifact": false
- },
{
"name": "@alook/daemon",
"root": "src/daemon",
@@ -178,12 +162,11 @@
}
],
"suites": {
- "windows": ["agent-driver", "app", "cli", "daemon", "shared"],
- "integration": ["cli", "daemon", "web"],
+ "windows": ["agent-driver", "app", "daemon", "shared"],
+ "integration": ["daemon", "web"],
"linux": ["agent-driver-packed", "daemon-packed", "daemon-real"]
},
"path_suites": [
- { "root": "tests/integration/cli", "integration_suites": ["cli"] },
{ "root": "tests/integration/daemon", "integration_suites": ["daemon"] }
],
"ui": {
@@ -195,7 +178,6 @@
},
"codecov_targets": {
"shared": { "path": "src/shared", "target": 50 },
- "cli": { "path": "src/cli", "target": 60 },
"email-worker": { "path": "src/email-worker", "target": 70 },
"ws-do": { "path": "src/ws-do", "target": 70 },
"web": { "path": "src/web", "target": 30 }
@@ -217,7 +199,6 @@
"scripts/ci/verify-coverage-plan.mjs",
"scripts/ci/validate-execution-plan.mjs",
"src/app/package.json",
- "src/cli/package.json",
"src/daemon/agent-driver/package.json",
"src/daemon/package.json",
"src/desktop/package.json",
diff --git a/scripts/ci/changed-scopes.mjs b/scripts/ci/changed-scopes.mjs
index 1f06a892e..81b9ec2bf 100644
--- a/scripts/ci/changed-scopes.mjs
+++ b/scripts/ci/changed-scopes.mjs
@@ -39,7 +39,6 @@ const COVERAGE_EXCLUDES = [
/(?:^|\/)test-harness\.ts$/,
/(?:^|\/)react-dom-(?:harness|setup)\.ts$/,
/\.d\.ts$/,
- /^src\/cli\/src\/index\.ts$/,
/^src\/shared\/src\/index\.ts$/,
/^src\/web\/scripts\//,
/^src\/web\/readme-capture\//,
diff --git a/scripts/ci/changed-scopes.test.ts b/scripts/ci/changed-scopes.test.ts
index 59de3cfd3..520fbe5bd 100644
--- a/scripts/ci/changed-scopes.test.ts
+++ b/scripts/ci/changed-scopes.test.ts
@@ -90,11 +90,11 @@ function gitDiffFixture() {
runGit("add", "README.md")
commit("baseline")
- const changedPath = "src/cli/src/commands/inbox.ts"
- mkdirSync(join(root, "src/cli/src/commands"), { recursive: true })
+ const changedPath = "src/app/src/commands/inbox.ts"
+ mkdirSync(join(root, "src/app/src/commands"), { recursive: true })
writeFileSync(join(root, changedPath), "export const fixture = true\n")
runGit("add", changedPath)
- commit("change cli")
+ commit("change app")
return { changedPath, root }
}
@@ -150,42 +150,38 @@ describe("canonical execution plan", () => {
expect(result.jobs.app_packed_artifact).toBe(false)
})
- it("selects only the CLI package and its explicit platform suites", () => {
- const result = plan(["src/cli/src/commands/inbox.ts"])
-
+ it("selects the active app package without retired CLI suites", () => {
+ const result = plan(["src/app/src/commands/inbox.ts"])
expect(result.change_class).toBe("package")
- expect(result.packages.affected).toEqual(["@alook/cli"])
- expect(result.suites.static).toEqual(["@alook/cli"])
- expect(result.suites.unit).toEqual(["src/cli"])
- expect(result.suites.integration).toEqual(["cli"])
- expect(result.suites.windows).toEqual(["cli"])
+ expect(result.packages.affected).toEqual(["@alook/app"])
+ expect(result.suites.static).toEqual(["@alook/app"])
+ expect(result.suites.unit).toEqual(["src/app"])
+ expect(result.suites.integration).toEqual([])
+ expect(result.suites.windows).toEqual(["app"])
expect(result.ui.specs).toEqual([])
- expect(result.coverage.targets).toEqual(["cli"])
- expect(result.jobs.app_packed_artifact).toBe(false)
+ expect(result.coverage.targets).toEqual([])
+ expect(result.jobs.app_packed_artifact).toBe(true)
})
it("routes integration-owned paths without widening to unrelated suites", () => {
- const cli = plan(["tests/integration/cli/session-resume.test.ts"])
- expect(cli.suites.integration).toEqual(["cli"])
- expect(cli.jobs.e2e).toBe(true)
- expect(cli.jobs.static_checks).toBe(false)
-
- const daemon = plan(["tests/integration/daemon/lifecycle.test.ts"])
- expect(daemon.suites.integration).toEqual(["daemon"])
+ const integration = plan(["tests/integration/daemon/lifecycle.test.ts"])
+ expect(integration.suites.integration).toEqual(["daemon"])
+ expect(integration.jobs.e2e).toBe(true)
+ expect(integration.jobs.static_checks).toBe(false)
const undeclared = plan(["tests/integration/future/case.test.ts"])
expect(undeclared.full).toBe(true)
expect(undeclared.full_reason).toBe("unknown_path")
- expect(undeclared.suites.integration).toEqual(["cli", "daemon", "web"])
+ expect(undeclared.suites.integration).toEqual(["daemon", "web"])
const trailingSlashManifest = structuredClone(loadScopeManifest())
- const cliPathSuite = trailingSlashManifest.path_suites.find((entry) => (
- entry.root === "tests/integration/cli"
+ const daemonPathSuite = trailingSlashManifest.path_suites.find((entry) => (
+ entry.root === "tests/integration/daemon"
))
- expect(cliPathSuite).toBeDefined()
- cliPathSuite!.root += "/"
+ expect(daemonPathSuite).toBeDefined()
+ daemonPathSuite!.root += "/"
const canonicalized = buildExecutionPlan(
- modified("tests/integration/cli/session-resume.test.ts"),
+ modified("tests/integration/daemon/lifecycle.test.ts"),
{
baseSha: sha("a"),
headSha: sha("b"),
@@ -193,7 +189,7 @@ describe("canonical execution plan", () => {
},
)
expect(canonicalized.full).toBe(false)
- expect(canonicalized.suites.integration).toEqual(["cli"])
+ expect(canonicalized.suites.integration).toEqual(["daemon"])
})
it("expands shared changes through the complete workspace dependent closure", () => {
@@ -202,7 +198,6 @@ describe("canonical execution plan", () => {
expect(result.change_class).toBe("shared")
expect(result.packages.affected).toEqual([
"@alook/app",
- "@alook/cli",
"@alook/daemon",
"@alook/email-worker",
"@alook/queue-worker",
@@ -211,8 +206,8 @@ describe("canonical execution plan", () => {
"@alook/web",
"@alook/ws-do",
])
- expect(result.suites.integration).toEqual(["cli", "daemon", "web"])
- expect(result.suites.windows).toEqual(["app", "cli", "daemon", "shared"])
+ expect(result.suites.integration).toEqual(["daemon", "web"])
+ expect(result.suites.windows).toEqual(["app", "daemon", "shared"])
expect(result.ui.specs).toEqual(["all"])
expect(result.jobs.app_packed_artifact).toBe(true)
expect(result.jobs.rust).toBe(false)
@@ -231,8 +226,8 @@ describe("canonical execution plan", () => {
const result = plan(paths)
expect(result.full, paths.join(",") || "empty").toBe(true)
expect(result.ui.specs).toEqual(["all"])
- expect(result.suites.integration).toEqual(["cli", "daemon", "web"])
- expect(result.suites.windows).toEqual(["agent-driver", "app", "cli", "daemon", "shared"])
+ expect(result.suites.integration).toEqual(["daemon", "web"])
+ expect(result.suites.windows).toEqual(["agent-driver", "app", "daemon", "shared"])
}
expect(plan(["README.md"], { forceFull: true }).full).toBe(true)
@@ -253,23 +248,22 @@ describe("canonical execution plan", () => {
expect(plan(["src/app/README.md"]).jobs.app_packed_artifact).toBe(true)
expect(plan(["src/daemon/README.md"]).jobs.app_packed_artifact).toBe(true)
expect(plan(["src/shared/README.md"]).jobs.app_packed_artifact).toBe(true)
- expect(plan(["src/cli/README.md"]).jobs.app_packed_artifact).toBe(false)
})
it("takes a monotonic union for multiple paths", () => {
- const cli = plan(["src/cli/src/index.ts"])
+ const app = plan(["src/app/src/index.ts"])
const web = plan(["src/web/src/app/page.tsx"])
- const combined = plan(["src/web/src/app/page.tsx", "src/cli/src/index.ts"])
+ const combined = plan(["src/web/src/app/page.tsx", "src/app/src/index.ts"])
- for (const value of cli.packages.affected) expect(combined.packages.affected).toContain(value)
+ for (const value of app.packages.affected) expect(combined.packages.affected).toContain(value)
for (const value of web.packages.affected) expect(combined.packages.affected).toContain(value)
- for (const value of cli.suites.integration) expect(combined.suites.integration).toContain(value)
+ for (const value of app.suites.integration) expect(combined.suites.integration).toContain(value)
for (const value of web.suites.integration) expect(combined.suites.integration).toContain(value)
})
it("produces byte-identical plans, hashes, and mechanical projections", () => {
- const first = plan(["src/cli/src/index.ts", "src/web/src/app/page.tsx"])
- const second = plan(["src/web/src/app/page.tsx", "src/cli/src/index.ts"])
+ const first = plan(["src/app/src/index.ts", "src/web/src/app/page.tsx"])
+ const second = plan(["src/web/src/app/page.tsx", "src/app/src/index.ts"])
expect(first).toEqual(second)
expect(stablePlanJson(first)).toBe(stablePlanJson(second))
@@ -331,25 +325,25 @@ describe("coverage name-status contract", () => {
it("requires surviving A/M and rename/copy new sides but not deleted or old paths", () => {
const result = buildExecutionPlan([
- { status: "A", path: "src/cli/src/added.ts" },
- { status: "M", path: "src/cli/src/modified.ts" },
- { status: "D", path: "src/cli/src/deleted.ts" },
- { status: "R100", old_path: "src/cli/src/old.ts", path: "src/cli/src/renamed.ts" },
- { status: "C090", old_path: "src/cli/src/source.ts", path: "src/cli/src/copied.ts" },
+ { status: "A", path: "src/app/src/added.ts" },
+ { status: "M", path: "src/app/src/modified.ts" },
+ { status: "D", path: "src/app/src/deleted.ts" },
+ { status: "R100", old_path: "src/app/src/old.ts", path: "src/app/src/renamed.ts" },
+ { status: "C090", old_path: "src/app/src/source.ts", path: "src/app/src/copied.ts" },
], { baseSha: sha("a"), headSha: sha("b") })
expect(result.coverage.required_changed_files).toEqual([
- "src/cli/src/added.ts",
- "src/cli/src/copied.ts",
- "src/cli/src/modified.ts",
- "src/cli/src/renamed.ts",
+ "src/app/src/added.ts",
+ "src/app/src/copied.ts",
+ "src/app/src/modified.ts",
+ "src/app/src/renamed.ts",
])
})
it("requires only files selected by the actual coverage globs", () => {
for (const path of [
"src/app/scripts/app-packed-artifact.mjs",
- "src/cli/scripts/prepare-dist.mjs",
+ "src/app/scripts/bundle-daemon.mjs",
"src/shared/src/index.ts",
"src/web/auth/vitest.config.ts",
"src/web/vitest.config.ts",
@@ -379,13 +373,13 @@ describe("coverage name-status contract", () => {
it("parses NUL-delimited statuses without losing rename/copy identity", () => {
const input = Buffer.from(
- "M\0src/cli/src/a.ts\0D\0src/cli/src/deleted.ts\0R100\0src/cli/src/old.ts\0src/cli/src/new.ts\0C090\0src/shared/src/a.ts\0src/shared/src/b.ts\0",
+ "M\0src/app/src/a.ts\0D\0src/app/src/deleted.ts\0R100\0src/app/src/old.ts\0src/app/src/new.ts\0C090\0src/shared/src/a.ts\0src/shared/src/b.ts\0",
)
expect(parseNameStatus(input)).toEqual([
- { status: "M", path: "src/cli/src/a.ts" },
- { status: "D", path: "src/cli/src/deleted.ts" },
- { status: "R100", old_path: "src/cli/src/old.ts", path: "src/cli/src/new.ts" },
+ { status: "M", path: "src/app/src/a.ts" },
+ { status: "D", path: "src/app/src/deleted.ts" },
+ { status: "R100", old_path: "src/app/src/old.ts", path: "src/app/src/new.ts" },
{ status: "C090", old_path: "src/shared/src/a.ts", path: "src/shared/src/b.ts" },
])
})
@@ -397,20 +391,20 @@ describe("coverage name-status contract", () => {
it("sorts equal destination paths by old path and then status", () => {
const input = Buffer.from([
- "R100", "src/cli/src/z.ts", "src/cli/src/same.ts",
- "R090", "src/cli/src/a.ts", "src/cli/src/same.ts",
- "C100", "src/cli/src/a.ts", "src/cli/src/same.ts",
- "M", "src/cli/src/same.ts",
- "A", "src/cli/src/same.ts",
+ "R100", "src/app/src/z.ts", "src/app/src/same.ts",
+ "R090", "src/app/src/a.ts", "src/app/src/same.ts",
+ "C100", "src/app/src/a.ts", "src/app/src/same.ts",
+ "M", "src/app/src/same.ts",
+ "A", "src/app/src/same.ts",
"",
].join("\0"))
expect(parseNameStatus(input)).toEqual([
- { status: "A", path: "src/cli/src/same.ts" },
- { status: "M", path: "src/cli/src/same.ts" },
- { status: "C100", old_path: "src/cli/src/a.ts", path: "src/cli/src/same.ts" },
- { status: "R090", old_path: "src/cli/src/a.ts", path: "src/cli/src/same.ts" },
- { status: "R100", old_path: "src/cli/src/z.ts", path: "src/cli/src/same.ts" },
+ { status: "A", path: "src/app/src/same.ts" },
+ { status: "M", path: "src/app/src/same.ts" },
+ { status: "C100", old_path: "src/app/src/a.ts", path: "src/app/src/same.ts" },
+ { status: "R090", old_path: "src/app/src/a.ts", path: "src/app/src/same.ts" },
+ { status: "R100", old_path: "src/app/src/z.ts", path: "src/app/src/same.ts" },
])
})
})
diff --git a/scripts/ci/characterization-guard.test.ts b/scripts/ci/characterization-guard.test.ts
index b3443e4af..377d5f6b3 100644
--- a/scripts/ci/characterization-guard.test.ts
+++ b/scripts/ci/characterization-guard.test.ts
@@ -12,7 +12,7 @@ import {
const candidateSha = "a".repeat(40)
const fixtureSha = "b".repeat(40)
-const sourcePath = "src/cli/commands/update.ts"
+const sourcePath = "src/app/src/commands/update.ts"
function validInput() {
const manifest = loadScopeManifest()
@@ -102,7 +102,7 @@ describe("validateCharacterization", () => {
["merge commit", { parentShas: [candidateSha, "c".repeat(40)] }],
["ancestor", { isAncestor: false }],
["regular source", { fileMode: "120000" }],
- ["single source", { changes: [{ status: "M", path: sourcePath }, { status: "M", path: "src/cli/lib/config.ts" }] }],
+ ["single source", { changes: [{ status: "M", path: sourcePath }, { status: "M", path: "src/app/src/config.ts" }] }],
["deletion", { changes: [{ status: "D", path: sourcePath }] }],
["class", { expectedClass: "shared" }],
])("rejects invalid %s evidence", (_label, override) => {
@@ -121,7 +121,7 @@ describe("validateCharacterization", () => {
}
expect(() => validateCharacterization(drift)).toThrow("blob")
- const testPath = "src/cli/commands/update.test.ts"
+ const testPath = "src/app/src/commands/update.test.ts"
const nonCoverable = validInput()
nonCoverable.changes = [{ status: "M", path: testPath }]
nonCoverable.plan = buildExecutionPlan(nonCoverable.changes, {
@@ -147,11 +147,11 @@ describe("validateCharacterization", () => {
it("rejects full, mixed, unknown, and non-diagnostic plans", () => {
for (const path of [
".github/workflows/ci.yml",
- "src/cli/commands/update.ts",
+ "src/app/src/commands/update.ts",
"unexpected/file.ts",
]) {
const input = validInput()
- input.changes = path === "src/cli/commands/update.ts"
+ input.changes = path === "src/app/src/commands/update.ts"
? [{ status: "M", path }, { status: "M", path: "src/shared/src/semver.ts" }]
: [{ status: "M", path }]
input.plan = buildExecutionPlan(input.changes, {
@@ -174,7 +174,7 @@ describe("validateCharacterization", () => {
describe("characterization guard CLI", () => {
it.each([
- ["package", "src/cli/src/commands/inbox.ts"],
+ ["package", "src/app/src/commands/status.ts"],
["auth", "src/web/auth/index.ts"],
["blog", "src/web/blog/src/lib/posts.ts"],
["shared", "src/shared/src/semver.ts"],
diff --git a/scripts/ci/logo-assets.test.ts b/scripts/ci/logo-assets.test.ts
index 69c1dfd0a..91de3b5a1 100644
--- a/scripts/ci/logo-assets.test.ts
+++ b/scripts/ci/logo-assets.test.ts
@@ -14,8 +14,8 @@ import {
} from "../generate-logo-assets.mjs"
const repoRoot = resolve(import.meta.dirname, "../..")
-const requireFromCli = createRequire(resolve(repoRoot, "src/cli/package.json"))
-const sharp = requireFromCli("sharp")
+const requireFromRoot = createRequire(resolve(repoRoot, "package.json"))
+const sharp = requireFromRoot("sharp")
const androidLegacyIconSizes = {
mdpi: 48,
diff --git a/scripts/ci/validate-execution-plan.test.ts b/scripts/ci/validate-execution-plan.test.ts
index e241e5502..2aedf4a89 100644
--- a/scripts/ci/validate-execution-plan.test.ts
+++ b/scripts/ci/validate-execution-plan.test.ts
@@ -3,7 +3,7 @@ import { buildExecutionPlan, projectPlan, stablePlanJson } from "./changed-scope
import { runCli, runIfMain, validatePlanEnvelope } from "./validate-execution-plan.mjs"
const plan = buildExecutionPlan(
- [{ status: "M", path: "src/cli/src/commands/inbox.ts" }],
+ [{ status: "M", path: "src/daemon/src/manager.ts" }],
{ baseSha: "a".repeat(40), headSha: "b".repeat(40) },
)
diff --git a/scripts/ci/verify-coverage-plan.test.ts b/scripts/ci/verify-coverage-plan.test.ts
index e41786142..078851206 100644
--- a/scripts/ci/verify-coverage-plan.test.ts
+++ b/scripts/ci/verify-coverage-plan.test.ts
@@ -126,30 +126,30 @@ describe("verifyCoveragePlan", () => {
})
it("proves required changed files and a nonempty passing Codecov project denominator", () => {
- const changed = "src/cli/commands/update.ts"
+ const changed = "src/email-worker/src/index.ts"
const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })
const report = {
[resolve(changed)]: coveredFile(resolve(changed)),
- [resolve("src/cli/lib/config.ts")]: coveredFile(resolve("src/cli/lib/config.ts")),
+ [resolve("src/email-worker/src/lib/imap-client.ts")]: coveredFile(resolve("src/email-worker/src/lib/imap-client.ts")),
}
const result = verifyCoveragePlan(plan, report)
expect(result.required_changed_files).toEqual([changed])
- expect(result.targets.cli).toMatchObject({ files: 2, statements: 2, covered: 2, percent: 100 })
+ expect(result.targets["email-worker"]).toMatchObject({ files: 2, statements: 2, covered: 2, percent: 100 })
})
it("rejects a required surviving changed file missing from the merged report", () => {
- const changed = "src/cli/commands/update.ts"
+ const changed = "src/email-worker/src/index.ts"
const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })
expect(() => verifyCoveragePlan(plan, {
- [resolve("src/cli/lib/config.ts")]: coveredFile(resolve("src/cli/lib/config.ts")),
+ [resolve("src/email-worker/src/lib/imap-client.ts")]: coveredFile(resolve("src/email-worker/src/lib/imap-client.ts")),
})).toThrow("required changed coverage file")
})
it("rejects a required changed file that is absent from the checked-out head", () => {
- const changed = "src/cli/commands/update.ts"
+ const changed = "src/email-worker/src/index.ts"
const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })
const root = mkdtempSync(join(tmpdir(), "alook-coverage-head-"))
try {
@@ -171,7 +171,7 @@ describe("verifyCoveragePlan", () => {
expect(() => verifyCoveragePlan(testOnlyPlan, {})).toThrow("nonempty denominator")
expect(() => verifyCoveragePlan(plan, {
- [resolve("src/cli/lib/config.ts")]: coveredFile(resolve("src/cli/lib/config.ts")),
+ [resolve("src/email-worker/src/lib/imap-client.ts")]: coveredFile(resolve("src/email-worker/src/lib/imap-client.ts")),
[resolve("src/email-worker/src/index.ts")]: coveredFile(resolve("src/email-worker/src/index.ts")),
[resolve(changed)]: coveredFile(resolve(changed), false),
[resolve("src/web/src/lib/config.ts")]: coveredFile(resolve("src/web/src/lib/config.ts")),
@@ -180,7 +180,7 @@ describe("verifyCoveragePlan", () => {
})
it("rejects targets absent from the Codecov contract", () => {
- const changed = "src/cli/commands/update.ts"
+ const changed = "src/email-worker/src/index.ts"
const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })
const invalid = structuredClone(plan)
invalid.coverage.targets = ["future"]
@@ -191,7 +191,7 @@ describe("verifyCoveragePlan", () => {
})
it("writes an auditable target manifest from the CLI", () => {
- const changed = "src/cli/commands/update.ts"
+ const changed = "src/email-worker/src/index.ts"
const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })
const directory = mkdtempSync(join(tmpdir(), "alook-coverage-plan-"))
const planPath = join(directory, "plan.json")
diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.ts
index e88ce35f5..c8aa56eff 100644
--- a/scripts/ci/workflow-contract.test.ts
+++ b/scripts/ci/workflow-contract.test.ts
@@ -185,7 +185,7 @@ const desktopUpdateRoute = readFileSync(
resolve(import.meta.dirname, "../../src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.ts"),
"utf8",
)
-const publishWorkflows = ["publish-app.yml", "publish-cli.yml", "publish-daemon.yml"]
+const publishWorkflows = ["publish-app.yml", "publish-daemon.yml"]
.map((name) => normalizeWorkflow(readFileSync(resolve(workflowRoot, name), "utf8")))
const publishDaemonWorkflow = normalizeWorkflow(
readFileSync(resolve(workflowRoot, "publish-daemon.yml"), "utf8"),
@@ -431,7 +431,6 @@ describe("CI workflow graph", () => {
it("prepares shared services for every selected integration suite", () => {
const e2e = ciJob("e2e")
const webCondition = "if: contains(fromJSON(needs.scope.outputs.integration_suites), 'web')"
- const cliCondition = "if: contains(fromJSON(needs.scope.outputs.integration_suites), 'cli')"
const daemonCondition = "if: contains(fromJSON(needs.scope.outputs.integration_suites), 'daemon')"
expect(e2e).toContain("if: needs.scope.outputs.run_e2e == 'true'")
@@ -453,12 +452,9 @@ describe("CI workflow graph", () => {
expect(e2e).not.toContain('pkill -f "wrangler"')
expect(e2e.match(new RegExp(webCondition.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g")))
.toHaveLength(1)
- expect(e2e.match(new RegExp(cliCondition.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g")))
- .toHaveLength(1)
expect(e2e.match(new RegExp(daemonCondition.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g")))
.toHaveLength(1)
expect(e2e).toContain(`${webCondition}\n run: pnpm test:e2e`)
- expect(e2e).toContain(`${cliCondition}\n run: pnpm --filter @alook/cli run test:integration`)
expect(e2e).toContain(`${daemonCondition}\n run: pnpm --filter @alook/daemon run test:integration`)
})
@@ -625,7 +621,7 @@ describe("CI test budgets", () => {
it("runs only Windows-relevant workspace packages after the process-bearing suites", () => {
const windows = ciJob("test-windows")
- expect(windows).toContain("for suite in app cli shared")
+ expect(windows).toContain("for suite in app shared")
expect(windows).toContain('filters+=("--filter=@alook/$suite")')
expect(windows).toContain('pnpm turbo run test "${filters[@]}"')
expect(windows).not.toContain("--affected")
@@ -879,7 +875,6 @@ describe("Turbo CI execution", () => {
"src/web/vitest.dom.config.ts",
"src/web/auth/vitest.config.ts",
"src/web/auth/vitest.runtime.config.mts",
- "src/cli",
"src/daemon",
"src/daemon/agent-driver",
"src/email-worker",
diff --git a/scripts/generate-logo-assets.mjs b/scripts/generate-logo-assets.mjs
index b7b7f7f12..e15c6f74b 100644
--- a/scripts/generate-logo-assets.mjs
+++ b/scripts/generate-logo-assets.mjs
@@ -13,8 +13,8 @@ import { createRequire } from "node:module"
import { fileURLToPath, pathToFileURL } from "node:url"
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..")
-const requireFromCli = createRequire(pathToFileURL(resolve(repoRoot, "src/cli/package.json")))
-const sharp = requireFromCli("sharp")
+const requireFromRoot = createRequire(pathToFileURL(resolve(repoRoot, "package.json")))
+const sharp = requireFromRoot("sharp")
export const preservedAssets = [
"src/web/src/app/favicon.ico",
diff --git a/src/cli/LICENSE b/src/cli/LICENSE
deleted file mode 100644
index dfbb4b150..000000000
--- a/src/cli/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for describing the origin of the Work and
- reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Support. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or support.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 2026 Alook
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied. See the License for the specific language governing permissions
- and limitations under the License.
diff --git a/src/cli/README.md b/src/cli/README.md
deleted file mode 100644
index f0832d613..000000000
--- a/src/cli/README.md
+++ /dev/null
@@ -1,149 +0,0 @@
-# @alook/cli
-
-Alook CLI — register machines, run the daemon, and manage agents from the command line.
-
-## Install
-
-```bash
-npx @alook/cli <command>
-```
-
-## Quick Start
-
-1. Generate a machine token from the [Alook dashboard](https://alook.ai).
-2. Register this machine:
-
-```bash
-npx @alook/cli register --token al_xxxxxxxxxxxxxxxxxxxxxxxx
-```
-
-3. Start the daemon:
-
-```bash
-npx @alook/cli daemon start
-```
-
-The daemon runs in the background, polling for tasks and dispatching them to your local AI runtimes (Claude, Codex, or OpenCode).
-
-## Commands
-
-| Command | Description |
-| --- | --- |
-| `register --token <token>` | Register this machine with your Alook account |
-| `status` | Show registration status and linked workspace |
-| `daemon start` | Start the background daemon |
-| `daemon stop` | Stop the daemon |
-| `email pull` | Download agent emails |
-| `email send --to <addr> --subject "..." --body-file <path>` | Send an email |
-| `calendar set --event_title "..." --datetime <YYYY-MM-DDTHH:MM>` | Create a scheduled event |
-| `issue create --title "..."` | Create and dispatch an issue |
-| `sync upload-artifact --conversation_id <id> --file <path>` | Upload a file artifact |
-| `config show` | Show current configuration |
-| `update` | Update CLI to the latest version |
-| `version` | Print CLI version |
-
-Run `npx @alook/cli <command> --help` for all subcommand options.
-
-<details>
-<summary><strong>daemon</strong> — manage the background daemon</summary>
-
-```bash
-alook daemon start # Start in background
-alook daemon start --foreground # Start in foreground (for debugging)
-alook daemon stop # Stop the daemon
-alook daemon status # Check if the daemon is running
-```
-
-</details>
-
-<details>
-<summary><strong>email</strong> — pull, send, reply, forward, and manage sender whitelist</summary>
-
-```bash
-alook email pull # Download inbox
-alook email pull --status unread # Unread only
-alook email pull --folder sent # Sent emails
-alook email set --email_id <id> --status read # Mark as read
-
-alook email send --to <addr> --subject "Hi" --body-file body.html
-alook email send ... --in-reply-to <email_id> # Reply to a thread
-alook email send ... --attachment report.pdf # Attach a file
-alook email forward --email_id <id> --to <addr> --note "FYI"
-
-alook email whitelist list # List allowed senders
-alook email whitelist add <email> # Allow a sender
-alook email whitelist delete <email> # Remove a sender
-```
-
-Options: `--from <addr>` to send from a custom mailbox, `--limit <n>` / `--offset <n>` for pagination, `--json` for machine-readable output.
-
-</details>
-
-<details>
-<summary><strong>calendar</strong> — schedule one-off or recurring agent events</summary>
-
-When an event fires, a new task is dispatched to the agent with the event title as the prompt.
-
-```bash
-alook calendar set --event_title "Daily standup" --datetime 2026-05-16T09:00
-alook calendar set ... --repeat 1week --repeat_stop_date 2026-12-31
-
-alook calendar list # List upcoming events
-alook calendar show --event_id <id> # Show full detail
-alook calendar update --event_id <id> --datetime 2026-05-17T10:00
-alook calendar delete --event_id <id>
-```
-
-Datetime is always local time (`YYYY-MM-DDTHH:MM`). Repeat intervals: `1hour`, `1day`, `1week`, `1month`, etc.
-
-</details>
-
-<details>
-<summary><strong>issue</strong> — create and manage issues assigned to agents</summary>
-
-```bash
-alook issue create --title "Fix login bug"
-alook issue create --title "Refactor auth" --body-file spec.md
-
-alook issue list # Active issues
-alook issue list --completed # Completed/closed issues
-alook issue show --issue_id <id> # Full detail + conversation
-alook issue update --issue_id <id> --status done
-alook issue comment --issue_id <id> --body "Looks good"
-```
-
-Statuses: `todo`, `in_progress`, `review`, `done`, `closed`, `canceled`, `failed`.
-
-</details>
-
-<details>
-<summary><strong>config</strong> — manage CLI configuration</summary>
-
-```bash
-alook config show # Show current config
-alook config path # Show config file path
-```
-
-Config is stored at `~/.alook/config.json` and includes:
-
-- `server_url` — Alook server URL
-- `profiles` — per-profile settings with workspace bindings
-- `watched_workspaces` — workspaces the daemon monitors (each with `id`, `name`, `token`, `agent_ids`)
-
-</details>
-
-## Global Options
-
-```
---server <url> Override server URL
---profile <name> Use a specific config profile
---agent_id <id> Override agent ID (default: $ALOOK_AGENT_ID env var)
-```
-
-## Requirements
-
-- Node.js >= 20
-
-## License
-
-Apache-2.0 — see [LICENSE](../../LICENSE).
diff --git a/src/cli/RELEASING.md b/src/cli/RELEASING.md
deleted file mode 100644
index 5f7b6a72a..000000000
--- a/src/cli/RELEASING.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# Releasing @alook/cli
-
-Releases are triggered by pushing a tag of the form `cli/vX.Y.Z`:
-
-```bash
-git tag cli/v0.2.0
-git push origin cli/v0.2.0
-```
-
-The [`Publish CLI`](../../.github/workflows/publish-cli.yml) workflow will:
-
-1. Validate the tag format (`cli/vX.Y.Z` or `cli/vX.Y.Z-prerelease`)
-2. Set `src/cli/package.json` version to the tag's version (in-job, not committed)
-3. Build the Node ESM bundle (inlines `@alook/shared` and its deps)
-4. Publish `@alook/[email protected]` to npm via **OIDC + provenance**
-5. Create a GitHub Release with auto-generated notes
-
-No npm token lives in CI. The package is registered with [Trusted Publishers](https://docs.npmjs.com/trusted-publishers) on npmjs.com.
-
-## Prerelease versions
-
-Use tags like `cli/v0.2.0-beta.1` or `cli/v1.0.0-rc.1`. The npm `latest` dist-tag is **not** automatically moved for prereleases — users pin with `npm i @alook/[email protected]`.
-
-If you want a `next` dist-tag, pass `--tag next` to the publish step (requires editing the workflow).
-
-## Rolling back
-
-Within 72h of publishing, you can unpublish a specific version:
-
-```bash
-npm unpublish @alook/[email protected]
-```
-
-After 72h, use deprecation instead:
-
-```bash
-npm deprecate @alook/[email protected] "broken release, please upgrade to 0.2.1"
-```
-
-## Local smoke test before tagging
-
-```bash
-cd src/cli
-pnpm run build
-node dist/index.js --help
-npm pack --dry-run # inspect the tarball contents
-```
diff --git a/src/cli/commands/agent.ts b/src/cli/commands/agent.ts
deleted file mode 100644
index d00e8a023..000000000
--- a/src/cli/commands/agent.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-import { Command } from "commander";
-import { readFileSync } from "fs";
-import { APIClient } from "../lib/client.js";
-import { printJSON } from "../lib/output.js";
-import { resolveAgentId } from "../lib/flags.js";
-import { resolveClientOpts } from "../lib/resolve-client.js";
-import { gatherContextEnvVars } from "../lib/context-env.js";
-
-function readField(opts: { inline?: string; file?: string }, inlineName: string, fileName: string): string | null {
- if (opts.inline && opts.file) {
- console.error(`Error: --${inlineName} and --${fileName} are mutually exclusive`);
- process.exit(1);
- }
- if (opts.file) return readFileSync(opts.file, "utf-8");
- return opts.inline ?? null;
-}
-
-export function agentCommand(): Command {
- const cmd = new Command("agent").description("Manage agents");
-
- cmd
- .command("recruit")
- .description("Recruit a new colleague agent")
- .option("--agent_id <id>", "Agent ID (or set ALOOK_AGENT_ID env var)")
- .option("--instructions <text>", "Instructions for the new agent (system prompt)")
- .option("--instructions-file <path>", "Read instructions from a file")
- .option("--relationship <text>", "Relationship/delegation instruction for the link")
- .option("--relationship-file <path>", "Read relationship from a file")
- .option("--name <name>", "Preferred name for the new agent (auto-generated if omitted)")
- .option("--description <text>", "Agent description")
- .option("--model <model>", "Model override")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const instructions = readField(
- { inline: opts.instructions, file: opts.instructionsFile },
- "instructions",
- "instructions-file",
- );
- if (!instructions) {
- console.error("Error: --instructions or --instructions-file is required");
- process.exit(1);
- }
-
- const relationship = readField(
- { inline: opts.relationship, file: opts.relationshipFile },
- "relationship",
- "relationship-file",
- );
- if (!relationship) {
- console.error("Error: --relationship or --relationship-file is required");
- process.exit(1);
- }
-
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- const ctx = gatherContextEnvVars();
- const body: Record<string, string> = { instructions, relationship };
- if (opts.name) body.name = opts.name;
- if (opts.description) body.description = opts.description;
- if (opts.model) body.model = opts.model;
- if (ctx.conversationId) body.context_key = ctx.conversationId;
-
- try {
- const res = await client.postJSON<{
- agent: { id: string; name: string; email: string };
- link: { id: string; instruction: string };
- }>(`/api/agents/recruit?agentId=${encodeURIComponent(agentId)}`, body);
-
- if (opts.json) return printJSON(res);
- console.log(`Recruited ${res.agent.name} (${res.agent.email}) — ${res.agent.id}`);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("link")
- .description("Set (create-or-replace) the relationship with an existing colleague agent")
- .option("--agent_id <id>", "Calling agent ID (or set ALOOK_AGENT_ID env var)")
- .option("--to <handleOrId>", "Target agent: email handle (coder / [email protected]) or agent id (ag_...)")
- .option("--relationship <text>", "Relationship/delegation instruction for the link")
- .option("--relationship-file <path>", "Read relationship from a file")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const relationship = readField(
- { inline: opts.relationship, file: opts.relationshipFile },
- "relationship",
- "relationship-file",
- );
- if (!relationship) {
- console.error("Error: --relationship or --relationship-file is required");
- process.exit(1);
- }
-
- const to = opts.to as string | undefined;
- if (!to) {
- console.error("Error: --to <handleOrId> is required");
- process.exit(1);
- }
-
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- type AgentInfo = { id: string; name: string; email_handle: string | null };
-
- try {
- // Resolve target to an agent id. ag_-prefixed values are ids; anything
- // else is treated as an email handle (domain stripped) and resolved via
- // GET /api/agents, which returns id + email_handle for each agent.
- let targetAgentId: string;
- let agents: AgentInfo[] | null = null;
- if (to.startsWith("ag_")) {
- targetAgentId = to;
- } else {
- const handle = to.split("@")[0].toLowerCase();
- agents = await client.getJSON<AgentInfo[]>("/api/agents");
- const match = agents.find((a) => (a.email_handle || "").toLowerCase() === handle);
- if (!match) {
- console.error(`Error: no agent with handle '${handle}' in this workspace`);
- process.exit(1);
- }
- targetAgentId = match.id;
- }
-
- const res = await client.putJSON<{
- id: string;
- source_agent_id: string;
- target_agent_id: string;
- instruction: string;
- created: boolean;
- }>(`/api/agent-links?agentId=${encodeURIComponent(agentId)}`, {
- target_agent_id: targetAgentId,
- instruction: relationship,
- });
-
- if (opts.json) return printJSON(res);
-
- // Best-effort friendly labels; fall back to ids if names aren't handy.
- if (!agents) {
- try {
- agents = await client.getJSON<AgentInfo[]>("/api/agents");
- } catch {
- agents = [];
- }
- }
- const label = (id: string) => agents!.find((a) => a.id === id)?.name || id;
- const meLabel = label(agentId);
- const targetLabel = label(targetAgentId);
- console.log(`Linked ${meLabel} <-> ${targetLabel} (${res.created ? "created" : "updated"})`);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/calendar.test.ts b/src/cli/commands/calendar.test.ts
deleted file mode 100644
index 44c048929..000000000
--- a/src/cli/commands/calendar.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { calendarCommand } from "./calendar";
-
-describe("calendarCommand", () => {
- const cmd = calendarCommand();
-
- it("registers set, list, show, update, and delete subcommands", () => {
- const names = cmd.commands.map((c) => c.name());
- expect(names).toContain("set");
- expect(names).toContain("list");
- expect(names).toContain("show");
- expect(names).toContain("update");
- expect(names).toContain("delete");
- });
-
- it("calendar set requires --event_title, --datetime; --agent_id is optional (env fallback)", () => {
- const set = cmd.commands.find((c) => c.name() === "set")!;
- const opts = (set as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).not.toContain("--agent_id");
- expect(mandatory).toContain("--event_title");
- expect(mandatory).toContain("--datetime");
- // not mandatory
- expect(mandatory).not.toContain("--repeat");
- expect(mandatory).not.toContain("--repeat_stop_date");
- });
-
- it("calendar set accepts --repeat and --repeat_stop_date as optional", () => {
- const set = cmd.commands.find((c) => c.name() === "set")!;
- const opts = (set as unknown as { options: { long: string }[] }).options;
- const longs = opts.map((o) => o.long);
- expect(longs).toContain("--repeat");
- expect(longs).toContain("--repeat_stop_date");
- });
-
- it("calendar set accepts --description as optional", () => {
- const set = cmd.commands.find((c) => c.name() === "set")!;
- const opts = (set as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const descOpt = opts.find((o) => o.long === "--description");
- expect(descOpt).toBeDefined();
- expect(descOpt?.mandatory).not.toBe(true);
- });
-
- it("calendar list has optional --agent_id (env fallback); supports --future_days and --past_days", () => {
- const list = cmd.commands.find((c) => c.name() === "list")!;
- const opts = (list as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).not.toContain("--agent_id");
- const longs = opts.map((o) => o.long);
- expect(longs).toContain("--agent_id");
- expect(longs).toContain("--future_days");
- expect(longs).toContain("--past_days");
- });
-
- it("calendar show requires --event_id; --agent_id is optional (env fallback)", () => {
- const show = cmd.commands.find((c) => c.name() === "show")!;
- const opts = (show as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).not.toContain("--agent_id");
- expect(mandatory).toContain("--event_id");
- });
-
- it("calendar update requires --event_id; --agent_id is optional (env fallback); accepts mutating flags", () => {
- const update = cmd.commands.find((c) => c.name() === "update")!;
- const opts = (update as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).not.toContain("--agent_id");
- expect(mandatory).toContain("--event_id");
- const longs = opts.map((o) => o.long);
- for (const flag of [
- "--event_title",
- "--description",
- "--clear_description",
- "--datetime",
- "--repeat",
- "--clear_repeat",
- "--repeat_stop_date",
- "--clear_repeat_stop_date",
- ]) {
- expect(longs).toContain(flag);
- expect(mandatory).not.toContain(flag);
- }
- });
-
- it("calendar delete requires --event_id; --agent_id is optional (env fallback)", () => {
- const del = cmd.commands.find((c) => c.name() === "delete")!;
- const opts = (del as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).not.toContain("--agent_id");
- expect(mandatory).toContain("--event_id");
- });
-
- it("no subcommand accepts --workspace (agent-scoped only)", () => {
- for (const sub of cmd.commands) {
- const opts = (sub as unknown as { options: { long: string }[] }).options;
- const longs = opts.map((o) => o.long);
- expect(longs).not.toContain("--workspace");
- }
- });
-});
diff --git a/src/cli/commands/calendar.ts b/src/cli/commands/calendar.ts
deleted file mode 100644
index fe55b0c6f..000000000
--- a/src/cli/commands/calendar.ts
+++ /dev/null
@@ -1,348 +0,0 @@
-import { Command } from "commander";
-import { APIClient } from "../lib/client.js";
-import { printJSON } from "../lib/output.js";
-import { resolveAgentId } from "../lib/flags.js";
-import { resolveClientOpts } from "../lib/resolve-client.js";
-
-interface CalendarEventResponse {
- id: string;
- agent_id: string;
- workspace_id: string;
- title: string;
- description: string | null;
- scheduled_at: string;
- occurrence_at?: string;
- collapsed_count?: number | null;
- repeat_interval: string | null;
- repeat_stop_at: string | null;
- last_triggered_at: string | null;
- created_at: string;
- updated_at: string;
-}
-
-
-function parseLocalDatetime(input: string): string {
- // Accepts YYYY-MM-DDTHH:MM and interprets as local time.
- const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(
- input
- );
- if (!match) {
- throw new Error(
- `invalid --datetime "${input}" — expected YYYY-MM-DDTHH:MM`
- );
- }
- const [, y, mo, d, h, mi, s] = match;
- const date = new Date(
- Number(y),
- Number(mo) - 1,
- Number(d),
- Number(h),
- Number(mi),
- s ? Number(s) : 0
- );
- return date.toISOString();
-}
-
-function formatLocalDatetime(iso: string): string {
- const d = new Date(iso);
- const pad = (n: number) => String(n).padStart(2, "0");
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(
- d.getDate()
- )} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
-}
-
-function printEventDetail(ev: CalendarEventResponse): void {
- console.log(`id: ${ev.id}`);
- console.log(`agent_id: ${ev.agent_id}`);
- console.log(`title: ${ev.title}`);
- console.log(`scheduled_at: ${formatLocalDatetime(ev.scheduled_at)}`);
- if (ev.repeat_interval) {
- const until = ev.repeat_stop_at
- ? ` until ${formatLocalDatetime(ev.repeat_stop_at)}`
- : "";
- console.log(`repeat: every ${ev.repeat_interval}${until}`);
- } else {
- console.log(`repeat: (none)`);
- }
- console.log(
- `last_fired_at: ${
- ev.last_triggered_at ? formatLocalDatetime(ev.last_triggered_at) : "(never)"
- }`
- );
- console.log("description:");
- console.log(ev.description ?? "(no description)");
-}
-
-export function calendarCommand(): Command {
- const cmd = new Command("calendar").description(
- "Manage scheduled agent events"
- );
-
- cmd
- .command("set")
- .description("Create a calendar event")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--event_title <title>", "Event title (used as the task prompt)")
- .requiredOption(
- "--datetime <iso>",
- "Scheduled datetime (YYYY-MM-DDTHH:MM, local time)"
- )
- .option("--description <text>", "Optional longer-form notes for the event")
- .option("--repeat <interval>", "Repeat interval, e.g. 1day, 2hour, 1month")
- .option(
- "--repeat_stop_date <date>",
- "Stop repeating on or after this date (YYYY-MM-DD, local time)"
- )
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- let scheduledAt: string;
- try {
- scheduledAt = parseLocalDatetime(opts.datetime);
- } catch (err) {
- console.error(
- `Error: ${err instanceof Error ? err.message : String(err)}`
- );
- process.exit(1);
- }
-
- if (opts.repeat_stop_date && !opts.repeat) {
- console.error("Error: --repeat_stop_date requires --repeat");
- process.exit(1);
- }
- if (opts.repeat_stop_date && !/^\d{4}-\d{2}-\d{2}$/.test(opts.repeat_stop_date)) {
- console.error("Error: --repeat_stop_date must be YYYY-MM-DD");
- process.exit(1);
- }
-
- const body: Record<string, unknown> = {
- agent_id: agentId,
- title: opts.event_title,
- scheduled_at: scheduledAt,
- };
- if (opts.description) body.description = opts.description;
- if (opts.repeat) body.repeat_interval = opts.repeat;
- if (opts.repeat_stop_date) body.repeat_stop_date = opts.repeat_stop_date;
- if (process.env.ALOOK_CONVERSATION_ID) body.conversation_id = process.env.ALOOK_CONVERSATION_ID;
-
- try {
- const created = await client.postJSON<CalendarEventResponse>(
- "/api/calendar",
- body
- );
- if (opts.json) {
- printJSON(created);
- return;
- }
- console.log(
- `Created ${created.id} — ${created.title} @ ${formatLocalDatetime(
- created.scheduled_at
- )}${created.repeat_interval ? ` (every ${created.repeat_interval})` : ""}`
- );
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("list")
- .description("List calendar events for an agent")
- .option("--agent_id <id>", "Agent ID")
- .option("--future_days <n>", "Include events scheduled in the next N days", "30")
- .option("--past_days <n>", "Include events scheduled in the past N days", "0")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- const now = Date.now();
- const from = new Date(
- now - Number(opts.past_days) * 86_400_000
- ).toISOString();
- const to = new Date(
- now + Number(opts.future_days) * 86_400_000
- ).toISOString();
-
- try {
- const events = await client.getJSON<CalendarEventResponse[]>(
- `/api/calendar?agentId=${encodeURIComponent(agentId)}&from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`
- );
- if (opts.json) {
- printJSON(events);
- return;
- }
- if (events.length === 0) {
- console.log("No calendar events.");
- return;
- }
- for (const ev of events) {
- const repeatBadge = ev.repeat_interval
- ? ` [every ${ev.repeat_interval}${ev.collapsed_count ? ` · ${ev.collapsed_count} occurrences` : ""}${ev.repeat_stop_at ? ` until ${formatLocalDatetime(ev.repeat_stop_at)}` : ""}]`
- : "";
- const descBadge = ev.description ? " [has description]" : "";
- console.log(
- `${ev.id} ${formatLocalDatetime(ev.scheduled_at)} ${ev.title}${repeatBadge}${descBadge}`
- );
- }
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("show")
- .description("Show the full detail of a single calendar event")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--event_id <id>", "Event ID")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- try {
- const ev = await client.getJSON<CalendarEventResponse>(
- `/api/calendar/${opts.event_id}`
- );
- if (ev.agent_id !== agentId) {
- console.error(
- `Error: event ${ev.id} does not belong to agent ${agentId}`
- );
- process.exit(1);
- }
- if (opts.json) {
- printJSON(ev);
- return;
- }
- printEventDetail(ev);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("update")
- .description("Update fields on an existing calendar event")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--event_id <id>", "Event ID")
- .option("--event_title <title>", "New event title (task prompt)")
- .option("--description <text>", "New description text")
- .option("--clear_description", "Remove the description (sets to null)")
- .option(
- "--datetime <iso>",
- "New scheduled datetime (YYYY-MM-DDTHH:MM, local time)"
- )
- .option("--repeat <interval>", "New repeat interval, e.g. 1day, 2hour")
- .option("--clear_repeat", "Convert a repeating event into a one-off")
- .option(
- "--repeat_stop_date <date>",
- "New stop date (YYYY-MM-DD, local time)"
- )
- .option("--clear_repeat_stop_date", "Remove the repeat stop date")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- if (opts.description && opts.clear_description) {
- console.error(
- "Error: --description and --clear_description are mutually exclusive"
- );
- process.exit(1);
- }
- if (opts.repeat && opts.clear_repeat) {
- console.error(
- "Error: --repeat and --clear_repeat are mutually exclusive"
- );
- process.exit(1);
- }
- if (opts.repeat_stop_date && opts.clear_repeat_stop_date) {
- console.error(
- "Error: --repeat_stop_date and --clear_repeat_stop_date are mutually exclusive"
- );
- process.exit(1);
- }
-
- const body: Record<string, unknown> = {};
- if (opts.event_title) body.title = opts.event_title;
- if (opts.description) body.description = opts.description;
- if (opts.clear_description) body.description = null;
- if (opts.datetime) {
- try {
- body.scheduled_at = parseLocalDatetime(opts.datetime);
- } catch (err) {
- console.error(
- `Error: ${err instanceof Error ? err.message : String(err)}`
- );
- process.exit(1);
- }
- }
- if (opts.repeat) body.repeat_interval = opts.repeat;
- if (opts.clear_repeat) body.repeat_interval = null;
- if (opts.repeat_stop_date) {
- if (!/^\d{4}-\d{2}-\d{2}$/.test(opts.repeat_stop_date)) {
- console.error("Error: --repeat_stop_date must be YYYY-MM-DD");
- process.exit(1);
- }
- body.repeat_stop_date = opts.repeat_stop_date;
- }
- if (opts.clear_repeat_stop_date) body.repeat_stop_date = null;
-
- if (Object.keys(body).length === 0) {
- console.error(
- "Error: no fields to update — pass at least one of --event_title, --description, --clear_description, --datetime, --repeat, --clear_repeat, --repeat_stop_date, --clear_repeat_stop_date"
- );
- process.exit(1);
- }
-
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- try {
- const updated = await client.patchJSON<CalendarEventResponse>(
- `/api/calendar/${opts.event_id}`,
- body
- );
- if (updated.agent_id !== agentId) {
- console.error(
- `Error: event ${updated.id} does not belong to agent ${agentId}`
- );
- process.exit(1);
- }
- if (opts.json) {
- printJSON(updated);
- return;
- }
- printEventDetail(updated);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("delete")
- .description("Delete a calendar event")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--event_id <id>", "Event ID")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- try {
- await client.deleteJSON(`/api/calendar/${opts.event_id}`);
- console.log(`Deleted ${opts.event_id}`);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts
deleted file mode 100644
index e6f8251c1..000000000
--- a/src/cli/commands/config.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { Command } from "commander";
-import { loadCLIConfig, configPath } from "../lib/config.js";
-import { printJSON } from "../lib/output.js";
-
-export function configCommand(): Command {
- const cmd = new Command("config").description("Manage CLI configuration");
-
- cmd
- .command("show")
- .description("Show current configuration")
- .action(() => {
- const cfg = loadCLIConfig();
- printJSON(cfg);
- });
-
- cmd
- .command("path")
- .description("Show config file path")
- .action(() => {
- console.log(configPath());
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/daemon.test.ts b/src/cli/commands/daemon.test.ts
deleted file mode 100644
index b2023cf54..000000000
--- a/src/cli/commands/daemon.test.ts
+++ /dev/null
@@ -1,344 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import type { EventEmitter } from "events";
-
-vi.mock("../daemon/daemon.js", () => ({
- startDaemon: vi.fn(async () => {}),
-}));
-
-vi.mock("../daemon/pidfile.js", () => ({
- readDaemonPid: vi.fn(() => null),
- isProcessAlive: vi.fn(() => false),
- removePidFileIfMatches: vi.fn(),
-}));
-
-vi.mock("../daemon/config.js", () => ({
- daemonLogFilePath: vi.fn(() => "/tmp/alook/daemon/logs/2026-04-17.log"),
- pidFilePath: vi.fn(() => "/tmp/fake.pid"),
-}));
-
-vi.mock("fs", () => ({
- openSync: vi.fn(() => 99),
- closeSync: vi.fn(),
- mkdirSync: vi.fn(),
-}));
-
-vi.mock("child_process", () => {
- const { EventEmitter } = require("events");
- return {
- spawn: vi.fn(() => {
- const child = new EventEmitter();
- (child as EventEmitter & { pid: number; unref: () => void }).pid = 40000;
- (child as EventEmitter & { pid: number; unref: () => void }).unref = vi.fn();
- return child;
- }),
- };
-});
-
-import { Command } from "commander";
-import { spawn } from "child_process";
-import { openSync, closeSync, mkdirSync } from "fs";
-import { startDaemon } from "../daemon/daemon.js";
-import {
- readDaemonPid,
- isProcessAlive,
- removePidFileIfMatches,
-} from "../daemon/pidfile.js";
-import { daemonCommand } from "./daemon.js";
-
-const startDaemonMock = vi.mocked(startDaemon);
-const readDaemonPidMock = vi.mocked(readDaemonPid);
-const isProcessAliveMock = vi.mocked(isProcessAlive);
-const removePidFileIfMatchesMock = vi.mocked(removePidFileIfMatches);
-const spawnMock = vi.mocked(spawn);
-const openSyncMock = vi.mocked(openSync);
-const closeSyncMock = vi.mocked(closeSync);
-const mkdirMock = vi.mocked(mkdirSync);
-
-interface ChildLike extends EventEmitter {
- pid: number;
- unref: ReturnType<typeof vi.fn>;
-}
-
-function resetAll() {
- startDaemonMock.mockClear();
- readDaemonPidMock.mockClear();
- readDaemonPidMock.mockReturnValue(null);
- isProcessAliveMock.mockClear();
- isProcessAliveMock.mockReturnValue(false);
- removePidFileIfMatchesMock.mockClear();
- spawnMock.mockClear();
- openSyncMock.mockClear();
- closeSyncMock.mockClear();
- mkdirMock.mockClear();
-}
-
-// Mount the daemon subcommand under a root program with the same top-level
-// --profile / --server flags as the real CLI, so parentOpts resolution is
-// exercised the way users actually invoke it.
-async function runCLI(
- args: string[],
- rootFlags: string[] = [],
-): Promise<{ out: string[]; err: string[] }> {
- const out: string[] = [];
- const err: string[] = [];
- const logSpy = vi.spyOn(console, "log").mockImplementation((m: unknown) => {
- out.push(String(m));
- });
- const errSpy = vi.spyOn(console, "error").mockImplementation((m: unknown) => {
- err.push(String(m));
- });
- const warnSpy = vi.spyOn(console, "warn").mockImplementation((m: unknown) => {
- err.push(String(m));
- });
- const exitSpy = vi
- .spyOn(process, "exit")
- .mockImplementation(((_code?: number) => {
- throw new Error("__exit__");
- }) as never);
- try {
- const program = new Command()
- .name("alook")
- .option("--server <url>", "Server URL")
- .option("--profile <name>", "Profile name");
- program.addCommand(daemonCommand());
- await program.parseAsync([...rootFlags, "daemon", ...args], {
- from: "user",
- });
- } catch (e) {
- if (!(e instanceof Error) || e.message !== "__exit__") throw e;
- } finally {
- logSpy.mockRestore();
- errSpy.mockRestore();
- warnSpy.mockRestore();
- exitSpy.mockRestore();
- }
- return { out, err };
-}
-
-describe("daemon status", () => {
- beforeEach(resetAll);
-
- it("prints 'not running' when no pidfile", async () => {
- const { out } = await runCLI(["status"]);
- expect(out.join("\n")).toContain("Daemon not running.");
- });
-
- it("prints running + pid when alive", async () => {
- readDaemonPidMock.mockReturnValue(12345);
- isProcessAliveMock.mockReturnValue(true);
- const { out } = await runCLI(["status"]);
- expect(out.join("\n")).toContain("Daemon running (pid=12345)");
- });
-
- it("prints stale pidfile when pid is dead", async () => {
- readDaemonPidMock.mockReturnValue(99999);
- isProcessAliveMock.mockReturnValue(false);
- const { out } = await runCLI(["status"]);
- expect(out.join("\n")).toContain("stale pidfile");
- });
-});
-
-describe("daemon stop", () => {
- let killSpy: ReturnType<typeof vi.spyOn>;
-
- beforeEach(() => {
- resetAll();
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- killSpy?.mockRestore();
- vi.useRealTimers();
- });
-
- it("prints 'not running' and does not signal when no pidfile", async () => {
- killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
- const { out } = await runCLI(["stop"]);
- expect(out.join("\n")).toContain("Daemon not running.");
- expect(killSpy).not.toHaveBeenCalled();
- });
-
- it("sends SIGTERM and reports clean stop when process exits", async () => {
- readDaemonPidMock.mockReturnValue(777);
- let alive = true;
- isProcessAliveMock.mockImplementation(() => alive);
- killSpy = vi.spyOn(process, "kill").mockImplementation((_p, sig) => {
- if (sig === "SIGTERM") alive = false;
- return true;
- });
-
- const promise = runCLI(["stop"]);
- await vi.advanceTimersByTimeAsync(500);
- const { out } = await promise;
-
- expect(killSpy).toHaveBeenCalledWith(777, "SIGTERM");
- expect(killSpy).not.toHaveBeenCalledWith(777, "SIGKILL");
- expect(out.join("\n")).toContain("Daemon stopped.");
- });
-
- it("falls back to SIGKILL and removes pidfile when shutdown times out", async () => {
- readDaemonPidMock.mockReturnValue(888);
- let alive = true;
- isProcessAliveMock.mockImplementation(() => alive);
- process.env.ALOOK_SHUTDOWN_TIMEOUT_MS = "1000";
-
- killSpy = vi.spyOn(process, "kill").mockImplementation((_p, sig) => {
- if (sig === "SIGKILL") alive = false;
- return true;
- });
-
- const promise = runCLI(["stop"]);
- await vi.advanceTimersByTimeAsync(1500);
- const { out, err } = await promise;
-
- expect(killSpy).toHaveBeenCalledWith(888, "SIGTERM");
- if (process.platform !== "win32") {
- expect(killSpy).toHaveBeenCalledWith(888, "SIGKILL");
- }
- expect(removePidFileIfMatchesMock).toHaveBeenCalledWith(888, undefined);
- expect(err.join("\n")).toContain("force killing");
- expect(out.join("\n")).toContain("Daemon stopped.");
-
- delete process.env.ALOOK_SHUTDOWN_TIMEOUT_MS;
- });
-
- it("cleans up stale pidfile and reports not running when pid is dead", async () => {
- readDaemonPidMock.mockReturnValue(444);
- isProcessAliveMock.mockReturnValue(false);
- killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
-
- const { out } = await runCLI(["stop"]);
-
- expect(killSpy).not.toHaveBeenCalled();
- expect(removePidFileIfMatchesMock).toHaveBeenCalledWith(444, undefined);
- expect(out.join("\n")).toContain("Daemon not running.");
- });
-});
-
-describe("daemon start (foreground)", () => {
- beforeEach(resetAll);
-
- it("delegates to startDaemon and does not spawn", async () => {
- await runCLI(["start", "--foreground"]);
- expect(startDaemonMock).toHaveBeenCalledTimes(1);
- expect(spawnMock).not.toHaveBeenCalled();
- });
-});
-
-describe("daemon start (background)", () => {
- beforeEach(() => {
- resetAll();
- vi.useFakeTimers();
- // Default spawn: fresh EventEmitter with fake pid each call
- spawnMock.mockImplementation(() => {
- const { EventEmitter } = require("events");
- const c = new EventEmitter() as ChildLike;
- c.pid = 40000;
- c.unref = vi.fn();
- return c as never;
- });
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("spawns detached with log fds and reconstructed args", async () => {
- // Initial pre-check: no daemon running. After spawn: pidfile has pid 55555.
- let calls = 0;
- readDaemonPidMock.mockImplementation(() => (++calls === 1 ? null : 55555));
- isProcessAliveMock.mockImplementation((p: number) => p === 55555);
-
- const promise = runCLI(["start"]);
- await vi.advanceTimersByTimeAsync(250);
- const { out } = await promise;
-
- expect(startDaemonMock).not.toHaveBeenCalled();
- expect(spawnMock).toHaveBeenCalledTimes(1);
- const call = spawnMock.mock.calls[0];
- expect(call[0]).toBe(process.execPath);
- const args = call[1] as string[];
- expect(args).toContain("daemon");
- expect(args).toContain("start");
- expect(args).toContain("--foreground");
- const opts = call[2] as { detached?: boolean; stdio?: unknown };
- expect(opts.detached).toBe(true);
- expect(Array.isArray(opts.stdio)).toBe(true);
- expect((opts.stdio as unknown[])[0]).toBe("ignore");
- expect((opts.stdio as unknown[])[1]).toBe(99);
- expect((opts.stdio as unknown[])[2]).toBe(99);
-
- expect(closeSyncMock).toHaveBeenCalledWith(99);
-
- expect(out.join("\n")).toContain("Daemon started (pid=55555)");
- expect(out.join("\n")).toContain("Logs: /tmp/alook/daemon/logs/2026-04-17.log");
- });
-
- it("forwards --server to child argv", async () => {
- let calls = 0;
- readDaemonPidMock.mockImplementation(() => (++calls === 1 ? null : 101));
- isProcessAliveMock.mockImplementation((p: number) => p === 101);
-
- const promise = runCLI(["start", "--server", "http://x.test"]);
- await vi.advanceTimersByTimeAsync(250);
- await promise;
-
- const args = spawnMock.mock.calls[0][1] as string[];
- const serverIdx = args.indexOf("--server");
- expect(serverIdx).toBeGreaterThanOrEqual(0);
- expect(args[serverIdx + 1]).toBe("http://x.test");
- });
-
- it("forwards root-level --profile to child argv", async () => {
- let calls = 0;
- readDaemonPidMock.mockImplementation(() => (++calls === 1 ? null : 202));
- isProcessAliveMock.mockImplementation((p: number) => p === 202);
-
- const promise = runCLI(["start"], ["--profile", "staging"]);
- await vi.advanceTimersByTimeAsync(250);
- await promise;
-
- const args = spawnMock.mock.calls[0][1] as string[];
- const profileIdx = args.indexOf("--profile");
- expect(profileIdx).toBeGreaterThanOrEqual(0);
- expect(args[profileIdx + 1]).toBe("staging");
- });
-
- it("forwards root-level --server to child argv", async () => {
- let calls = 0;
- readDaemonPidMock.mockImplementation(() => (++calls === 1 ? null : 303));
- isProcessAliveMock.mockImplementation((p: number) => p === 303);
-
- const promise = runCLI(["start"], ["--server", "http://root.test"]);
- await vi.advanceTimersByTimeAsync(250);
- await promise;
-
- const args = spawnMock.mock.calls[0][1] as string[];
- const serverIdx = args.indexOf("--server");
- expect(serverIdx).toBeGreaterThanOrEqual(0);
- expect(args[serverIdx + 1]).toBe("http://root.test");
- });
-
- it("warns and exits non-zero when pidfile never appears", async () => {
- readDaemonPidMock.mockReturnValue(null); // never set
- isProcessAliveMock.mockReturnValue(false);
-
- const promise = runCLI(["start"]);
- await vi.advanceTimersByTimeAsync(2500);
- const { err } = await promise;
-
- expect(err.join("\n")).toContain("did not write a pidfile");
- expect(err.join("\n")).toContain("/tmp/alook/daemon/logs/2026-04-17.log");
- });
-
- it("refuses to start when another daemon is already alive", async () => {
- // Pre-existing alive daemon: readDaemonPid returns pid, isProcessAlive true
- readDaemonPidMock.mockReturnValue(333);
- isProcessAliveMock.mockReturnValue(true);
-
- const { err } = await runCLI(["start"]);
-
- expect(spawnMock).not.toHaveBeenCalled();
- expect(err.join("\n")).toContain("Daemon already running (pid=333)");
- });
-});
diff --git a/src/cli/commands/daemon.ts b/src/cli/commands/daemon.ts
deleted file mode 100644
index f08f7db64..000000000
--- a/src/cli/commands/daemon.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { Command } from "commander";
-import { spawn } from "child_process";
-import { openSync, closeSync, mkdirSync } from "fs";
-import { dirname } from "path";
-import { startDaemon } from "../daemon/daemon.js";
-import { daemonLogFilePath, pidFilePath } from "../daemon/config.js";
-import {
- isProcessAlive,
- readDaemonPid,
- removePidFileIfMatches,
-} from "../daemon/pidfile.js";
-import { resolveLoginShellEnv } from "../lib/shell-env.js";
-import { isWindows } from "../lib/platform.js";
-
-const PID_POLL_INTERVAL_MS = 200;
-const PID_POLL_TIMEOUT_MS = 2000;
-const STOP_POLL_INTERVAL_MS = 200;
-
-function sleep(ms: number): Promise<void> {
- return new Promise((r) => setTimeout(r, ms));
-}
-
-function buildChildArgs(profile?: string, serverUrl?: string): string[] {
- const entry = process.argv[1];
- const args = [entry];
- if (profile) args.push("--profile", profile);
- if (serverUrl) args.push("--server", serverUrl);
- args.push("daemon", "start", "--foreground");
- return args;
-}
-
-async function waitForPidFile(profile: string | undefined): Promise<number | null> {
- const deadline = Date.now() + PID_POLL_TIMEOUT_MS;
- while (Date.now() < deadline) {
- const pid = readDaemonPid(profile);
- if (pid != null && isProcessAlive(pid)) return pid;
- await sleep(PID_POLL_INTERVAL_MS);
- }
- return null;
-}
-
-async function startInBackground(
- profile?: string,
- serverUrl?: string,
-): Promise<void> {
- const existing = readDaemonPid(profile);
- if (existing != null && isProcessAlive(existing)) {
- console.error(`Daemon already running (pid=${existing}).`);
- process.exit(1);
- return;
- }
-
- const logPath = daemonLogFilePath();
- mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 });
- const logFd = openSync(logPath, "a", 0o600);
-
- const child = spawn(process.execPath, buildChildArgs(profile, serverUrl), {
- detached: true,
- stdio: ["ignore", logFd, logFd],
- env: resolveLoginShellEnv(),
- });
- child.unref();
- closeSync(logFd);
-
- const pid = await waitForPidFile(profile);
- if (pid != null) {
- console.log(`Daemon started (pid=${pid})`);
- console.log(`Logs: ${logPath}`);
- return;
- }
- console.error(
- `Daemon did not write a pidfile within ${PID_POLL_TIMEOUT_MS}ms — check logs: ${logPath}`,
- );
- process.exit(1);
-}
-
-function statusCommand(profile: string | undefined): void {
- const pid = readDaemonPid(profile);
- const profileSuffix = profile ? ` profile=${profile}` : "";
- if (pid == null) {
- console.log(`Daemon not running.${profileSuffix}`);
- return;
- }
- if (!isProcessAlive(pid)) {
- console.log(
- `Daemon not running (stale pidfile at ${pidFilePath(profile)}).${profileSuffix}`,
- );
- return;
- }
- console.log(`Daemon running (pid=${pid})${profileSuffix}`);
-}
-
-async function stopCommand(profile: string | undefined): Promise<void> {
- const pid = readDaemonPid(profile);
- if (pid == null) {
- console.log("Daemon not running.");
- return;
- }
- if (!isProcessAlive(pid)) {
- removePidFileIfMatches(pid, profile);
- console.log("Daemon not running.");
- return;
- }
-
- console.log(`Stopping daemon (pid=${pid})...`);
- try {
- process.kill(pid, "SIGTERM");
- } catch (e) {
- console.error(`Failed to signal daemon: ${e}`);
- process.exit(1);
- }
-
- const shutdownMs =
- Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000;
- const deadline = Date.now() + shutdownMs;
- while (Date.now() < deadline) {
- if (!isProcessAlive(pid)) {
- console.log("Daemon stopped.");
- return;
- }
- await sleep(STOP_POLL_INTERVAL_MS);
- }
-
- console.warn(
- `Daemon did not exit within ${shutdownMs}ms — force killing.`,
- );
- if (!isWindows) {
- try {
- process.kill(pid, "SIGKILL");
- } catch {
- // already dead
- }
- }
- removePidFileIfMatches(pid, profile);
- console.log("Daemon stopped.");
-}
-
-export function daemonCommand(): Command {
- const cmd = new Command("daemon").description("Manage the Alook daemon");
-
- cmd
- .command("start")
- .description("Start the daemon")
- .option("--foreground", "Run in foreground")
- .option("--server <url>", "Server URL override")
- .action(async (opts, command) => {
- const parentOpts = command.parent?.parent?.opts() || {};
- const profile: string | undefined = parentOpts.profile;
- const serverUrl: string | undefined = opts.server || parentOpts.server;
-
- if (opts.foreground) {
- await startDaemon(profile, serverUrl);
- return;
- }
-
- await startInBackground(profile, serverUrl);
- });
-
- cmd
- .command("status")
- .description("Show daemon status")
- .action((_opts, command) => {
- const parentOpts = command.parent?.parent?.opts() || {};
- statusCommand(parentOpts.profile);
- });
-
- cmd
- .command("stop")
- .description("Stop the running daemon")
- .action(async (_opts, command) => {
- const parentOpts = command.parent?.parent?.opts() || {};
- await stopCommand(parentOpts.profile);
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/email.test.ts b/src/cli/commands/email.test.ts
deleted file mode 100644
index 594bfa14c..000000000
--- a/src/cli/commands/email.test.ts
+++ /dev/null
@@ -1,1239 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "fs";
-import { join } from "path";
-import PostalMime from "postal-mime";
-import { Command } from "commander";
-
-const { postMultipartMock, postJSONMock, getJSONMock, getTextMock, deleteJSONMock } = vi.hoisted(() => ({
- postMultipartMock: vi.fn(),
- postJSONMock: vi.fn(),
- getJSONMock: vi.fn(),
- getTextMock: vi.fn(),
- deleteJSONMock: vi.fn(),
-}));
-
-vi.mock("../lib/client.js", () => ({
- APIClient: class {
- postMultipart(...a: unknown[]) {
- return postMultipartMock(...a);
- }
- postJSON(...a: unknown[]) {
- return postJSONMock(...a);
- }
- getJSON(...a: unknown[]) {
- return getJSONMock(...a);
- }
- getText(...a: unknown[]) {
- return getTextMock(...a);
- }
- deleteJSON(...a: unknown[]) {
- return deleteJSONMock(...a);
- }
- },
-}));
-
-vi.mock("../lib/config.js", async (importActual) => ({
- ...(await importActual<typeof import("../lib/config.js")>()),
- loadCLIConfigForProfile: vi.fn(() => ({
- server_url: "http://localhost:3000",
- watched_workspaces: [
- { id: "w1", token: "tok", agent_ids: ["ag_1"] },
- ],
- })),
-}));
-
-import { emailCommand } from "./email.js";
-
-// Test the PostalMime parsing and file writing logic in isolation
-// (CLI commands themselves depend on network + config which we don't mock here)
-
-const TMP_DIR = "/tmp/alook-emails-test";
-
-describe("email pull output structure", () => {
- beforeEach(() => {
- mkdirSync(TMP_DIR, { recursive: true });
- });
-
- afterEach(() => {
- rmSync(TMP_DIR, { recursive: true, force: true });
- });
-
- it("creates metadata.json with correct fields", () => {
- const emailDir = join(TMP_DIR, "test-email-1");
- mkdirSync(emailDir, { recursive: true });
-
- const metadata = {
- id: "test-email-1",
- subject: "Test Subject",
- date: "2024-01-01T00:00:00Z",
- status: "unread",
- };
- writeFileSync(join(emailDir, "metadata.json"), JSON.stringify(metadata, null, 2));
-
- const written = JSON.parse(readFileSync(join(emailDir, "metadata.json"), "utf-8"));
- expect(written.id).toBe("test-email-1");
- expect(written.from).toBe("[email protected]");
- expect(written.to).toBe("[email protected]");
- expect(written.subject).toBe("Test Subject");
- expect(written.status).toBe("unread");
- expect(written.date).toBe("2024-01-01T00:00:00Z");
- });
-
- it("writes body.txt from parsed MIME text body", async () => {
- const rawMime = "From: [email protected]\r\nTo: [email protected]\r\nSubject: Hello\r\nContent-Type: text/plain\r\n\r\nHello world";
- const parsed = await new PostalMime().parse(rawMime);
-
- const emailDir = join(TMP_DIR, "test-email-2");
- mkdirSync(emailDir, { recursive: true });
-
- if (parsed.text) {
- writeFileSync(join(emailDir, "body.txt"), parsed.text);
- }
-
- expect(existsSync(join(emailDir, "body.txt"))).toBe(true);
- expect(readFileSync(join(emailDir, "body.txt"), "utf-8").trim()).toBe("Hello world");
- });
-
- it("writes body.html from parsed MIME HTML body", async () => {
- const rawMime = [
- "Subject: Hello",
- "Content-Type: text/html; charset=utf-8",
- "",
- "<p>Hello world</p>",
- ].join("\r\n");
- const parsed = await new PostalMime().parse(rawMime);
-
- const emailDir = join(TMP_DIR, "test-email-3");
- mkdirSync(emailDir, { recursive: true });
-
- if (parsed.html) {
- writeFileSync(join(emailDir, "body.html"), parsed.html);
- }
-
- expect(existsSync(join(emailDir, "body.html"))).toBe(true);
- expect(readFileSync(join(emailDir, "body.html"), "utf-8").trim()).toBe("<p>Hello world</p>");
- });
-
- it("extracts attachments with correct binary content", async () => {
- const boundary = "----=_Part_001";
- const rawMime = [
- "Subject: With attachment",
- `Content-Type: multipart/mixed; boundary="${boundary}"`,
- "",
- `--${boundary}`,
- "Content-Type: text/plain",
- "",
- "Body text",
- `--${boundary}`,
- "Content-Type: application/octet-stream",
- 'Content-Disposition: attachment; filename="report.bin"',
- "Content-Transfer-Encoding: base64",
- "",
- Buffer.from("binary content").toString("base64"),
- `--${boundary}--`,
- ].join("\r\n");
-
- const parsed = await new PostalMime().parse(rawMime);
- expect(parsed.attachments.length).toBeGreaterThan(0);
-
- const emailDir = join(TMP_DIR, "test-email-4");
- const attDir = join(emailDir, "attachments");
- mkdirSync(attDir, { recursive: true });
-
- for (const att of parsed.attachments) {
- const filename = att.filename || "attachment-0.bin";
- const content = att.content;
- let buf: Buffer;
- if (typeof content === "string") {
- buf = Buffer.from(content, "base64");
- } else if (content instanceof ArrayBuffer) {
- buf = Buffer.from(new Uint8Array(content));
- } else {
- buf = Buffer.from(content as Uint8Array);
- }
- writeFileSync(join(attDir, filename), buf);
- }
-
- const writtenFile = join(attDir, "report.bin");
- expect(existsSync(writtenFile)).toBe(true);
- expect(readFileSync(writtenFile).toString()).toBe("binary content");
- });
-
- it("handles attachments with missing filename", async () => {
- const boundary = "----=_Part_002";
- const rawMime = [
- "Subject: No filename",
- `Content-Type: multipart/mixed; boundary="${boundary}"`,
- "",
- `--${boundary}`,
- "Content-Type: text/plain",
- "",
- "Body",
- `--${boundary}`,
- "Content-Type: application/octet-stream",
- "Content-Transfer-Encoding: base64",
- "",
- Buffer.from("data").toString("base64"),
- `--${boundary}--`,
- ].join("\r\n");
-
- const parsed = await new PostalMime().parse(rawMime);
-
- const emailDir = join(TMP_DIR, "test-email-5");
- const attDir = join(emailDir, "attachments");
- mkdirSync(attDir, { recursive: true });
-
- for (let i = 0; i < parsed.attachments.length; i++) {
- const att = parsed.attachments[i];
- const filename = att.filename || `attachment-${i}.bin`;
- const content = att.content;
- let buf: Buffer;
- if (typeof content === "string") {
- buf = Buffer.from(content, "base64");
- } else if (content instanceof ArrayBuffer) {
- buf = Buffer.from(new Uint8Array(content));
- } else {
- buf = Buffer.from(content as Uint8Array);
- }
- writeFileSync(join(attDir, filename), buf);
- }
-
- // Should use fallback filename
- const files = require("fs").readdirSync(attDir);
- expect(files.length).toBeGreaterThan(0);
- expect(files.some((f: string) => f.startsWith("attachment-"))).toBe(true);
- });
-
- it("handles duplicate attachment filenames by prefixing with index", () => {
- const emailDir = join(TMP_DIR, "test-email-6");
- const attDir = join(emailDir, "attachments");
- mkdirSync(attDir, { recursive: true });
-
- const usedFilenames = new Set<string>();
- const attachments = [
- { filename: "report.pdf" },
- { filename: "report.pdf" },
- ];
-
- for (let i = 0; i < attachments.length; i++) {
- let filename = attachments[i].filename;
- if (usedFilenames.has(filename)) {
- filename = `${i}-${filename}`;
- }
- usedFilenames.add(filename);
- writeFileSync(join(attDir, filename), "content");
- }
-
- expect(existsSync(join(attDir, "report.pdf"))).toBe(true);
- expect(existsSync(join(attDir, "1-report.pdf"))).toBe(true);
- });
-
- it("does not clear existing email directories", () => {
- // Pre-create some content
- const existingDir = join(TMP_DIR, "existing-email");
- mkdirSync(existingDir, { recursive: true });
- writeFileSync(join(existingDir, "metadata.json"), "existing");
-
- // Create a new email directory
- const newDir = join(TMP_DIR, "new-email");
- mkdirSync(newDir, { recursive: true });
- writeFileSync(join(newDir, "metadata.json"), "new");
-
- // Existing should still be there
- expect(existsSync(join(existingDir, "metadata.json"))).toBe(true);
- expect(readFileSync(join(existingDir, "metadata.json"), "utf-8")).toBe("existing");
- });
-});
-
-describe("email status validation", () => {
- const VALID_STATUSES = ["unread", "read", "archived", "sent"];
-
- it("accepts valid status values", () => {
- for (const s of VALID_STATUSES) {
- expect(VALID_STATUSES.includes(s)).toBe(true);
- }
- });
-
- it("rejects invalid status values", () => {
- expect(VALID_STATUSES.includes("deleted")).toBe(false);
- expect(VALID_STATUSES.includes("pending")).toBe(false);
- expect(VALID_STATUSES.includes("")).toBe(false);
- });
-});
-
-describe("email send subcommand shape", () => {
- const cmd = emailCommand();
- const send = cmd.commands.find((c) => c.name() === "send")!;
-
- it("is registered", () => {
- expect(send).toBeDefined();
- });
-
- it("requires --to, --subject, --body-file; --agent_id is optional (env fallback)", () => {
- const opts = (send as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).not.toContain("--agent_id");
- expect(mandatory).toContain("--to");
- expect(mandatory).toContain("--subject");
- expect(mandatory).toContain("--body-file");
- });
-
- it("accepts --attachment, --workspace, and --from as optional", () => {
- const opts = (send as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const longs = opts.map((o) => o.long);
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(longs).toContain("--attachment");
- expect(longs).toContain("--workspace");
- expect(longs).toContain("--from");
- expect(mandatory).not.toContain("--attachment");
- expect(mandatory).not.toContain("--workspace");
- expect(mandatory).not.toContain("--from");
- });
-});
-
-describe("email send behavior", () => {
- const SEND_TMP = "/tmp/alook-email-send-test";
-
- async function runSend(args: string[]): Promise<{ out: string[]; err: string[]; exitCode: number | null }> {
- const out: string[] = [];
- const err: string[] = [];
- let exitCode: number | null = null;
- const logSpy = vi.spyOn(console, "log").mockImplementation((m: unknown) => {
- out.push(String(m));
- });
- const errSpy = vi.spyOn(console, "error").mockImplementation((m: unknown) => {
- err.push(String(m));
- });
- const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
- exitCode = code ?? 0;
- throw new Error("__exit__");
- }) as never);
- try {
- const program = new Command()
- .name("alook")
- .option("--server <url>", "Server URL")
- .option("--profile <name>", "Profile name");
- program.addCommand(emailCommand());
- await program.parseAsync(["email", "send", ...args], { from: "user" });
- } catch (e) {
- if (!(e instanceof Error) || e.message !== "__exit__") throw e;
- } finally {
- logSpy.mockRestore();
- errSpy.mockRestore();
- exitSpy.mockRestore();
- }
- return { out, err, exitCode };
- }
-
- beforeEach(() => {
- mkdirSync(SEND_TMP, { recursive: true });
- postMultipartMock.mockReset();
- postJSONMock.mockReset();
- });
-
- afterEach(() => {
- rmSync(SEND_TMP, { recursive: true, force: true });
- });
-
- it("uploads each attachment then sends", async () => {
- const bodyPath = join(SEND_TMP, "body.html");
- const att1 = join(SEND_TMP, "report.pdf");
- const att2 = join(SEND_TMP, "chart.png");
- writeFileSync(bodyPath, "<p>Hi</p>");
- writeFileSync(att1, Buffer.from("pdf-bytes"));
- writeFileSync(att2, Buffer.from("png-bytes"));
-
- postMultipartMock
- .mockResolvedValueOnce({ key: "emails/drafts/abc/report.pdf", filename: "report.pdf", size: 9, contentType: "application/pdf" })
- .mockResolvedValueOnce({ key: "emails/drafts/def/chart.png", filename: "chart.png", size: 9, contentType: "image/png" });
- postJSONMock.mockResolvedValueOnce({ id: "em_1", to_email: "[email protected]" });
-
- const { out, exitCode } = await runSend([
- "--agent_id", "ag_1",
- "--to", "[email protected]",
- "--subject", "Weekly report",
- "--body-file", bodyPath,
- "--attachment", att1,
- "--attachment", att2,
- ]);
-
- expect(exitCode).toBeNull();
- expect(postMultipartMock).toHaveBeenCalledTimes(2);
- expect(postMultipartMock.mock.calls[0][0]).toBe("/api/email/upload");
- expect(postMultipartMock.mock.calls[0][1]).toBeInstanceOf(FormData);
- const form1 = postMultipartMock.mock.calls[0][1] as FormData;
- const file1 = form1.get("file") as File;
- expect(file1).toBeInstanceOf(Blob);
- // Blob.type carries our guessed content-type
- expect(file1.type).toBe("application/pdf");
-
- expect(postJSONMock).toHaveBeenCalledTimes(1);
- expect(postJSONMock.mock.calls[0][0]).toBe("/api/email/send");
- const payload = postJSONMock.mock.calls[0][1] as {
- agentId: string;
- to: string;
- subject: string;
- htmlBody: string;
- attachments: Array<{ key: string; filename: string; contentType: string }>;
- };
- expect(payload.agentId).toBe("ag_1");
- expect(payload.to).toBe("[email protected]");
- expect(payload.subject).toBe("Weekly report");
- expect(payload.htmlBody).toBe("<p>Hi</p>");
- expect(payload.attachments).toHaveLength(2);
- expect(payload.attachments[0].key).toBe("emails/drafts/abc/report.pdf");
- expect(payload.attachments[1].key).toBe("emails/drafts/def/chart.png");
-
- expect(out.join("\n")).toContain("Sent email to [email protected]");
- });
-
- it("sends with empty attachments when none provided", async () => {
- const bodyPath = join(SEND_TMP, "body.html");
- writeFileSync(bodyPath, "<p>No attachments</p>");
- postJSONMock.mockResolvedValueOnce({ id: "em_2", to_email: "[email protected]" });
-
- const { exitCode } = await runSend([
- "--agent_id", "ag_1",
- "--to", "[email protected]",
- "--subject", "Hi",
- "--body-file", bodyPath,
- ]);
-
- expect(exitCode).toBeNull();
- expect(postMultipartMock).not.toHaveBeenCalled();
- const payload = postJSONMock.mock.calls[0][1] as { attachments: unknown[] };
- expect(payload.attachments).toEqual([]);
- });
-
- it("errors when body file does not exist", async () => {
- const { err, exitCode } = await runSend([
- "--agent_id", "ag_1",
- "--to", "[email protected]",
- "--subject", "Hi",
- "--body-file", join(SEND_TMP, "missing.html"),
- ]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("cannot read body file");
- expect(postMultipartMock).not.toHaveBeenCalled();
- expect(postJSONMock).not.toHaveBeenCalled();
- });
-
- it("passes --from to API payload when provided", async () => {
- const bodyPath = join(SEND_TMP, "body.html");
- writeFileSync(bodyPath, "<p>From custom</p>");
- postJSONMock.mockResolvedValueOnce({ id: "em_3", to_email: "[email protected]" });
-
- const { exitCode } = await runSend([
- "--agent_id", "ag_1",
- "--to", "[email protected]",
- "--subject", "Custom from",
- "--body-file", bodyPath,
- "--from", "[email protected]",
- ]);
-
- expect(exitCode).toBeNull();
- const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
- expect(payload.from).toBe("[email protected]");
- });
-
- it("omits from in payload when --from is not provided", async () => {
- const bodyPath = join(SEND_TMP, "body.html");
- writeFileSync(bodyPath, "<p>Default from</p>");
- postJSONMock.mockResolvedValueOnce({ id: "em_4", to_email: "[email protected]" });
-
- const { exitCode } = await runSend([
- "--agent_id", "ag_1",
- "--to", "[email protected]",
- "--subject", "Default",
- "--body-file", bodyPath,
- ]);
-
- expect(exitCode).toBeNull();
- const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
- expect(payload.from).toBeUndefined();
- });
-
- it("errors when body file is empty", async () => {
- const bodyPath = join(SEND_TMP, "empty.html");
- writeFileSync(bodyPath, "");
-
- const { err, exitCode } = await runSend([
- "--agent_id", "ag_1",
- "--to", "[email protected]",
- "--subject", "Hi",
- "--body-file", bodyPath,
- ]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("is empty");
- expect(postMultipartMock).not.toHaveBeenCalled();
- expect(postJSONMock).not.toHaveBeenCalled();
- });
-});
-
-// --- Forward tests ---
-
-async function runForward(args: string[]): Promise<{ out: string[]; err: string[]; exitCode: number | null }> {
- const out: string[] = [];
- const err: string[] = [];
- let exitCode: number | null = null;
- const logSpy = vi.spyOn(console, "log").mockImplementation((m: unknown) => {
- out.push(String(m));
- });
- const errSpy = vi.spyOn(console, "error").mockImplementation((m: unknown) => {
- err.push(String(m));
- });
- const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
- exitCode = code ?? 0;
- throw new Error("__exit__");
- }) as never);
- try {
- const program = new Command()
- .name("alook")
- .option("--server <url>", "Server URL")
- .option("--profile <name>", "Profile name");
- program.addCommand(emailCommand());
- await program.parseAsync(["email", "forward", ...args], { from: "user" });
- } catch (e) {
- if (!(e instanceof Error) || e.message !== "__exit__") throw e;
- } finally {
- logSpy.mockRestore();
- errSpy.mockRestore();
- exitSpy.mockRestore();
- }
- return { out, err, exitCode };
-}
-
-async function runPull(args: string[]): Promise<{ out: string[]; err: string[]; exitCode: number | null }> {
- const out: string[] = [];
- const err: string[] = [];
- let exitCode: number | null = null;
- const logSpy = vi.spyOn(console, "log").mockImplementation((m: unknown) => {
- out.push(String(m));
- });
- const errSpy = vi.spyOn(console, "error").mockImplementation((m: unknown) => {
- err.push(String(m));
- });
- const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
- exitCode = code ?? 0;
- throw new Error("__exit__");
- }) as never);
- try {
- const program = new Command()
- .name("alook")
- .option("--server <url>", "Server URL")
- .option("--profile <name>", "Profile name");
- program.addCommand(emailCommand());
- await program.parseAsync(["email", "pull", ...args], { from: "user" });
- } catch (e) {
- if (!(e instanceof Error) || e.message !== "__exit__") throw e;
- } finally {
- logSpy.mockRestore();
- errSpy.mockRestore();
- exitSpy.mockRestore();
- }
- return { out, err, exitCode };
-}
-
-const FORWARD_TMP = "/tmp/alook-email-forward-test";
-
-function makeOriginalEmail(overrides: Partial<Record<string, unknown>> = {}) {
- return {
- id: "em_orig",
- agent_id: "ag_1",
- from_email: "[email protected]",
- to_email: "[email protected]",
- subject: "Original Subject",
- r2_key: "emails/em_orig",
- is_whitelisted: true,
- forwarded: false,
- message_id: "<[email protected]>",
- in_reply_to: "",
- references: "",
- html_body: "<p>Hello</p>",
- attachments: [],
- status: "read",
- created_at: "2026-04-20T10:00:00Z",
- ...overrides,
- };
-}
-
-function makeRawMime(opts: { html?: string; text?: string; attachment?: boolean } = {}) {
- if (opts.attachment) {
- const boundary = "----=_Part_fwd";
- const parts = [];
- if (opts.html) {
- parts.push(
- `--${boundary}\r\nContent-Type: text/html; charset=utf-8\r\n\r\n${opts.html}`,
- );
- } else if (opts.text) {
- parts.push(
- `--${boundary}\r\nContent-Type: text/plain\r\n\r\n${opts.text}`,
- );
- }
- parts.push(
- `--${boundary}\r\nContent-Type: application/pdf\r\nContent-Disposition: attachment; filename="original.pdf"\r\nContent-Transfer-Encoding: base64\r\n\r\n${Buffer.from("pdf-content").toString("base64")}`,
- );
- return `From: [email protected]\r\nTo: [email protected]\r\nSubject: Original Subject\r\nContent-Type: multipart/mixed; boundary="${boundary}"\r\n\r\n${parts.join("\r\n")}\r\n--${boundary}--`;
- }
- if (opts.html) {
- return `From: [email protected]\r\nTo: [email protected]\r\nSubject: Original Subject\r\nContent-Type: text/html; charset=utf-8\r\n\r\n${opts.html}`;
- }
- return `From: [email protected]\r\nTo: [email protected]\r\nSubject: Original Subject\r\nContent-Type: text/plain\r\n\r\n${opts.text || "Hello world"}`;
-}
-
-describe("email forward subcommand shape", () => {
- const cmd = emailCommand();
- const forward = cmd.commands.find((c) => c.name() === "forward")!;
-
- it("is registered", () => {
- expect(forward).toBeDefined();
- });
-
- it("requires --email_id, --to; --agent_id is optional (env fallback)", () => {
- const opts = (forward as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).not.toContain("--agent_id");
- expect(mandatory).toContain("--email_id");
- expect(mandatory).toContain("--to");
- });
-
- it("accepts --from, --note, --attachment, --workspace as optional", () => {
- const opts = (forward as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const longs = opts.map((o) => o.long);
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(longs).toContain("--from");
- expect(longs).toContain("--note");
- expect(longs).toContain("--attachment");
- expect(longs).toContain("--workspace");
- expect(mandatory).not.toContain("--from");
- expect(mandatory).not.toContain("--note");
- expect(mandatory).not.toContain("--attachment");
- expect(mandatory).not.toContain("--workspace");
- });
-});
-
-describe("email forward behavior", () => {
- beforeEach(() => {
- mkdirSync(FORWARD_TMP, { recursive: true });
- postMultipartMock.mockReset();
- postJSONMock.mockReset();
- getJSONMock.mockReset();
- getTextMock.mockReset();
- });
-
- afterEach(() => {
- rmSync(FORWARD_TMP, { recursive: true, force: true });
- });
-
- it("fetches original email, parses MIME, re-uploads attachments, and sends", async () => {
- getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
- getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Hello</p>", attachment: true }));
- postMultipartMock.mockResolvedValueOnce({
- key: "emails/drafts/x/original.pdf",
- filename: "original.pdf",
- size: 11,
- contentType: "application/pdf",
- });
- postJSONMock.mockResolvedValueOnce({ id: "em_fwd1", to_email: "[email protected]" });
-
- const { out, exitCode } = await runForward([
- "--agent_id", "ag_1",
- "--email_id", "em_orig",
- "--to", "[email protected]",
- ]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/email/em_orig");
- expect(getTextMock).toHaveBeenCalledWith("/api/email/em_orig/raw");
- expect(postMultipartMock).toHaveBeenCalledTimes(1);
- expect(postJSONMock).toHaveBeenCalledTimes(1);
-
- const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
- expect(payload.subject).toBe("Fwd: Original Subject");
- expect((payload.htmlBody as string)).toContain("---------- Forwarded message ----------");
- expect((payload.htmlBody as string)).toContain("[email protected]");
- expect((payload.attachments as unknown[]).length).toBe(1);
- expect(out.join("\n")).toContain("Forwarded email to [email protected]");
- });
-
- it("prepends note when --note is provided", async () => {
- getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
- getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Content</p>" }));
- postJSONMock.mockResolvedValueOnce({ id: "em_fwd2", to_email: "[email protected]" });
-
- const { exitCode } = await runForward([
- "--agent_id", "ag_1",
- "--email_id", "em_orig",
- "--to", "[email protected]",
- "--note", "FYI see below",
- ]);
-
- expect(exitCode).toBeNull();
- const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
- const body = payload.htmlBody as string;
- expect(body).toMatch(/^<p>FYI see below<\/p>/);
- expect(body).toContain("---------- Forwarded message ----------");
- });
-
- it("has no extra prefix without --note", async () => {
- getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
- getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Content</p>" }));
- postJSONMock.mockResolvedValueOnce({ id: "em_fwd3", to_email: "[email protected]" });
-
- const { exitCode } = await runForward([
- "--agent_id", "ag_1",
- "--email_id", "em_orig",
- "--to", "[email protected]",
- ]);
-
- expect(exitCode).toBeNull();
- const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
- const body = payload.htmlBody as string;
- expect(body).not.toMatch(/^<p>/);
- expect(body).toMatch(/^<br><br>---------- Forwarded message ----------/);
- });
-
- it("handles plain-text-only original email", async () => {
- getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
- getTextMock.mockResolvedValueOnce(makeRawMime({ text: "Plain text body" }));
- postJSONMock.mockResolvedValueOnce({ id: "em_fwd4", to_email: "[email protected]" });
-
- const { exitCode } = await runForward([
- "--agent_id", "ag_1",
- "--email_id", "em_orig",
- "--to", "[email protected]",
- ]);
-
- expect(exitCode).toBeNull();
- const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
- const body = payload.htmlBody as string;
- expect(body).toContain("<pre>Plain text body");
- expect(body).toContain("</pre>");
- });
-
- it("preserves subject prefix — no double Fwd:", async () => {
- getJSONMock.mockResolvedValueOnce(makeOriginalEmail({ subject: "Fwd: Already forwarded" }));
- getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Hi</p>" }));
- postJSONMock.mockResolvedValueOnce({ id: "em_fwd5", to_email: "[email protected]" });
-
- const { exitCode } = await runForward([
- "--agent_id", "ag_1",
- "--email_id", "em_orig",
- "--to", "[email protected]",
- ]);
-
- expect(exitCode).toBeNull();
- const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
- expect(payload.subject).toBe("Fwd: Already forwarded");
- });
-
- it("passes --from to send payload when provided", async () => {
- getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
- getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Hi</p>" }));
- postJSONMock.mockResolvedValueOnce({ id: "em_fwd6", to_email: "[email protected]" });
-
- const { exitCode } = await runForward([
- "--agent_id", "ag_1",
- "--email_id", "em_orig",
- "--to", "[email protected]",
- "--from", "[email protected]",
- ]);
-
- expect(exitCode).toBeNull();
- const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
- expect(payload.from).toBe("[email protected]");
- });
-
- it("adds extra --attachment files alongside original attachments", async () => {
- getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
- getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Hi</p>", attachment: true }));
- postMultipartMock
- .mockResolvedValueOnce({ key: "emails/drafts/x/original.pdf", filename: "original.pdf", size: 11, contentType: "application/pdf" })
- .mockResolvedValueOnce({ key: "emails/drafts/y/extra.pdf", filename: "extra.pdf", size: 5, contentType: "application/pdf" });
- postJSONMock.mockResolvedValueOnce({ id: "em_fwd7", to_email: "[email protected]" });
-
- const extraPath = join(FORWARD_TMP, "extra.pdf");
- writeFileSync(extraPath, "extra");
-
- const { exitCode } = await runForward([
- "--agent_id", "ag_1",
- "--email_id", "em_orig",
- "--to", "[email protected]",
- "--attachment", extraPath,
- ]);
-
- expect(exitCode).toBeNull();
- expect(postMultipartMock).toHaveBeenCalledTimes(2);
- const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
- expect((payload.attachments as unknown[]).length).toBe(2);
- });
-
- it("errors when original email not found (404)", async () => {
- getJSONMock.mockRejectedValueOnce(new Error("HTTP 404: not found"));
-
- const { err, exitCode } = await runForward([
- "--agent_id", "ag_1",
- "--email_id", "em_missing",
- "--to", "[email protected]",
- ]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("not found");
- });
-
- it("errors when raw MIME not available (404)", async () => {
- getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
- getTextMock.mockRejectedValueOnce(new Error("HTTP 404: not found"));
-
- const { err, exitCode } = await runForward([
- "--agent_id", "ag_1",
- "--email_id", "em_orig",
- "--to", "[email protected]",
- ]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("raw email body not available");
- });
-});
-
-describe("email pull with --email_id", () => {
- beforeEach(() => {
- getJSONMock.mockReset();
- getTextMock.mockReset();
- });
-
- it("registers --email_id option on pull command", () => {
- const cmd = emailCommand();
- const pullCmd = cmd.commands.find((c) => c.name() === "pull")!;
- const optNames = pullCmd.options.map((o) => o.long);
- expect(optNames).toContain("--email_id");
- });
-
- it("calls single-email endpoint when --email_id is provided", async () => {
- getJSONMock.mockResolvedValueOnce({
- id: "em_123",
- agent_id: "ag_1",
- from_email: "[email protected]",
- to_email: "[email protected]",
- subject: "Test",
- r2_key: "emails/em_123",
- is_whitelisted: true,
- forwarded: false,
- message_id: "",
- in_reply_to: "",
- references: "",
- html_body: "",
- attachments: [],
- status: "unread",
- created_at: "2026-05-26T00:00:00Z",
- });
- getTextMock.mockResolvedValueOnce("From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\nContent-Type: text/plain\r\n\r\nHello");
-
- const { exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_123"]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/email/em_123");
- });
-
- it("errors when --email_id combined with --status", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_1", "--status", "unread"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("--email_id cannot be combined");
- });
-
- it("errors when --email_id combined with --folder", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_1", "--folder", "sent"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("--email_id cannot be combined");
- });
-
- it("errors when --email_id combined with --limit", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_1", "--limit", "5"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("--email_id cannot be combined");
- });
-
- it("errors when --email_id combined with --offset", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_1", "--offset", "10"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("--email_id cannot be combined");
- });
-
- it("handles not-found error gracefully", async () => {
- getJSONMock.mockRejectedValueOnce(new Error("HTTP 404: email not found"));
-
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_nonexistent"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("404");
- });
-
- it("does not use --email_id endpoint when flag is absent (backward compatible)", async () => {
- getJSONMock.mockResolvedValueOnce([]);
-
- const { exitCode } = await runPull(["--agent_id", "ag_1", "--status", "unread"]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&status=unread");
- });
-});
-
-describe("email pull with --folder", () => {
- beforeEach(() => {
- getJSONMock.mockReset();
- getTextMock.mockReset();
- });
-
- it("passes folder param to API when --folder sent", async () => {
- getJSONMock.mockResolvedValueOnce([]);
-
- const { exitCode } = await runPull(["--agent_id", "ag_1", "--folder", "sent"]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&folder=sent");
- });
-
- it("rejects invalid --folder value", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--folder", "invalid"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("invalid folder");
- expect(err.join("\n")).toContain("inbox, sent, untrust");
- });
-
- it("does not include folder param without --folder (preserves default)", async () => {
- getJSONMock.mockResolvedValueOnce([]);
-
- const { exitCode } = await runPull(["--agent_id", "ag_1"]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1");
- });
-});
-
-describe("email pull with --limit and --offset", () => {
- beforeEach(() => {
- getJSONMock.mockReset();
- getTextMock.mockReset();
- });
-
- it("passes limit param to API when --limit 10", async () => {
- getJSONMock.mockResolvedValueOnce([]);
-
- const { exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "10"]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&limit=10");
- });
-
- it("passes both limit and offset to API", async () => {
- getJSONMock.mockResolvedValueOnce([]);
-
- const { exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "10", "--offset", "20"]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&limit=10&offset=20");
- });
-
- it("rejects --limit 0", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "0"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("--limit must be an integer between 1 and 100");
- });
-
- it("rejects negative --limit", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "-5"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("--limit must be an integer between 1 and 100");
- });
-
- it("rejects non-numeric --limit", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "abc"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("--limit must be an integer between 1 and 100");
- });
-
- it("rejects --limit over 100", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "200"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("--limit must be an integer between 1 and 100");
- });
-
- it("rejects negative --offset", async () => {
- const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--offset", "-1"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("--offset must be a non-negative integer");
- });
-
- it("does not include limit/offset params when not specified", async () => {
- getJSONMock.mockResolvedValueOnce([]);
-
- const { exitCode } = await runPull(["--agent_id", "ag_1"]);
-
- expect(exitCode).toBeNull();
- const calledUrl = getJSONMock.mock.calls[0][0] as string;
- expect(calledUrl).not.toContain("limit");
- expect(calledUrl).not.toContain("offset");
- });
-
- it("combines --limit with --folder and --status", async () => {
- getJSONMock.mockResolvedValueOnce([]);
-
- const { exitCode } = await runPull(["--agent_id", "ag_1", "--status", "unread", "--folder", "sent", "--limit", "5"]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&status=unread&folder=sent&limit=5");
- });
-});
-
-// --- Whitelist tests ---
-
-async function runWhitelist(args: string[]): Promise<{ out: string[]; err: string[]; exitCode: number | null }> {
- const out: string[] = [];
- const err: string[] = [];
- let exitCode: number | null = null;
- const logSpy = vi.spyOn(console, "log").mockImplementation((m: unknown) => {
- out.push(String(m));
- });
- const errSpy = vi.spyOn(console, "error").mockImplementation((m: unknown) => {
- err.push(String(m));
- });
- const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
- exitCode = code ?? 0;
- throw new Error("__exit__");
- }) as never);
- try {
- const program = new Command()
- .name("alook")
- .option("--server <url>", "Server URL")
- .option("--profile <name>", "Profile name");
- program.addCommand(emailCommand());
- await program.parseAsync(["email", "whitelist", ...args], { from: "user" });
- } catch (e) {
- if (!(e instanceof Error) || e.message !== "__exit__") throw e;
- } finally {
- logSpy.mockRestore();
- errSpy.mockRestore();
- exitSpy.mockRestore();
- }
- return { out, err, exitCode };
-}
-
-describe("whitelist command registration", () => {
- const cmd = emailCommand();
- const whitelistCmd = cmd.commands.find((c) => c.name() === "whitelist")!;
-
- it("whitelist subcommand group exists under email", () => {
- expect(whitelistCmd).toBeDefined();
- expect(whitelistCmd.description()).toBe("Manage email whitelist (allowed senders)");
- });
-
- it("list, add, delete subcommands exist under whitelist", () => {
- const subNames = whitelistCmd.commands.map((c) => c.name());
- expect(subNames).toContain("list");
- expect(subNames).toContain("add");
- expect(subNames).toContain("delete");
- });
-
- it("--agent_id is optional on all three subcommands (env fallback)", () => {
- for (const name of ["list", "add", "delete"]) {
- const sub = whitelistCmd.commands.find((c) => c.name() === name)!;
- const opts = (sub as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- const longs = opts.map((o) => o.long);
- expect(longs).toContain("--agent_id");
- expect(mandatory).not.toContain("--agent_id");
- }
- });
-
- it("--workspace is optional on all three subcommands", () => {
- for (const name of ["list", "add", "delete"]) {
- const sub = whitelistCmd.commands.find((c) => c.name() === name)!;
- const opts = (sub as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const longs = opts.map((o) => o.long);
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(longs).toContain("--workspace");
- expect(mandatory).not.toContain("--workspace");
- }
- });
-
- it("--json is optional on list only", () => {
- const listCmd = whitelistCmd.commands.find((c) => c.name() === "list")!;
- const listOpts = (listCmd as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- expect(listOpts.map((o) => o.long)).toContain("--json");
-
- for (const name of ["add", "delete"]) {
- const sub = whitelistCmd.commands.find((c) => c.name() === name)!;
- const opts = (sub as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- expect(opts.map((o) => o.long)).not.toContain("--json");
- }
- });
-});
-
-describe("whitelist list behavior", () => {
- beforeEach(() => {
- getJSONMock.mockReset();
- });
-
- it("returns table output with entries", async () => {
- getJSONMock.mockResolvedValueOnce([
- { id: "wl_abc123", email: "[email protected]", created_at: "2026-04-20T10:00:00Z" },
- { id: "wl_def456", email: "[email protected]", created_at: "2026-04-21T14:30:00Z" },
- ]);
-
- const { out, exitCode } = await runWhitelist(["list", "--agent_id", "ag_1"]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist");
- const output = out.join("\n");
- expect(output).toContain("ID");
- expect(output).toContain("EMAIL");
- expect(output).toContain("CREATED AT");
- expect(output).toContain("[email protected]");
- expect(output).toContain("[email protected]");
- });
-
- it("returns JSON output with --json", async () => {
- const entries = [
- { id: "wl_abc123", email: "[email protected]", created_at: "2026-04-20T10:00:00Z" },
- ];
- getJSONMock.mockResolvedValueOnce(entries);
-
- const { out, exitCode } = await runWhitelist(["list", "--agent_id", "ag_1", "--json"]);
-
- expect(exitCode).toBeNull();
- const parsed = JSON.parse(out.join("\n"));
- expect(parsed).toEqual(entries);
- });
-
- it("prints 'No whitelisted emails.' when empty", async () => {
- getJSONMock.mockResolvedValueOnce([]);
-
- const { out, exitCode } = await runWhitelist(["list", "--agent_id", "ag_1"]);
-
- expect(exitCode).toBeNull();
- expect(out.join("\n")).toContain("No whitelisted emails.");
- });
-
- it("exits 1 on API error", async () => {
- getJSONMock.mockRejectedValueOnce(new Error("HTTP 500: Internal Server Error"));
-
- const { err, exitCode } = await runWhitelist(["list", "--agent_id", "ag_1"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("HTTP 500");
- });
-});
-
-describe("whitelist add behavior", () => {
- beforeEach(() => {
- postJSONMock.mockReset();
- });
-
- it("posts email and prints confirmation", async () => {
- postJSONMock.mockResolvedValueOnce({ id: "wl_new1", email: "[email protected]", created_at: "2026-04-22T00:00:00Z" });
-
- const { out, exitCode } = await runWhitelist(["add", "--agent_id", "ag_1", "[email protected]"]);
-
- expect(exitCode).toBeNull();
- expect(postJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist", { email: "[email protected]" });
- expect(out.join("\n")).toContain("Added [email protected] to whitelist (id: wl_new1)");
- });
-
- it("normalizes email to lowercase before sending", async () => {
- postJSONMock.mockResolvedValueOnce({ id: "wl_new2", email: "[email protected]", created_at: "2026-04-22T00:00:00Z" });
-
- const { exitCode } = await runWhitelist(["add", "--agent_id", "ag_1", "[email protected]"]);
-
- expect(exitCode).toBeNull();
- expect(postJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist", { email: "[email protected]" });
- });
-
- it("exits 1 with message on 409 duplicate", async () => {
- postJSONMock.mockRejectedValueOnce(new Error("HTTP 409: already exists"));
-
- const { err, exitCode } = await runWhitelist(["add", "--agent_id", "ag_1", "[email protected]"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("[email protected] is already whitelisted");
- });
-
- it("exits 1 with message on 404 agent not found", async () => {
- postJSONMock.mockRejectedValueOnce(new Error("HTTP 404: agent not found"));
-
- const { err, exitCode } = await runWhitelist(["add", "--agent_id", "ag_999", "[email protected]"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("404");
- });
-
- it("exits 1 with message on invalid email format (400 from API)", async () => {
- postJSONMock.mockRejectedValueOnce(new Error("HTTP 400: invalid email format"));
-
- const { err, exitCode } = await runWhitelist(["add", "--agent_id", "ag_1", "not-an-email"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("400");
- });
-});
-
-describe("whitelist delete behavior", () => {
- beforeEach(() => {
- getJSONMock.mockReset();
- deleteJSONMock.mockReset();
- });
-
- it("fetches list, finds entry, sends DELETE with correct whitelistId, prints confirmation", async () => {
- getJSONMock.mockResolvedValueOnce([
- { id: "wl_abc123", email: "[email protected]", created_at: "2026-04-20T10:00:00Z" },
- { id: "wl_def456", email: "[email protected]", created_at: "2026-04-21T14:30:00Z" },
- ]);
- deleteJSONMock.mockResolvedValueOnce(undefined);
-
- const { out, exitCode } = await runWhitelist(["delete", "--agent_id", "ag_1", "[email protected]"]);
-
- expect(exitCode).toBeNull();
- expect(getJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist");
- expect(deleteJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist/wl_abc123");
- expect(out.join("\n")).toContain("Removed [email protected] from whitelist");
- });
-
- it("exits 1 with message when email not in whitelist", async () => {
- getJSONMock.mockResolvedValueOnce([
- { id: "wl_abc123", email: "[email protected]", created_at: "2026-04-20T10:00:00Z" },
- ]);
-
- const { err, exitCode } = await runWhitelist(["delete", "--agent_id", "ag_1", "[email protected]"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("[email protected] is not in the whitelist");
- });
-
- it("exits 1 on API error", async () => {
- getJSONMock.mockRejectedValueOnce(new Error("HTTP 500: Internal Server Error"));
-
- const { err, exitCode } = await runWhitelist(["delete", "--agent_id", "ag_1", "[email protected]"]);
-
- expect(exitCode).toBe(1);
- expect(err.join("\n")).toContain("HTTP 500");
- });
-});
diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.ts
deleted file mode 100644
index 641aaabdb..000000000
--- a/src/cli/commands/email.ts
+++ /dev/null
@@ -1,567 +0,0 @@
-import { Command } from "commander";
-import { writeFileSync, mkdirSync, readFileSync } from "fs";
-import { join } from "path";
-import PostalMime from "postal-mime";
-import { APIClient } from "../lib/client.js";
-import { printJSON, printTable } from "../lib/output.js";
-import { tempDir } from "../lib/platform.js";
-import { createLogger } from "../lib/logger.js";
-import { resolveAgentId, collectRepeated } from "../lib/flags.js";
-import { resolveClientOpts } from "../lib/resolve-client.js";
-import { contentToBuffer, uploadFile } from "../lib/file-utils.js";
-import type { UploadedFile } from "../lib/file-utils.js";
-import { gatherContextEnvVars } from "../lib/context-env.js";
-
-const log = createLogger({ module: "email" });
-
-interface EmailResponse {
- id: string;
- agent_id: string;
- from_email: string;
- to_email: string;
- subject: string;
- r2_key: string;
- is_whitelisted: boolean;
- forwarded: boolean;
- message_id: string;
- in_reply_to: string;
- references: string;
- html_body: string;
- attachments: unknown[];
- status: string;
- created_at: string;
-}
-
-const VALID_STATUSES = ["unread", "read", "archived", "sent"];
-const VALID_FOLDERS = ["inbox", "sent", "untrust"];
-const EMAIL_BASE = tempDir("alook-emails");
-
-interface SendResponse {
- id: string;
- to_email: string;
-}
-
-interface WhitelistEntry {
- id: string;
- email: string;
- created_at: string;
-}
-
-
-export function emailCommand(): Command {
- const cmd = new Command("email").description("Manage agent emails");
-
- cmd
- .command("pull")
- .description("Download and parse emails to /tmp/alook-emails/{workspaceId}/{agentId}/")
- .option("--agent_id <id>", "Agent ID")
- .option("--email_id <id>", "Fetch a single email by ID (mutually exclusive with --status/--folder/--limit/--offset)")
- .option("--status <status>", "Filter by status (unread, read, archived)")
- .option("--folder <folder>", "Email folder (inbox, sent, untrust)")
- .option("--limit <n>", "Maximum number of emails to download")
- .option("--offset <n>", "Number of emails to skip")
- .option("--workspace <id>", "Workspace ID")
- .option("--json", "Output as JSON instead of files")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { workspace: opts.workspace, agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- if (opts.email_id && (opts.status || opts.folder || opts.limit || opts.offset)) {
- console.error("Error: --email_id cannot be combined with --status, --folder, --limit, or --offset");
- process.exit(1);
- }
-
- if (opts.status && !VALID_STATUSES.includes(opts.status)) {
- console.error(
- `Error: invalid status "${opts.status}", must be one of: ${VALID_STATUSES.join(", ")}`,
- );
- process.exit(1);
- }
-
- if (opts.folder && !VALID_FOLDERS.includes(opts.folder)) {
- console.error(
- `Error: invalid folder "${opts.folder}", must be one of: ${VALID_FOLDERS.join(", ")}`,
- );
- process.exit(1);
- }
-
- if (opts.limit != null) {
- const n = parseInt(opts.limit, 10);
- if (isNaN(n) || n < 1 || n > 100) {
- console.error(`Error: --limit must be an integer between 1 and 100`);
- process.exit(1);
- }
- }
-
- if (opts.offset != null) {
- const n = parseInt(opts.offset, 10);
- if (isNaN(n) || n < 0) {
- console.error(`Error: --offset must be a non-negative integer`);
- process.exit(1);
- }
- }
-
- const emailDir_base = join(EMAIL_BASE, workspaceId, agentId);
-
- try {
- let emails: EmailResponse[];
- if (opts.email_id) {
- const single = await client.getJSON<EmailResponse>(`/api/email/${opts.email_id}`);
- emails = [single];
- } else {
- let query = `/api/email?agentId=${agentId}`;
- if (opts.status) query += `&status=${opts.status}`;
- if (opts.folder) query += `&folder=${opts.folder}`;
- if (opts.limit) query += `&limit=${opts.limit}`;
- if (opts.offset) query += `&offset=${opts.offset}`;
- emails = await client.getJSON<EmailResponse[]>(query);
- }
-
- if (!emails.length) {
- console.log("No emails found.");
- return;
- }
-
- if (opts.json) {
- printJSON(emails);
- return;
- }
-
- mkdirSync(emailDir_base, { recursive: true });
-
- const downloadedPaths: string[] = [];
-
- for (const email of emails) {
- const emailDir = join(emailDir_base, email.id);
- mkdirSync(emailDir, { recursive: true });
-
- // Write metadata
- const metadata = {
- id: email.id,
- from: email.from_email,
- to: email.to_email,
- subject: email.subject,
- date: email.created_at,
- status: email.status,
- message_id: email.message_id || "",
- in_reply_to: email.in_reply_to || "",
- references: email.references || "",
- };
- const metadataPath = join(emailDir, "metadata.json");
- writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));
- downloadedPaths.push(metadataPath);
-
- // Fetch and parse raw MIME
- let rawMime: string;
- try {
- rawMime = await client.getText(`/api/email/${email.id}/raw`);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (msg.includes("404")) {
- log.warn(`email body not available for ${email.id}, skipping`);
- continue;
- }
- throw err;
- }
-
- const parsed = await new PostalMime().parse(rawMime);
-
- if (parsed.text) {
- const bodyPath = join(emailDir, "body.txt");
- writeFileSync(bodyPath, parsed.text);
- downloadedPaths.push(bodyPath);
- }
-
- if (parsed.html) {
- const htmlPath = join(emailDir, "body.html");
- writeFileSync(htmlPath, parsed.html);
- downloadedPaths.push(htmlPath);
- }
-
- if (parsed.attachments && parsed.attachments.length > 0) {
- const attDir = join(emailDir, "attachments");
- mkdirSync(attDir, { recursive: true });
- const usedFilenames = new Set<string>();
-
- for (let i = 0; i < parsed.attachments.length; i++) {
- const att = parsed.attachments[i];
- let filename = att.filename || `attachment-${i}.bin`;
- if (usedFilenames.has(filename)) {
- filename = `${i}-${filename}`;
- }
- usedFilenames.add(filename);
- const attPath = join(attDir, filename);
- writeFileSync(attPath, contentToBuffer(att.content));
- downloadedPaths.push(attPath);
- }
- }
- }
-
- console.log(
- `Downloaded ${emails.length} email${emails.length === 1 ? "" : "s"} to ${emailDir_base}/`,
- );
- for (const p of downloadedPaths) {
- console.log(` ${p}`);
- }
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("set")
- .description("Update email status")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--email_id <id>", "Email ID")
- .requiredOption("--status <status>", "New status (unread, read, archived)")
- .option("--workspace <id>", "Workspace ID")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { workspace: opts.workspace, agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- if (!VALID_STATUSES.includes(opts.status)) {
- console.error(
- `Error: invalid status "${opts.status}", must be one of: ${VALID_STATUSES.join(", ")}`,
- );
- process.exit(1);
- }
-
- try {
- await client.patchJSON(`/api/email/${opts.email_id}`, {
- status: opts.status,
- });
- console.log(`Email ${opts.email_id} status set to ${opts.status}`);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("send")
- .description("Send an email from the agent")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--to <addr>", "Recipient email address")
- .requiredOption("--subject <s>", "Subject line")
- .requiredOption("--body-file <path>", "Path to HTML body file")
- .option("--from <addr>", "Send from a specific email address (custom mailbox)")
- .option("--in-reply-to <emailId>", "Email ID to reply to (sets threading headers)")
- .option(
- "--attachment <path>",
- "Path to a file to attach (repeatable)",
- collectRepeated,
- [] as string[],
- )
- .option("--workspace <id>", "Workspace ID")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, {
- workspace: opts.workspace,
- agentId,
- });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- let htmlBody: string;
- try {
- htmlBody = readFileSync(opts.bodyFile, "utf-8");
- } catch (err) {
- console.error(
- `Error: cannot read body file "${opts.bodyFile}": ${err instanceof Error ? err.message : err}`,
- );
- process.exit(1);
- }
- if (!htmlBody) {
- console.error(`Error: body file "${opts.bodyFile}" is empty`);
- process.exit(1);
- }
-
- const attachmentPaths: string[] = opts.attachment ?? [];
- const attachments: UploadedFile[] = [];
-
- try {
- for (const filePath of attachmentPaths) {
- attachments.push(await uploadFile(client, filePath, "/api/email/upload"));
- }
-
- // Build threading context if replying
- let inReplyTo: string | undefined;
- let references: string | undefined;
- if (opts.inReplyTo) {
- try {
- const parentEmail = await client.getJSON<EmailResponse>(`/api/email/${opts.inReplyTo}`);
- if (parentEmail.message_id) {
- inReplyTo = parentEmail.message_id;
- references = [parentEmail.references, parentEmail.message_id].filter(Boolean).join(" ").trim() || undefined;
- }
- } catch {
- log.warn(`could not fetch parent email ${opts.inReplyTo}, sending without threading`);
- }
- }
-
- const ctx = gatherContextEnvVars();
- const res = await client.postJSON<SendResponse>("/api/email/send", {
- agentId,
- to: opts.to,
- subject: opts.subject,
- htmlBody,
- attachments,
- ...(inReplyTo ? { inReplyTo, references } : {}),
- ...(opts.from ? { from: opts.from } : {}),
- ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),
- ...(ctx.traceId ? { traceId: ctx.traceId } : {}),
- ...(ctx.sourceTaskId ? { sourceTaskId: ctx.sourceTaskId } : {}),
- });
- console.log(`Sent email to ${res.to_email} (id: ${res.id})`);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("forward")
- .description("Forward an email to a new recipient")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--email_id <id>", "Source email ID to forward")
- .requiredOption("--to <addr>", "Recipient email address")
- .option("--from <addr>", "Send from a specific email address (custom mailbox)")
- .option("--note <text>", "Text to prepend above the forwarded message")
- .option(
- "--attachment <path>",
- "Extra file to attach (repeatable)",
- collectRepeated,
- [] as string[],
- )
- .option("--workspace <id>", "Workspace ID")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, {
- workspace: opts.workspace,
- agentId,
- });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- try {
- // 1. Fetch original email metadata
- let original: EmailResponse;
- try {
- original = await client.getJSON<EmailResponse>(`/api/email/${opts.email_id}`);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (msg.includes("404")) {
- console.error(`Error: email ${opts.email_id} not found`);
- process.exit(1);
- }
- throw err;
- }
-
- // 2. Fetch raw MIME
- let rawMime: string;
- try {
- rawMime = await client.getText(`/api/email/${opts.email_id}/raw`);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (msg.includes("404")) {
- console.error(`Error: raw email body not available for ${opts.email_id}`);
- process.exit(1);
- }
- throw err;
- }
-
- // 3. Parse MIME to extract body and attachments
- const parsed = await new PostalMime().parse(rawMime);
-
- // 4. Re-upload original attachments
- const attachments: UploadedFile[] = [];
- if (parsed.attachments && parsed.attachments.length > 0) {
- for (const att of parsed.attachments) {
- const filename = att.filename || "attachment.bin";
- const contentType = att.mimeType || "application/octet-stream";
- const buf = contentToBuffer(att.content);
- const form = new FormData();
- form.append(
- "file",
- new Blob([new Uint8Array(buf)], { type: contentType }),
- filename,
- );
- const uploaded = await client.postMultipart<UploadedFile>(
- "/api/email/upload",
- form,
- );
- attachments.push({
- key: uploaded.key,
- filename: uploaded.filename,
- size: uploaded.size ?? buf.byteLength,
- contentType: uploaded.contentType ?? contentType,
- });
- }
- }
-
- // 5. Upload extra --attachment files
- const extraPaths: string[] = opts.attachment ?? [];
- for (const filePath of extraPaths) {
- attachments.push(await uploadFile(client, filePath, "/api/email/upload"));
- }
-
- // 6. Compose forwarded HTML body
- let htmlBody = "";
- if (opts.note) {
- htmlBody += `<p>${opts.note}</p>`;
- }
- htmlBody += `<br><br>---------- Forwarded message ----------<br>`;
- htmlBody += `From: ${original.from_email}<br>`;
- htmlBody += `Date: ${original.created_at}<br>`;
- htmlBody += `Subject: ${original.subject}<br>`;
- htmlBody += `To: ${original.to_email}<br><br>`;
- if (parsed.html) {
- htmlBody += parsed.html;
- } else if (parsed.text) {
- htmlBody += `<pre>${parsed.text}</pre>`;
- }
-
- // 7. Build subject
- const subject = /^fwd:/i.test(original.subject)
- ? original.subject
- : `Fwd: ${original.subject}`;
-
- // 8. Send
- const ctx = gatherContextEnvVars();
- const res = await client.postJSON<SendResponse>("/api/email/send", {
- agentId,
- to: opts.to,
- subject,
- htmlBody,
- attachments,
- ...(opts.from ? { from: opts.from } : {}),
- ...(ctx.conversationId ? { conversationId: ctx.conversationId } : {}),
- ...(ctx.traceId ? { traceId: ctx.traceId } : {}),
- ...(ctx.sourceTaskId ? { sourceTaskId: ctx.sourceTaskId } : {}),
- });
- console.log(`Forwarded email to ${res.to_email} (id: ${res.id})`);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (msg === "__exit__") throw err;
- console.error(`Error: ${msg}`);
- process.exit(1);
- }
- });
-
- const whitelistCmd = new Command("whitelist").description(
- "Manage email whitelist (allowed senders)",
- );
-
- whitelistCmd
- .command("list")
- .description("List all whitelisted emails for an agent")
- .option("--agent_id <id>", "Agent ID")
- .option("--workspace <id>", "Workspace ID")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, {
- workspace: opts.workspace,
- agentId,
- });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- try {
- const entries = await client.getJSON<WhitelistEntry[]>(
- `/api/agents/${agentId}/whitelist`,
- );
-
- if (!entries.length) {
- console.log("No whitelisted emails.");
- return;
- }
-
- if (opts.json) {
- printJSON(entries);
- return;
- }
-
- printTable(
- ["ID", "EMAIL", "CREATED AT"],
- entries.map((e) => [e.id, e.email, e.created_at]),
- );
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- whitelistCmd
- .command("add")
- .description("Add an email to the whitelist")
- .option("--agent_id <id>", "Agent ID")
- .option("--workspace <id>", "Workspace ID")
- .argument("<email>", "Email address to whitelist")
- .action(async (email, opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, {
- workspace: opts.workspace,
- agentId,
- });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- try {
- const entry = await client.postJSON<WhitelistEntry>(
- `/api/agents/${agentId}/whitelist`,
- { email: email.toLowerCase() },
- );
- console.log(`Added ${entry.email} to whitelist (id: ${entry.id})`);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (msg.includes("409")) {
- console.error(`Error: ${email.toLowerCase()} is already whitelisted`);
- } else {
- console.error(`Error: ${msg}`);
- }
- process.exit(1);
- }
- });
-
- whitelistCmd
- .command("delete")
- .description("Remove an email from the whitelist")
- .option("--agent_id <id>", "Agent ID")
- .option("--workspace <id>", "Workspace ID")
- .argument("<email>", "Email address to remove")
- .action(async (email, opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, {
- workspace: opts.workspace,
- agentId,
- });
- const client = new APIClient(serverUrl, token, workspaceId);
- const normalizedEmail = email.toLowerCase();
-
- try {
- const entries = await client.getJSON<WhitelistEntry[]>(
- `/api/agents/${agentId}/whitelist`,
- );
- const entry = entries.find((e) => e.email === normalizedEmail);
-
- if (!entry) {
- console.error(`Error: ${normalizedEmail} is not in the whitelist`);
- process.exit(1);
- }
-
- await client.deleteJSON(
- `/api/agents/${agentId}/whitelist/${entry.id}`,
- );
- console.log(`Removed ${normalizedEmail} from whitelist`);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (msg === "__exit__") throw err;
- console.error(`Error: ${msg}`);
- process.exit(1);
- }
- });
-
- cmd.addCommand(whitelistCmd);
-
- return cmd;
-}
diff --git a/src/cli/commands/issue.test.ts b/src/cli/commands/issue.test.ts
deleted file mode 100644
index 12dfcfe6b..000000000
--- a/src/cli/commands/issue.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { issueCommand } from "./issue";
-
-describe("issueCommand", () => {
- const cmd = issueCommand();
-
- it("registers issue subcommands", () => {
- const names = cmd.commands.map((c) => c.name());
- expect(names).toContain("create");
- expect(names).toContain("list");
- expect(names).toContain("show");
- expect(names).toContain("update");
- expect(names).toContain("comment");
- });
-
- it("create requires title; --agent_id is optional (env fallback)", () => {
- const create = cmd.commands.find((c) => c.name() === "create")!;
- const opts = (create as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).not.toContain("--agent_id");
- expect(mandatory).toContain("--title");
- });
-
- it("show/update/comment require issue_id; --agent_id is optional (env fallback)", () => {
- for (const name of ["show", "update", "comment"]) {
- const sub = cmd.commands.find((c) => c.name() === name)!;
- const opts = (sub as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).not.toContain("--agent_id");
- expect(mandatory).toContain("--issue_id");
- }
- });
-
- it("update supports status, title, description, and body-file", () => {
- const update = cmd.commands.find((c) => c.name() === "update")!;
- const opts = (update as unknown as { options: { long: string }[] }).options;
- const longs = opts.map((o) => o.long);
- expect(longs).toContain("--status");
- expect(longs).toContain("--title");
- expect(longs).toContain("--description");
- expect(longs).toContain("--body-file");
- });
-});
diff --git a/src/cli/commands/issue.ts b/src/cli/commands/issue.ts
deleted file mode 100644
index cbcae55f5..000000000
--- a/src/cli/commands/issue.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-import { Command } from "commander";
-import { APIClient } from "../lib/client.js";
-import { printJSON } from "../lib/output.js";
-import { resolveAgentId, readBody } from "../lib/flags.js";
-import { resolveClientOpts } from "../lib/resolve-client.js";
-
-const VALID_STATUSES = ["todo", "in_progress", "review", "done", "closed", "canceled", "failed"];
-
-interface IssueResponse {
- id: string;
- workspace_id: string;
- agent_id: string;
- creator_user_id: string;
- conversation_id: string;
- latest_task_id: string | null;
- title: string;
- description: string;
- status: string;
- created_at: string;
- updated_at: string;
- completed_at: string | null;
-}
-
-interface MessageResponse {
- id: string;
- role: string;
- content: string;
- created_at: string;
-}
-
-interface CommentResponse {
- id: string;
- author_type: string;
- author_id: string;
- content: string;
- created_at: string;
-}
-
-
-function printIssue(issue: IssueResponse): void {
- console.log(`${issue.id} ${issue.status.padEnd(11)} ${issue.title}`);
-}
-
-function printIssueDetail(issue: IssueResponse, messages?: MessageResponse[], comments?: CommentResponse[]): void {
- console.log(`id: ${issue.id}`);
- console.log(`agent_id: ${issue.agent_id}`);
- console.log(`status: ${issue.status}`);
- console.log(`conversation_id: ${issue.conversation_id}`);
- if (issue.latest_task_id) console.log(`latest_task_id: ${issue.latest_task_id}`);
- console.log(`title: ${issue.title}`);
- console.log("description:");
- console.log(issue.description || "(no description)");
- const events = messages?.filter((m) => m.role === "event") ?? [];
- if (events.length > 0) {
- console.log("\nevents:");
- for (const m of events) {
- console.log(` [${m.created_at}] ${m.content}`);
- }
- }
- if (comments && comments.length > 0) {
- console.log("\ncomments:");
- for (const c of comments) {
- console.log(` [${c.created_at}] (${c.author_type}) ${c.content}`);
- }
- }
-}
-
-export function issueCommand(): Command {
- const cmd = new Command("issue").description("Manage assigned issues");
-
- cmd
- .command("create")
- .description("Create and dispatch an issue to an agent")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--title <title>", "Issue title")
- .option("--description <text>", "Issue description")
- .option("--body-file <path>", "Read issue description from a file")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
- const description = readBody({ body: opts.description, bodyFile: opts.bodyFile });
- try {
- const res = await client.postJSON<{ issue: IssueResponse }>("/api/issues", {
- agent_id: agentId,
- title: opts.title,
- description,
- });
- if (opts.json) return printJSON(res);
- console.log(`Created ${res.issue.id} — ${res.issue.title}`);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("list")
- .description("List issues for an agent")
- .option("--agent_id <id>", "Agent ID")
- .option("--status <status>", `Filter by status (${VALID_STATUSES.join(", ")})`)
- .option("--completed", "Show completed/closed/canceled/failed issues")
- .option("--all", "Show all issues")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- if (opts.status && !VALID_STATUSES.includes(opts.status)) {
- console.error(`Error: invalid status "${opts.status}"`);
- process.exit(1);
- }
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
- const params = new URLSearchParams({ agentId });
- if (opts.status) params.set("status", opts.status);
- if (!opts.all && !opts.status) params.set("terminal", opts.completed ? "true" : "false");
- try {
- const issues = await client.getJSON<IssueResponse[]>(`/api/issues?${params}`);
- if (opts.json) return printJSON(issues);
- if (issues.length === 0) {
- console.log("No issues found.");
- return;
- }
- for (const issue of issues) printIssue(issue);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("show")
- .description("Show issue details and conversation")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--issue_id <id>", "Issue ID")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
- try {
- const res = await client.getJSON<{ issue: IssueResponse; messages: MessageResponse[]; comments: CommentResponse[] }>(`/api/issues/${opts.issue_id}?agentId=${encodeURIComponent(agentId)}`);
- if (res.issue.agent_id !== agentId) {
- console.error(`Error: issue ${res.issue.id} does not belong to agent ${agentId}`);
- process.exit(1);
- }
- if (opts.json) return printJSON(res);
- printIssueDetail(res.issue, res.messages, res.comments);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("update")
- .description("Update issue status or text")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--issue_id <id>", "Issue ID")
- .option("--status <status>", `New status (${VALID_STATUSES.join(", ")})`)
- .option("--title <title>", "New title")
- .option("--description <text>", "New description")
- .option("--body-file <path>", "Read description from a file")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- if (opts.status && !VALID_STATUSES.includes(opts.status)) {
- console.error(`Error: invalid status "${opts.status}"`);
- process.exit(1);
- }
- const description = readBody({ body: opts.description, bodyFile: opts.bodyFile });
- const body: Record<string, string> = {};
- if (opts.status) body.status = opts.status;
- if (opts.title) body.title = opts.title;
- if (description) body.description = description;
- if (Object.keys(body).length === 0) {
- console.error("Error: pass at least one of --status, --title, --description, --body-file");
- process.exit(1);
- }
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
- try {
- const issue = await client.patchJSON<IssueResponse>(`/api/issues/${opts.issue_id}?agentId=${encodeURIComponent(agentId)}`, body);
- if (opts.json) return printJSON(issue);
- printIssue(issue);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("comment")
- .description("Append a comment to an issue")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--issue_id <id>", "Issue ID")
- .option("--body <text>", "Comment text")
- .option("--body-file <path>", "Read comment from a file")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const content = readBody({ body: opts.body, bodyFile: opts.bodyFile }).trim();
- if (!content) {
- console.error("Error: pass --body or --body-file");
- process.exit(1);
- }
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
- try {
- const res = await client.postJSON<{ comment: CommentResponse }>(`/api/issues/${opts.issue_id}/comments?agentId=${encodeURIComponent(agentId)}`, { content });
- if (opts.json) return printJSON(res);
- console.log(`Commented on ${opts.issue_id}`);
- } catch (err) {
- console.error(`Error: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/login.test.ts b/src/cli/commands/login.test.ts
deleted file mode 100644
index 6d8c0cee5..000000000
--- a/src/cli/commands/login.test.ts
+++ /dev/null
@@ -1,470 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-
-const mockLoadCLIConfigForProfile = vi.fn();
-const mockSaveCLIConfigForProfile = vi.fn();
-const mockReadDaemonPid = vi.fn();
-const mockIsProcessAlive = vi.fn();
-
-vi.mock("../lib/config.js", async (importActual) => ({
- ...(await importActual<typeof import("../lib/config.js")>()),
- loadCLIConfigForProfile: (...args: any[]) => mockLoadCLIConfigForProfile(...args),
- saveCLIConfigForProfile: (...args: any[]) => mockSaveCLIConfigForProfile(...args),
-}));
-
-vi.mock("../daemon/pidfile.js", () => ({
- readDaemonPid: (...args: any[]) => mockReadDaemonPid(...args),
- isProcessAlive: (...args: any[]) => mockIsProcessAlive(...args),
-}));
-
-vi.mock("../lib/env.js", () => ({
- cmdPrefix: () => "alook",
- isDev: () => false,
- getServerUrl: () => "http://localhost:3000",
-}));
-
-vi.mock("../lib/runtimes.js", () => ({
- isCommandAvailable: vi.fn(() => true),
- detectRuntimes: vi.fn(() => [{ type: "claude", version: "4.0.0" }]),
-}));
-
-vi.mock("child_process", () => ({
- execSync: vi.fn((cmd: string) => {
- if (cmd.includes("which claude")) return "/usr/bin/claude";
- if (cmd.includes("claude --version")) return "4.0.0";
- throw new Error("not found");
- }),
- spawn: vi.fn(() => ({ unref: vi.fn() })),
- fork: vi.fn(() => ({ unref: vi.fn() })),
-}));
-
-import { loginCommand } from "./login";
-
-describe("alook login", () => {
- let consoleSpy: ReturnType<typeof vi.spyOn>;
- let consoleErrSpy: ReturnType<typeof vi.spyOn>;
- let mockExit: ReturnType<typeof vi.spyOn>;
- let mockKill: ReturnType<typeof vi.spyOn>;
-
- beforeEach(() => {
- vi.useFakeTimers();
- vi.clearAllMocks();
- consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
- consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- mockExit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);
- mockKill = vi.spyOn(process, "kill").mockImplementation(() => true);
- Object.defineProperty(process.stdout, "isTTY", { value: true, writable: true });
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [],
- });
- mockReadDaemonPid.mockReturnValue(null);
- });
-
- afterEach(() => {
- vi.useRealTimers();
- consoleSpy.mockRestore();
- consoleErrSpy.mockRestore();
- mockExit.mockRestore();
- mockKill.mockRestore();
- vi.unstubAllGlobals();
- });
-
- function mockFetchSequence(responses: { url: string; status: number; body: unknown }[]) {
- const queue = [...responses];
- vi.stubGlobal("fetch", vi.fn(async (url: string | URL | Request, _init?: RequestInit) => {
- const urlStr = typeof url === "string" ? url : url instanceof URL ? url.toString() : url.url;
- const idx = queue.findIndex((r) => urlStr.includes(r.url));
- if (idx >= 0) {
- const resp = queue[idx];
- queue.splice(idx, 1);
- return {
- ok: resp.status >= 200 && resp.status < 300,
- status: resp.status,
- json: async () => resp.body,
- text: async (): Promise<string> => JSON.stringify(resp.body),
- };
- }
- return { ok: false, status: 404, text: async (): Promise<string> => "not found", json: async () => ({ error: "not_found" }) };
- }));
- }
-
- function deviceCodeResponse(overrides: Partial<Record<string, unknown>> = {}) {
- return {
- device_code: "dc_123",
- user_code: "ABCD-EFGH",
- verification_uri: "http://localhost:3000/device",
- verification_uri_complete: "http://localhost:3000/device?user_code=ABCD-EFGH",
- expires_in: 900,
- interval: 1,
- ...overrides,
- };
- }
-
- function tokenSuccessResponse(token = "session_tok_123") {
- return { access_token: token, token_type: "Bearer", expires_in: 2592000, scope: "" };
- }
-
- function fullSuccessResponses() {
- return [
- { url: "/api/auth/device/code", status: 200, body: deviceCodeResponse() },
- { url: "/api/auth/device/token", status: 200, body: tokenSuccessResponse() },
- { url: "/api/me", status: 200, body: { id: "u1", email: "[email protected]" } },
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },
- { url: "/api/machine-tokens", status: 201, body: { token: "al_machine_tok" } },
- { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "host1", workspace_id: "sp_ws1", runtimes: [{ id: "r1", provider: "claude" }] } },
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },
- { url: "/api/agents", status: 200, body: [{ id: "ag_1" }] },
- ];
- }
-
- async function runWithTimers(promise: Promise<unknown>) {
- let settled = false;
- const result = promise.finally(() => { settled = true; });
- while (!settled) {
- await vi.advanceTimersByTimeAsync(10000);
- }
- return result;
- }
-
- it("completes full device code flow and saves config", async () => {
- mockFetchSequence(fullSuccessResponses());
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- // syncWorkspacesToConfig stores session token + synced workspaces
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({
- server_url: "http://localhost:3000",
- session_token: "session_tok_123",
- watched_workspaces: expect.arrayContaining([
- expect.objectContaining({ id: "sp_ws1", name: "My Workspace", status: "active" }),
- ]),
- }),
- );
- // activateAndSave updates the workspace entry with the token
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({
- watched_workspaces: expect.arrayContaining([
- expect.objectContaining({ id: "sp_ws1", token: "al_machine_tok", status: "active" }),
- ]),
- }),
- );
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));
- });
-
-
- it("handles authorization_pending by continuing to poll", async () => {
- mockFetchSequence([
- { url: "/api/auth/device/code", status: 200, body: deviceCodeResponse() },
- { url: "/api/auth/device/token", status: 400, body: { error: "authorization_pending" } },
- { url: "/api/auth/device/token", status: 200, body: tokenSuccessResponse() },
- { url: "/api/me", status: 200, body: { id: "u1", email: "[email protected]" } },
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_poll", name: "Poll WS" }] },
- { url: "/api/machine-tokens", status: 201, body: { token: "al_poll_tok" } },
- { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "host1", workspace_id: "sp_poll", runtimes: [{ id: "r1", provider: "claude" }] } },
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_poll", name: "Poll WS" }] },
- { url: "/api/agents", status: 200, body: [] },
- ]);
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalled();
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));
- });
-
- it("handles slow_down by increasing polling interval", async () => {
- mockFetchSequence([
- { url: "/api/auth/device/code", status: 200, body: deviceCodeResponse() },
- { url: "/api/auth/device/token", status: 400, body: { error: "slow_down" } },
- { url: "/api/auth/device/token", status: 200, body: tokenSuccessResponse() },
- { url: "/api/me", status: 200, body: { id: "u1", email: "[email protected]" } },
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_slow", name: "Slow WS" }] },
- { url: "/api/machine-tokens", status: 201, body: { token: "al_slow_tok" } },
- { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "host1", workspace_id: "sp_slow", runtimes: [{ id: "r1", provider: "claude" }] } },
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_slow", name: "Slow WS" }] },
- { url: "/api/agents", status: 200, body: [] },
- ]);
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));
- });
-
- it("sends SIGHUP when daemon is running after login", async () => {
- mockReadDaemonPid.mockReturnValue(99999);
- mockIsProcessAlive.mockReturnValue(true);
- mockFetchSequence(fullSuccessResponses());
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(mockKill).toHaveBeenCalledWith(99999, "SIGHUP");
- });
-
- it("displays verification URL and user code", async () => {
- mockFetchSequence(fullSuccessResponses());
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("http://localhost:3000/device?user_code=ABCD-EFGH"));
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("ABCD-EFGH"));
- });
-
- describe("already authenticated", () => {
- it("exits early when token is still valid", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_existing_tok" }],
- });
-
- mockFetchSequence([
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },
- { url: "/api/me", status: 200, body: { email: "[email protected]" } },
- ]);
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(consoleSpy).toHaveBeenCalledWith(
- "Already logged in as [email protected] (workspace: My Workspace).",
- );
- expect(mockSaveCLIConfigForProfile).not.toHaveBeenCalled();
- });
-
- it("proceeds with login when --force is set", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_existing_tok" }],
- });
-
- mockFetchSequence(fullSuccessResponses());
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000", "--force"]));
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalled();
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));
- });
-
- it("proceeds with login when token is invalid/expired", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_expired_tok" }],
- });
-
- mockFetchSequence([
- { url: "/api/workspaces", status: 401, body: { error: "unauthorized" } },
- { url: "/api/auth/device/code", status: 200, body: deviceCodeResponse() },
- { url: "/api/auth/device/token", status: 200, body: tokenSuccessResponse() },
- { url: "/api/me", status: 200, body: { id: "u1", email: "[email protected]" } },
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },
- { url: "/api/machine-tokens", status: 201, body: { token: "al_new_tok" } },
- { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "host1", workspace_id: "sp_ws1", runtimes: [{ id: "r1", provider: "claude" }] } },
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },
- { url: "/api/agents", status: 200, body: [] },
- ]);
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalled();
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));
- });
-
- it("proceeds with login when no workspaces in config", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [],
- });
-
- mockFetchSequence(fullSuccessResponses());
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalled();
- });
-
- it("shows message without email when /api/me fails", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_existing_tok" }],
- });
-
- mockFetchSequence([
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },
- { url: "/api/me", status: 500, body: { error: "internal" } },
- ]);
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(consoleSpy).toHaveBeenCalledWith(
- "Already logged in (workspace: My Workspace).",
- );
- expect(mockSaveCLIConfigForProfile).not.toHaveBeenCalled();
- });
-
- it("shows message without email when /api/me throws network error", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_existing_tok" }],
- });
-
- let callCount = 0;
- vi.stubGlobal("fetch", vi.fn(async (url: string | URL | Request) => {
- const urlStr = typeof url === "string" ? url : url instanceof URL ? url.toString() : url.url;
- callCount++;
- if (urlStr.includes("/api/workspaces")) {
- return { ok: true, status: 200, json: async () => [{ id: "sp_ws1" }], text: async () => "[]" };
- }
- if (urlStr.includes("/api/me")) {
- throw new Error("network error");
- }
- return { ok: false, status: 404, text: async () => "not found", json: async () => ({}) };
- }));
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(consoleSpy).toHaveBeenCalledWith(
- "Already logged in (workspace: My Workspace).",
- );
- });
-
- it("proceeds with login when token field is empty", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "" }],
- });
-
- mockFetchSequence(fullSuccessResponses());
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalled();
- });
-
- it("works correctly in non-TTY mode with early exit", async () => {
- Object.defineProperty(process.stdout, "isTTY", { value: false, writable: true });
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_valid_tok" }],
- });
-
- mockFetchSequence([
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },
- { url: "/api/me", status: 200, body: { email: "[email protected]" } },
- ]);
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(consoleSpy).toHaveBeenCalledWith(
- "Already logged in as [email protected] (workspace: My Workspace).",
- );
- expect(mockSaveCLIConfigForProfile).not.toHaveBeenCalled();
- });
- });
-
- describe("session token and workspace sync", () => {
- it("stores session_token in config after login", async () => {
- mockFetchSequence(fullSuccessResponses());
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({ session_token: "session_tok_123" }),
- );
- });
-
- it("syncs server workspaces to local config during login", async () => {
- mockFetchSequence([
- { url: "/api/auth/device/code", status: 200, body: deviceCodeResponse() },
- { url: "/api/auth/device/token", status: 200, body: tokenSuccessResponse() },
- { url: "/api/me", status: 200, body: { id: "u1", email: "[email protected]" } },
- { url: "/api/workspaces", status: 200, body: [
- { id: "sp_ws1", name: "Work" },
- { id: "sp_ws2", name: "Personal" },
- ] },
- { url: "/api/machine-tokens", status: 201, body: { token: "al_mt" } },
- { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "h1", workspace_id: "sp_ws1", runtimes: [{ id: "r1", provider: "claude" }] } },
- { url: "/api/workspaces", status: 200, body: [
- { id: "sp_ws1", name: "Work" },
- { id: "sp_ws2", name: "Personal" },
- ] },
- { url: "/api/agents", status: 200, body: [] },
- ]);
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({
- watched_workspaces: expect.arrayContaining([
- expect.objectContaining({ id: "sp_ws1", name: "Work", status: "active" }),
- expect.objectContaining({ id: "sp_ws2", name: "Personal", status: "active" }),
- ]),
- }),
- );
- });
-
- it("syncs workspaces when existing auth valid but no local workspace id", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- session_token: "old_session_tok",
- watched_workspaces: [{ id: null, name: null, token: "al_reg_tok", status: "registered" }],
- });
-
- mockFetchSequence([
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_synced", name: "Synced WS" }] },
- { url: "/api/me", status: 200, body: { email: "[email protected]" } },
- ]);
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({
- watched_workspaces: expect.arrayContaining([
- expect.objectContaining({ id: "sp_synced", name: "Synced WS", status: "active" }),
- ]),
- }),
- );
- expect(consoleSpy).toHaveBeenCalledWith(
- "Already logged in as [email protected] (workspace: Synced WS).",
- );
- });
-
- it("uses session token for auth check when machine token not available", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- session_token: "session_valid",
- watched_workspaces: [{ id: "sp_ws1", name: "Session WS", token: "" }],
- });
-
- mockFetchSequence([
- { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "Session WS" }] },
- { url: "/api/me", status: 200, body: { email: "[email protected]" } },
- ]);
-
- const cmd = loginCommand();
- await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
-
- expect(consoleSpy).toHaveBeenCalledWith(
- "Already logged in as [email protected] (workspace: Session WS).",
- );
- });
- });
-});
diff --git a/src/cli/commands/login.ts b/src/cli/commands/login.ts
deleted file mode 100644
index 140161ca4..000000000
--- a/src/cli/commands/login.ts
+++ /dev/null
@@ -1,354 +0,0 @@
-import { Command } from "commander";
-import { fork, spawn } from "child_process";
-import { fileURLToPath } from "url";
-import { APIClient } from "../lib/client.js";
-import { activateAndSave } from "../lib/activate.js";
-import { loadCLIConfigForProfile, saveCLIConfigForProfile, activeWorkspaces, markWorkspaceActive, markWorkspaceDeletedInList } from "../lib/config.js";
-import { cmdPrefix, getServerUrl } from "../lib/env.js";
-
-const DEVICE_CLIENT_ID = process.env.ALOOK_DEVICE_CLIENT_ID || "alook-cli";
-
-interface DeviceCodeResponse {
- device_code: string;
- user_code: string;
- verification_uri: string;
- verification_uri_complete: string;
- expires_in: number;
- interval: number;
-}
-
-interface TokenResponse {
- access_token: string;
- token_type: string;
- expires_in: number;
- scope: string;
-}
-
-interface TokenErrorResponse {
- error: string;
- error_description?: string;
-}
-
-interface WorkspaceResponse {
- id: string;
- name: string;
-}
-
-
-function openBrowser(url: string): void {
- try {
- const cmd =
- process.platform === "darwin" ? "open" :
- process.platform === "linux" ? "xdg-open" :
- process.platform === "win32" ? "start" : null;
- if (cmd) {
- const args = process.platform === "win32" ? ["", url] : [url];
- spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
- }
- } catch {
- // Browser open is best-effort
- }
-}
-
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-function syncWorkspacesToConfig(
- serverWorkspaces: WorkspaceResponse[],
- profile?: string,
- sessionToken?: string,
-): void {
- const cfg = loadCLIConfigForProfile(profile);
- const watched = cfg.watched_workspaces || [];
- const serverIds = new Set(serverWorkspaces.map((w) => w.id));
-
- for (const sw of serverWorkspaces) {
- markWorkspaceActive(watched, { id: sw.id, name: sw.name });
- }
-
- for (const w of watched) {
- if (w.id && !serverIds.has(w.id)) {
- markWorkspaceDeletedInList(watched, w.id);
- }
- }
-
- saveCLIConfigForProfile(profile, {
- server_url: cfg.server_url,
- session_token: sessionToken ?? cfg.session_token,
- watched_workspaces: watched,
- });
-}
-
-async function pollAndActivate(opts: {
- deviceCode: string;
- interval: number;
- expiresIn: number;
- serverUrl: string;
- profile?: string;
-}): Promise<void> {
- const { deviceCode, expiresIn, serverUrl, profile } = opts;
- let interval = opts.interval;
- const expiresAt = Date.now() + expiresIn * 1000;
- let tokenResp: TokenResponse | undefined;
-
- while (Date.now() < expiresAt) {
- await sleep(interval);
-
- try {
- const res = await fetch(`${serverUrl}/api/auth/device/token`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
- device_code: deviceCode,
- client_id: DEVICE_CLIENT_ID,
- }),
- });
-
- if (res.ok) {
- tokenResp = await res.json() as TokenResponse;
- break;
- }
-
- const errBody = await res.json() as TokenErrorResponse;
- if (errBody.error === "slow_down") {
- interval += 5000;
- } else if (errBody.error === "authorization_pending") {
- // Keep polling
- } else if (errBody.error === "expired_token") {
- console.error("Error: device code expired. Please run login again.");
- process.exit(1);
- } else if (errBody.error === "access_denied") {
- console.error("Error: authorization was denied.");
- process.exit(1);
- } else {
- console.error(`Error: unexpected error: ${errBody.error_description || errBody.error}`);
- process.exit(1);
- }
- } catch {
- console.error("Error: network request failed during polling.");
- process.exit(1);
- }
- }
-
- if (!tokenResp) {
- console.error("Error: device code expired (timed out). Please run login again.");
- process.exit(1);
- }
-
- const sessionToken = tokenResp.access_token;
- const client = new APIClient(serverUrl, sessionToken);
-
- let email = "";
- try {
- const me = await client.getJSON<{ id: string; email: string }>("/api/me");
- email = me.email;
- } catch {
- // Non-fatal — we can proceed without the email for display
- }
-
- // Sync workspaces from server and store session token
- let serverWorkspaces: WorkspaceResponse[] = [];
- try {
- serverWorkspaces = await client.getJSON<WorkspaceResponse[]>("/api/workspaces");
- } catch {
- // Non-fatal — will create new workspace during activate
- }
- syncWorkspacesToConfig(serverWorkspaces, profile, sessionToken);
-
- let workspaceId = serverWorkspaces.length > 0 ? serverWorkspaces[0].id : "";
-
- if (!workspaceId) {
- try {
- const newWs = await client.postJSON<{ id: string; name: string }>("/api/workspaces", {
- name: "Personal",
- slug: email.split("@")[0]?.toLowerCase().replace(/[^a-z0-9-]/g, "-").slice(0, 48) || "personal",
- });
- workspaceId = newWs.id;
- } catch (err) {
- console.error(`Error: failed to create workspace: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- }
-
- let machineToken: string;
- try {
- const mtResp = await client.postJSON<{ token: string }>(`/api/machine-tokens?workspace_id=${workspaceId}`);
- machineToken = mtResp.token;
- } catch {
- process.exit(1);
- }
-
- const result = await activateAndSave({ token: machineToken, serverUrl, profile });
-
- if (email) {
- console.log(`\nLogged in as ${email}`);
- }
- console.log(`Workspace: ${result.workspaceName} (${result.workspaceId})`);
- console.log(`Runtimes: ${result.runtimeProviders.join(", ")}`);
-}
-
-// Background polling entry point — invoked as a detached child process in non-TTY mode
-if (process.argv.includes("--__login-poll")) {
- const idx = process.argv.indexOf("--__login-poll");
- let data;
- try {
- data = JSON.parse(process.argv[idx + 1]);
- } catch {
- console.error("Error: invalid poll data");
- process.exit(1);
- }
- pollAndActivate(data).catch(() => process.exit(1));
-}
-
-async function checkExistingAuth(serverUrl: string, profile?: string): Promise<{ valid: boolean; email?: string; workspaceName?: string }> {
- const config = loadCLIConfigForProfile(profile);
-
- // Try session token first, then machine token from workspaces
- const sessionToken = config.session_token;
- const workspaces = activeWorkspaces(config.watched_workspaces);
- const ws = workspaces[0];
- const authToken = sessionToken || ws?.token;
-
- if (!authToken) {
- return { valid: false };
- }
-
- try {
- const res = await fetch(`${serverUrl}/api/workspaces`, {
- headers: { Authorization: `Bearer ${authToken}` },
- });
- if (!res.ok) {
- return { valid: false };
- }
-
- const serverWorkspaces = await res.json() as WorkspaceResponse[];
-
- // Sync workspaces when config has no workspace with a valid id
- const hasValidWorkspace = workspaces.length > 0;
- if (!hasValidWorkspace && serverWorkspaces.length > 0) {
- syncWorkspacesToConfig(serverWorkspaces, profile);
- }
-
- let email: string | undefined;
- try {
- const meRes = await fetch(`${serverUrl}/api/me`, {
- headers: { Authorization: `Bearer ${authToken}` },
- });
- if (meRes.ok) {
- const me = await meRes.json() as { email?: string };
- email = me.email;
- }
- } catch {
- // Non-fatal — proceed without email
- }
-
- const workspaceName = (serverWorkspaces.length > 0 ? serverWorkspaces[0].name : undefined)
- || ws?.name
- || undefined;
-
- return { valid: true, email, workspaceName };
- } catch {
- return { valid: false };
- }
-}
-
-export function loginCommand(): Command {
- const cmd = new Command("login")
- .description("Log in to Alook via browser (device code flow)")
- .option("--server <url>", "Server URL")
- .option("--profile <name>", "Profile name")
- .option("--force", "Re-authenticate even if already logged in")
- .action(async (opts, command) => {
- const profile: string | undefined =
- opts.profile || command.parent?.opts().profile;
- const serverUrl: string =
- opts.server ||
- command.parent?.opts().server ||
- getServerUrl();
-
- // Check if already authenticated (skip with --force)
- if (!opts.force) {
- const existing = await checkExistingAuth(serverUrl, profile);
- if (existing.valid) {
- const parts = ["Already logged in"];
- if (existing.email) parts[0] += ` as ${existing.email}`;
- if (existing.workspaceName) parts[0] += ` (workspace: ${existing.workspaceName})`;
- parts[0] += ".";
- console.log(parts[0]);
- return;
- }
- }
-
- // Step 1: Request device code
- console.log("Requesting device code...");
- let deviceResp: DeviceCodeResponse;
- try {
- const res = await fetch(`${serverUrl}/api/auth/device/code`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ client_id: DEVICE_CLIENT_ID }),
- });
- if (!res.ok) {
- const text = await res.text();
- console.error(`Error: failed to get device code (${res.status}): ${text}`);
- process.exit(1);
- }
- deviceResp = await res.json() as DeviceCodeResponse;
- } catch (err) {
- console.error(
- `Error: failed to request device code: ${err instanceof Error ? err.message : err}`,
- );
- process.exit(1);
- }
-
- // Step 2: Display verification URL and code
- const verificationUrl = deviceResp.verification_uri_complete || deviceResp.verification_uri;
- console.log();
- console.log(` Open this URL in your browser:`);
- console.log(` ${verificationUrl}`);
- console.log();
- console.log(` Enter code: ${deviceResp.user_code}`);
- console.log();
-
- // Non-TTY (AI agent context): fork a background poller and exit immediately
- // so the agent gets the URL output and can prompt the user to authorize.
- if (!process.stdout.isTTY) {
- const pollData = JSON.stringify({
- deviceCode: deviceResp.device_code,
- interval: (deviceResp.interval || 5) * 1000,
- expiresIn: deviceResp.expires_in,
- serverUrl,
- profile,
- });
-
- const thisFile = fileURLToPath(import.meta.url);
- const child = fork(thisFile, ["--__login-poll", pollData], {
- detached: true,
- stdio: "ignore",
- });
- child.unref();
-
- console.log(" Polling for authorization in the background (timeout: 5min).");
- console.log(` Once approved, run \`${cmdPrefix()} status\` to verify.`);
- return;
- }
-
- // TTY: open browser and poll in foreground
- openBrowser(verificationUrl);
- console.log(" (Browser opened automatically)");
- console.log();
- console.log("Waiting for authorization...");
-
- await pollAndActivate({
- deviceCode: deviceResp.device_code,
- interval: (deviceResp.interval || 5) * 1000,
- expiresIn: deviceResp.expires_in,
- serverUrl,
- profile,
- });
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/register.test.ts b/src/cli/commands/register.test.ts
deleted file mode 100644
index 9b5f19d75..000000000
--- a/src/cli/commands/register.test.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-
-const mockLoadCLIConfigForProfile = vi.fn();
-const mockSaveCLIConfigForProfile = vi.fn();
-const mockReadDaemonPid = vi.fn();
-const mockIsProcessAlive = vi.fn();
-
-vi.mock("../lib/config.js", async (importActual) => ({
- ...(await importActual<typeof import("../lib/config.js")>()),
- loadCLIConfigForProfile: (...args: any[]) => mockLoadCLIConfigForProfile(...args),
- saveCLIConfigForProfile: (...args: any[]) => mockSaveCLIConfigForProfile(...args),
-}));
-
-vi.mock("../daemon/pidfile.js", () => ({
- readDaemonPid: (...args: any[]) => mockReadDaemonPid(...args),
- isProcessAlive: (...args: any[]) => mockIsProcessAlive(...args),
-}));
-
-vi.mock("../lib/env.js", () => ({
- cmdPrefix: () => "alook",
- isDev: () => false,
-}));
-
-vi.mock("../lib/runtimes.js", () => ({
- isCommandAvailable: vi.fn(() => true),
- detectRuntimes: vi.fn(() => [{ type: "claude", version: "4.0.0" }]),
-}));
-
-vi.mock("child_process", () => ({
- execSync: vi.fn((cmd: string) => {
- if (cmd.includes("which claude")) return "/usr/bin/claude";
- if (cmd.includes("claude --version")) return "4.0.0";
- throw new Error("not found");
- }),
- spawn: vi.fn(() => ({ unref: vi.fn() })),
-}));
-
-import { registerCommand } from "./register";
-
-describe("alook register", () => {
- let consoleSpy: ReturnType<typeof vi.spyOn>;
- let consoleErrSpy: ReturnType<typeof vi.spyOn>;
- let mockExit: ReturnType<typeof vi.spyOn>;
- let mockKill: ReturnType<typeof vi.spyOn>;
-
- beforeEach(() => {
- vi.clearAllMocks();
- consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
- consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- mockExit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);
- mockKill = vi.spyOn(process, "kill").mockImplementation(() => true);
- });
-
- afterEach(() => {
- consoleSpy.mockRestore();
- consoleErrSpy.mockRestore();
- mockExit.mockRestore();
- mockKill.mockRestore();
- vi.unstubAllGlobals();
- });
-
- function mockFetch(responses: Record<string, { status: number; body: unknown }>) {
- vi.stubGlobal("fetch", vi.fn(async (url: string | URL | Request) => {
- const urlStr = typeof url === "string" ? url : url instanceof URL ? url.toString() : url.url;
- for (const [pattern, resp] of Object.entries(responses)) {
- if (urlStr.includes(pattern)) {
- return {
- ok: resp.status >= 200 && resp.status < 300,
- status: resp.status,
- json: async () => resp.body,
- text: async (): Promise<string> => JSON.stringify(resp.body),
- };
- }
- }
- return { ok: false, status: 404, text: async (): Promise<string> => "not found" };
- }));
- }
-
- const activateResponse = {
- daemon_id: "host1",
- workspace_id: "ws_1",
- runtimes: [{ id: "rt_1", provider: "claude" }],
- };
-
- it("activates token and saves workspace to config", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [],
- });
- mockReadDaemonPid.mockReturnValue(null);
-
- mockFetch({
- "/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },
- "/api/machine-tokens/activate": { status: 200, body: activateResponse },
- "/api/workspaces": { status: 200, body: [{ id: "ws_1", name: "Personal" }] },
- "/api/agents": { status: 200, body: [] },
- });
-
- const cmd = registerCommand();
- await cmd.parseAsync(["node", "register", "--token", "al_testtoken123", "--server", "http://localhost:3000"]);
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({
- server_url: "http://localhost:3000",
- watched_workspaces: [
- { id: "ws_1", name: "Personal", token: "al_testtoken123", status: "active", agent_ids: [] },
- ],
- }),
- );
- });
-
- it("preserves existing watched_workspaces and updates matching entry", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [
- { id: "ws_1", name: "Existing", token: "al_old", status: "active", agent_ids: ["ag_1"] },
- ],
- });
- mockReadDaemonPid.mockReturnValue(null);
-
- mockFetch({
- "/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },
- "/api/machine-tokens/activate": { status: 200, body: activateResponse },
- "/api/workspaces": { status: 200, body: [{ id: "ws_1", name: "Personal" }] },
- "/api/agents": { status: 200, body: [{ id: "ag_1" }] },
- });
-
- const cmd = registerCommand();
- await cmd.parseAsync(["node", "register", "--token", "al_newtoken", "--server", "http://localhost:3000"]);
-
- expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
- undefined,
- expect.objectContaining({
- watched_workspaces: [
- { id: "ws_1", name: "Personal", token: "al_newtoken", status: "active", agent_ids: ["ag_1"] },
- ],
- }),
- );
- });
-
- it("sends SIGHUP when daemon is running", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [],
- });
- mockReadDaemonPid.mockReturnValue(12345);
- mockIsProcessAlive.mockReturnValue(true);
-
- mockFetch({
- "/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },
- "/api/machine-tokens/activate": { status: 200, body: activateResponse },
- "/api/workspaces": { status: 200, body: [{ id: "ws_1", name: "Personal" }] },
- "/api/agents": { status: 200, body: [] },
- });
-
- const cmd = registerCommand();
- await cmd.parseAsync(["node", "register", "--token", "al_test", "--server", "http://localhost:3000"]);
-
- expect(mockKill).toHaveBeenCalledWith(12345, "SIGHUP");
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Daemon (pid 12345) notified"));
- });
-
- it("auto-starts daemon when not running", async () => {
- mockLoadCLIConfigForProfile.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [],
- });
- mockReadDaemonPid.mockReturnValue(null);
-
- mockFetch({
- "/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },
- "/api/machine-tokens/activate": { status: 200, body: activateResponse },
- "/api/workspaces": { status: 200, body: [{ id: "ws_1", name: "Personal" }] },
- "/api/agents": { status: 200, body: [] },
- });
-
- const cmd = registerCommand();
- await cmd.parseAsync(["node", "register", "--token", "al_test", "--server", "http://localhost:3000"]);
-
- expect(mockKill).not.toHaveBeenCalled();
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Starting daemon"));
- });
-});
diff --git a/src/cli/commands/register.ts b/src/cli/commands/register.ts
deleted file mode 100644
index 1aa43abe8..000000000
--- a/src/cli/commands/register.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { Command } from "commander";
-import { APIClient } from "../lib/client.js";
-import { cmdPrefix, getServerUrl } from "../lib/env.js";
-import { activateAndSave } from "../lib/activate.js";
-
-interface MeResponse {
- id: string;
- email: string;
-}
-
-export function registerCommand(): Command {
- const cmd = new Command("register")
- .description("Register CLI with your Alook account")
- .requiredOption("--token <token>", "API token (starts with al_)")
- .option("--server <url>", "Server URL")
- .option("--profile <name>", "Profile name")
- .action(async (opts, command) => {
- const token: string = opts.token;
- const profile: string | undefined =
- opts.profile || command.parent?.opts().profile;
- const serverUrl: string =
- opts.server ||
- command.parent?.opts().server ||
- getServerUrl();
-
- if (!token) {
- console.error(
- `Error: --token is required\nUsage: ${cmdPrefix()} register --token <token>`,
- );
- process.exit(1);
- }
-
- if (!token.startsWith("al_")) {
- console.error(
- "Error: invalid token format: must start with 'al_'",
- );
- process.exit(1);
- }
-
- const client = new APIClient(serverUrl, token);
-
- // Verify token
- let me: MeResponse;
- try {
- me = await client.getJSON<MeResponse>("/api/me");
- } catch (err) {
- console.error(
- `Error: failed to verify token: ${err instanceof Error ? err.message : err}`,
- );
- process.exit(1);
- }
-
- const result = await activateAndSave({ token, serverUrl, profile });
-
- console.log(`\nRegistered as ${me.email}`);
- console.log(`Workspace: ${result.workspaceName} (${result.workspaceId})`);
- console.log(`Runtimes: ${result.runtimeProviders.join(", ")}`);
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/status.ts b/src/cli/commands/status.ts
deleted file mode 100644
index 980426b78..000000000
--- a/src/cli/commands/status.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { Command } from "commander";
-import { loadCLIConfigForProfile, activeWorkspaces } from "../lib/config.js";
-import { cmdPrefix } from "../lib/env.js";
-
-export function statusCommand(): Command {
- const cmd = new Command("status")
- .description("Show registration status")
- .action((_opts, command) => {
- const profile: string | undefined = command.parent?.opts().profile;
- const cfg = loadCLIConfigForProfile(profile);
-
- const ws = activeWorkspaces(cfg.watched_workspaces)[0];
- if (!ws?.token) {
- console.log("Not registered");
- console.log(
- `Run '${cmdPrefix()} register --token <token>' to register.`,
- );
- return;
- }
-
- console.log("Status: Registered");
- console.log(`Server: ${cfg.server_url}`);
- console.log(`Workspace: ${ws.name} (${ws.id})`);
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/sync.test.ts b/src/cli/commands/sync.test.ts
deleted file mode 100644
index f5e8783a0..000000000
--- a/src/cli/commands/sync.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { describe, expect, it, vi, afterEach } from "vitest";
-import { syncCommand } from "./sync";
-
-describe("syncCommand", () => {
- const cmd = syncCommand();
-
- it("registers sync subcommands (upload-artifact + send-dm)", () => {
- const names = cmd.commands.map((c) => c.name());
- expect(names).toContain("upload-artifact");
- expect(names).toContain("send-dm");
- });
-
- it("send-dm: --agent_id and --conversation_id are optional (env fallback)", () => {
- const sub = cmd.commands.find((c) => c.name() === "send-dm")!;
- const opts = (sub as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
- const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
- expect(mandatory).toEqual([]); // nothing required at the flag level
- const longs = opts.map((o) => o.long);
- expect(longs).toContain("--message");
- expect(longs).toContain("--message-file");
- expect(longs).toContain("--conversation_id");
- expect(longs).toContain("--agent_id");
- });
-
- describe("send-dm behavior", () => {
- afterEach(() => {
- vi.restoreAllMocks();
- delete process.env.ALOOK_CONVERSATION_ID;
- });
-
- function runSendDm(args: string[]) {
- // Throw on exit so we can assert it was hit without actually exiting.
- const exit = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
- throw new Error(`exit:${code}`);
- }) as never);
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- let thrown: Error | null = null;
- try {
- // parseAsync runs the action; commander dispatches to the subcommand.
- return { promise: syncCommand().parseAsync(["node", "alook", "send-dm", ...args]), exit, errSpy };
- } catch (e) {
- thrown = e as Error;
- return { thrown, exit, errSpy };
- }
- }
-
- it("TC2: --message and --message-file together → error, exit 1", async () => {
- const { promise, errSpy } = runSendDm([
- "--message", "hi",
- "--message-file", "/tmp/does-not-matter",
- ]);
- await expect(promise).rejects.toThrow("exit:1");
- expect(errSpy).toHaveBeenCalledWith(
- expect.stringContaining("mutually exclusive"),
- );
- });
-
- it("TC3: no conversation id (no env, no flag) → error, exit 1", async () => {
- delete process.env.ALOOK_CONVERSATION_ID;
- const { promise, errSpy } = runSendDm(["--message", "hello"]);
- await expect(promise).rejects.toThrow("exit:1");
- expect(errSpy).toHaveBeenCalledWith(
- expect.stringContaining("no conversation id"),
- );
- });
-
- it("empty --message → error, exit 1", async () => {
- process.env.ALOOK_CONVERSATION_ID = "c1";
- const { promise, errSpy } = runSendDm(["--message", " "]);
- await expect(promise).rejects.toThrow("exit:1");
- expect(errSpy).toHaveBeenCalledWith(
- expect.stringContaining("must not be empty"),
- );
- });
- });
-});
diff --git a/src/cli/commands/sync.ts b/src/cli/commands/sync.ts
deleted file mode 100644
index 33570086f..000000000
--- a/src/cli/commands/sync.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import { Command } from "commander";
-import { readFileSync } from "fs";
-import { basename } from "path";
-import { APIClient } from "../lib/client.js";
-import { printJSON } from "../lib/output.js";
-import { resolveAgentId } from "../lib/flags.js";
-import { resolveClientOpts } from "../lib/resolve-client.js";
-import { guessContentType } from "../lib/file-utils.js";
-
-export function syncCommand(): Command {
- const cmd = new Command("sync").description("Sync info with the user (files, messages)");
-
- cmd
- .command("upload-artifact")
- .description("Upload a file artifact to a conversation")
- .option("--agent_id <id>", "Agent ID")
- .requiredOption("--conversation_id <id>", "Conversation ID")
- .requiredOption("--file <path>", "Path to file to upload")
- .action(async (opts, command) => {
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- let bytes: Buffer;
- try {
- bytes = readFileSync(opts.file);
- } catch (err) {
- console.error(`Error: cannot read file "${opts.file}": ${(err as Error).message}`);
- process.exit(1);
- }
-
- const filename = basename(opts.file);
- const contentType = guessContentType(filename);
-
- let thumbnailBytes: Buffer | null = null;
- const isRasterImage = contentType.startsWith("image/") && contentType !== "image/svg+xml";
- if (isRasterImage) {
- try {
- const sharpMod = await import("sharp");
- const sharp = sharpMod.default;
- thumbnailBytes = await sharp(bytes)
- .resize(200, 200, { fit: "inside" })
- .jpeg({ quality: 70 })
- .toBuffer();
- } catch (err) {
- console.error(`Warning: thumbnail generation skipped: ${(err as Error).message}`);
- }
- }
-
- const form = new FormData();
- form.append(
- "file",
- new Blob([new Uint8Array(bytes)], { type: contentType }),
- filename
- );
- if (thumbnailBytes) {
- form.append(
- "thumbnail",
- new Blob([new Uint8Array(thumbnailBytes)], { type: "image/jpeg" }),
- `thumb_${filename}.jpg`
- );
- }
- form.append("agent_id", agentId);
- form.append("conversation_id", opts.conversation_id);
-
- try {
- const result = await client.postMultipart<Record<string, unknown>>(
- "/api/artifacts/upload",
- form
- );
- printJSON(result);
- } catch (err) {
- console.error(`Error uploading artifact: ${(err as Error).message}`);
- process.exit(1);
- }
- });
-
- cmd
- .command("send-dm")
- .description("Send a message to the user in the current conversation (the agent's voice)")
- .option("--agent_id <id>", "Agent ID")
- .option("--conversation_id <id>", "Conversation ID (defaults to $ALOOK_CONVERSATION_ID)")
- .option("--message <text>", "Message body")
- .option("--message-file <path>", "Read message body from a file")
- .action(async (opts, command) => {
- if (opts.message && opts.messageFile) {
- console.error("Error: --message and --message-file are mutually exclusive");
- process.exit(1);
- }
-
- let content: string;
- if (opts.messageFile) {
- try {
- content = readFileSync(opts.messageFile, "utf-8");
- } catch (err) {
- console.error(`Error: cannot read file "${opts.messageFile}": ${(err as Error).message}`);
- process.exit(1);
- }
- } else {
- content = (opts.message ?? "").replace(/\\n/g, "\n").replace(/\\t/g, "\t");
- }
- if (!content.trim()) {
- console.error("Error: --message or --message-file is required (and must not be empty)");
- process.exit(1);
- }
-
- const conversationId = opts.conversation_id || process.env.ALOOK_CONVERSATION_ID;
- if (!conversationId) {
- console.error("Error: no conversation id (set --conversation_id or $ALOOK_CONVERSATION_ID)");
- process.exit(1);
- }
-
- const agentId = resolveAgentId(opts);
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
- const client = new APIClient(serverUrl, token, workspaceId);
-
- try {
- const result = await client.postJSON<Record<string, unknown>>(
- `/api/daemon/conversations/${encodeURIComponent(conversationId)}/messages`,
- { content, task_id: process.env.ALOOK_TASK_ID || undefined }
- );
- printJSON(result);
- } catch (err) {
- console.error(`Error sending message: ${(err as Error).message}`);
- process.exit(1);
- }
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/update.test.ts b/src/cli/commands/update.test.ts
deleted file mode 100644
index 47984cdda..000000000
--- a/src/cli/commands/update.test.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-
-const mockGetCurrentVersion = vi.fn();
-const mockFetchLatestVersion = vi.fn();
-const mockRunNpmUpdate = vi.fn();
-
-vi.mock("../lib/update.js", () => ({
- getCurrentVersion: () => mockGetCurrentVersion(),
- fetchLatestVersion: () => mockFetchLatestVersion(),
- runNpmUpdate: (...args: any[]) => mockRunNpmUpdate(...args),
-}));
-
-vi.mock("@alook/shared", () => ({
- semverGte: (a: string, b: string) => {
- const pa = a.split(".").map(Number);
- const pb = b.split(".").map(Number);
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
- const sa = pa[i] ?? 0;
- const sb = pb[i] ?? 0;
- if (sa > sb) return true;
- if (sa < sb) return false;
- }
- return true;
- },
-}));
-
-import { updateCommand } from "./update";
-
-describe("alook update", () => {
- let consoleSpy: ReturnType<typeof vi.spyOn>;
- let consoleErrSpy: ReturnType<typeof vi.spyOn>;
- let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
- let mockExit: ReturnType<typeof vi.spyOn>;
-
- beforeEach(() => {
- vi.clearAllMocks();
- consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
- consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
- mockExit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);
- vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("no daemon")));
- });
-
- afterEach(() => {
- consoleSpy.mockRestore();
- consoleErrSpy.mockRestore();
- consoleWarnSpy.mockRestore();
- mockExit.mockRestore();
- vi.unstubAllGlobals();
- });
-
- it("shows 'already up to date' when on latest version", async () => {
- mockGetCurrentVersion.mockReturnValue("1.0.0");
- mockFetchLatestVersion.mockResolvedValue("1.0.0");
-
- const cmd = updateCommand();
- await cmd.parseAsync(["node", "update"]);
-
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("up to date"));
- });
-
- it("runs npm install when newer version available", async () => {
- mockGetCurrentVersion.mockReturnValue("0.5.0");
- mockFetchLatestVersion.mockResolvedValue("1.0.0");
- mockRunNpmUpdate.mockResolvedValue({ success: true, output: "" });
-
- const cmd = updateCommand();
- await cmd.parseAsync(["node", "update"]);
-
- expect(mockRunNpmUpdate).toHaveBeenCalledWith("1.0.0");
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Updated successfully"));
- });
-
- it("handles network errors gracefully", async () => {
- mockGetCurrentVersion.mockReturnValue("0.5.0");
- mockFetchLatestVersion.mockResolvedValue(null);
-
- const cmd = updateCommand();
- await cmd.parseAsync(["node", "update"]);
-
- expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to fetch"));
- expect(mockExit).toHaveBeenCalledWith(1);
- });
-
- it("warns when daemon health endpoint is reachable", async () => {
- mockGetCurrentVersion.mockReturnValue("0.5.0");
- mockFetchLatestVersion.mockResolvedValue("1.0.0");
- mockRunNpmUpdate.mockResolvedValue({ success: true, output: "" });
- (globalThis.fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({ ok: true });
-
- const cmd = updateCommand();
- await cmd.parseAsync(["node", "update"]);
-
- expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("daemon is running"));
- });
-});
diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts
deleted file mode 100644
index 51a371711..000000000
--- a/src/cli/commands/update.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { Command } from "commander";
-import { getCurrentVersion, fetchLatestVersion, runNpmUpdate } from "../lib/update.js";
-import { semverGte } from "@alook/shared";
-
-export function updateCommand(): Command {
- const cmd = new Command("update")
- .description("Update CLI to the latest version")
- .action(async () => {
- const current = getCurrentVersion();
- console.log(`Current version: ${current}`);
-
- const latest = await fetchLatestVersion();
- if (!latest) {
- console.error("Failed to fetch latest version from npm registry.");
- process.exit(1);
- return;
- }
-
- if (semverGte(current, latest)) {
- console.log(`Already up to date (v${current}).`);
- return;
- }
-
- // Check if daemon is running
- const healthPort = Number(process.env.ALOOK_HEALTH_PORT) || 19514;
- try {
- const res = await fetch(`http://127.0.0.1:${healthPort}/health`);
- if (res.ok) {
- console.warn(
- "Warning: daemon is running on the old version. After update, restart with: alook daemon restart",
- );
- }
- } catch {
- // daemon not running — fine
- }
-
- console.log(`Updating to v${latest}...`);
- const result = await runNpmUpdate(latest);
- if (result.success) {
- console.log(`Updated successfully: v${current} → v${latest}`);
- } else {
- console.error(`Update failed:\n${result.output}`);
- process.exit(1);
- }
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/version.ts b/src/cli/commands/version.ts
deleted file mode 100644
index e16b3ac94..000000000
--- a/src/cli/commands/version.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { Command } from "commander";
-import { getCurrentVersion } from "../lib/version.js";
-
-export function versionCommand(): Command {
- const cmd = new Command("version")
- .description("Show CLI version")
- .action(() => {
- console.log(`alook version ${getCurrentVersion()}`);
- });
-
- return cmd;
-}
diff --git a/src/cli/commands/workspace.test.ts b/src/cli/commands/workspace.test.ts
deleted file mode 100644
index 53412ff17..000000000
--- a/src/cli/commands/workspace.test.ts
+++ /dev/null
@@ -1,462 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { mkdirSync, writeFileSync, rmSync } from "fs";
-import { join } from "path";
-
-const { getJSONMock, postJSONMock } = vi.hoisted(() => ({
- getJSONMock: vi.fn(),
- postJSONMock: vi.fn(),
-}));
-
-vi.mock("../lib/client.js", () => ({
- APIClient: class {
- getJSON(...a: unknown[]) { return getJSONMock(...a); }
- postJSON(...a: unknown[]) { return postJSONMock(...a); }
- },
-}));
-
-vi.mock("../lib/resolve-client.js", () => ({
- resolveClientOpts: vi.fn(() => ({
- serverUrl: "http://localhost:3000",
- token: "test-token",
- workspaceId: "ws_test",
- })),
- resolveClientOptsPartial: vi.fn(() => ({
- serverUrl: "http://localhost:3000",
- token: "test-token",
- workspaceId: "ws_test",
- })),
-}));
-
-vi.mock("../lib/config.js", () => ({
- loadCLIConfigForProfile: vi.fn(() => ({
- server_url: "http://localhost:3000",
- watched_workspaces: [{ id: "ws_test", name: "Test", token: "test-token", status: "active" }],
- })),
- saveCLIConfigForProfile: vi.fn(),
-}));
-
-vi.mock("../lib/command-utils.js", () => ({
- getRootOpts: vi.fn(() => ({})),
-}));
-
-import { workspaceCommand } from "./workspace";
-import { resolveClientOptsPartial } from "../lib/resolve-client.js";
-import { loadCLIConfigForProfile } from "../lib/config.js";
-
-const mockedResolvePartial = vi.mocked(resolveClientOptsPartial);
-const mockedLoadConfig = vi.mocked(loadCLIConfigForProfile);
-
-const TMP_DIR = "/tmp/alook-workspace-test";
-
-describe("workspace init", () => {
- let consoleSpy: ReturnType<typeof vi.spyOn>;
- let consoleErrSpy: ReturnType<typeof vi.spyOn>;
- let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
- let mockExit: ReturnType<typeof vi.spyOn>;
-
- beforeEach(() => {
- vi.clearAllMocks();
- mkdirSync(TMP_DIR, { recursive: true });
- consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
- consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
- mockExit = vi.spyOn(process, "exit").mockImplementation((code) => { throw new Error(`process.exit(${code})`); });
- });
-
- afterEach(() => {
- rmSync(TMP_DIR, { recursive: true, force: true });
- consoleSpy.mockRestore();
- consoleErrSpy.mockRestore();
- consoleWarnSpy.mockRestore();
- mockExit.mockRestore();
- });
-
- function writeJson(filename: string, data: unknown) {
- const path = join(TMP_DIR, filename);
- writeFileSync(path, JSON.stringify(data));
- return path;
- }
-
- async function runInit(args: string[]) {
- const cmd = workspaceCommand();
- await cmd.parseAsync(["node", "workspace", "init", ...args]);
- }
-
- it("reads local JSON file and creates workspace", async () => {
- const jsonPath = writeJson("valid.json", {
- name: "Test WS",
- members: [
- { role: "leader", instructions: "You lead" },
- { role: "engineer", instructions: "You code", relationship: "delegate\n\nreport" },
- ],
- });
-
- getJSONMock
- .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]) // runtimes
- .mockResolvedValueOnce([]); // agents (empty = no existing agents)
-
- postJSONMock.mockResolvedValueOnce({
- studio: { name: "Test WS" },
- workspace: { id: "ws_test", name: "Test WS", slug: "test-ws" },
- agents: [
- { id: "ag1", name: "Alice", email_handle: "alice" },
- { id: "ag2", name: "Bob", email_handle: "bob" },
- ],
- links: [],
- });
-
- await runInit(["--json-file", jsonPath]);
-
- expect(postJSONMock).toHaveBeenCalledWith("/api/studios", expect.objectContaining({
- name: "Test WS",
- members: expect.arrayContaining([
- expect.objectContaining({ role: "leader", runtime_id: "rt1" }),
- ]),
- }));
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Workspace initialized"));
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("[email protected]"));
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("http://localhost:3000/w/test-ws"));
- });
-
- it("errors when JSON file does not exist", async () => {
- await expect(runInit(["--json-file", "/tmp/nonexistent-file.json"])).rejects.toThrow("process.exit(1)");
- expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("cannot read file"));
- });
-
- it("errors when JSON is malformed", async () => {
- const path = join(TMP_DIR, "bad.json");
- writeFileSync(path, "not json {{{");
-
- await expect(runInit(["--json-file", path])).rejects.toThrow("process.exit(1)");
- expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("invalid JSON"));
- });
-
- it("errors when members array is missing", async () => {
- const jsonPath = writeJson("no-members.json", { name: "Test" });
-
- await expect(runInit(["--json-file", jsonPath])).rejects.toThrow("process.exit(1)");
- expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("members"));
- });
-
- it("errors when no runtimes are registered", async () => {
- const jsonPath = writeJson("valid.json", {
- members: [{ role: "leader", instructions: "x" }],
- });
-
- getJSONMock.mockResolvedValueOnce([]); // empty runtimes
-
- await expect(runInit(["--json-file", jsonPath])).rejects.toThrow("process.exit(1)");
- expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("No daemon registered"));
- });
-
- it("creates new workspace and re-fetches runtimes from it", async () => {
- const jsonPath = writeJson("valid.json", {
- name: "New WS",
- members: [{ role: "leader", instructions: "x" }],
- });
-
- getJSONMock
- .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]) // runtimes (old ws)
- .mockResolvedValueOnce([{ id: "existing-agent" }]) // existing agents
- .mockResolvedValueOnce([{ id: "rt_new", machineLastSeenAt: new Date().toISOString() }]); // runtimes (new ws)
-
- postJSONMock
- .mockResolvedValueOnce({ id: "ws_new", name: "New WS" }) // POST /api/workspaces
- .mockResolvedValueOnce({ // POST /api/studios
- studio: { name: "New WS" },
- workspace: { id: "ws_new", name: "New WS", slug: "new-ws" },
- agents: [{ id: "ag1", name: "Charlie", email_handle: "charlie" }],
- links: [],
- });
-
- await runInit(["--json-file", jsonPath]);
-
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("existing agents"));
- expect(postJSONMock).toHaveBeenCalledWith("/api/workspaces", expect.objectContaining({ name: "New WS" }));
- expect(postJSONMock).toHaveBeenCalledWith("/api/studios", expect.objectContaining({
- members: expect.arrayContaining([
- expect.objectContaining({ runtime_id: "rt_new" }),
- ]),
- }));
- });
-
- it("registers runtime in new workspace when none exist there", async () => {
- const jsonPath = writeJson("valid.json", {
- name: "Fresh WS",
- members: [{ role: "leader", instructions: "x" }],
- });
-
- getJSONMock
- .mockResolvedValueOnce([{ id: "rt_orig", machineLastSeenAt: new Date().toISOString() }]) // runtimes (old ws)
- .mockResolvedValueOnce([{ id: "existing-agent" }]) // existing agents
- .mockResolvedValueOnce([]); // runtimes (new ws) — empty
-
- postJSONMock
- .mockResolvedValueOnce({ id: "ws_fresh", name: "Fresh WS" }) // POST /api/workspaces
- .mockResolvedValueOnce(undefined) // POST /api/runtimes (register)
- .mockResolvedValueOnce({ // POST /api/studios
- studio: { name: "Fresh WS" },
- workspace: { id: "ws_fresh", name: "Fresh WS", slug: "fresh-ws" },
- agents: [{ id: "ag1", name: "Dave", email_handle: "dave" }],
- links: [],
- });
-
- await runInit(["--json-file", jsonPath]);
-
- expect(postJSONMock).toHaveBeenCalledWith("/api/runtimes", { id: "rt_orig" });
- expect(postJSONMock).toHaveBeenCalledWith("/api/studios", expect.objectContaining({
- members: expect.arrayContaining([
- expect.objectContaining({ runtime_id: "rt_orig" }),
- ]),
- }));
- });
-
- it("warns but continues when runtime re-fetch fails in new workspace", async () => {
- const jsonPath = writeJson("valid.json", {
- name: "Warn WS",
- members: [{ role: "leader", instructions: "x" }],
- });
-
- getJSONMock
- .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]) // runtimes (old ws)
- .mockResolvedValueOnce([{ id: "existing-agent" }]) // existing agents
- .mockRejectedValueOnce(new Error("timeout")); // runtimes (new ws) fails
-
- postJSONMock
- .mockResolvedValueOnce({ id: "ws_warn", name: "Warn WS" }) // POST /api/workspaces
- .mockResolvedValueOnce({ // POST /api/studios
- studio: { name: "Warn WS" },
- workspace: { id: "ws_warn", name: "Warn WS", slug: "warn-ws" },
- agents: [{ id: "ag1", name: "Eve", email_handle: "eve" }],
- links: [],
- });
-
- await runInit(["--json-file", jsonPath]);
-
- expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("could not refresh runtimes"));
- expect(postJSONMock).toHaveBeenCalledWith("/api/studios", expect.objectContaining({
- members: expect.arrayContaining([
- expect.objectContaining({ runtime_id: "rt1" }),
- ]),
- }));
- });
-
- it("warns when agent existence check fails", async () => {
- const jsonPath = writeJson("valid.json", {
- members: [{ role: "leader", instructions: "x" }],
- });
-
- getJSONMock
- .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]) // runtimes
- .mockRejectedValueOnce(new Error("network error")); // agents check fails
-
- postJSONMock.mockResolvedValueOnce({
- studio: { name: "" },
- workspace: { id: "ws_test", name: "Workspace", slug: "workspace" },
- agents: [{ id: "ag1", name: "X", email_handle: "x" }],
- links: [],
- });
-
- await runInit(["--json-file", jsonPath]);
-
- expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("could not check existing agents"));
- });
-
- it("errors when runtime fetch fails", async () => {
- const jsonPath = writeJson("valid.json", {
- members: [{ role: "leader", instructions: "x" }],
- });
-
- getJSONMock.mockRejectedValueOnce(new Error("connection refused"));
-
- await expect(runInit(["--json-file", jsonPath])).rejects.toThrow("process.exit(1)");
- expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("failed to fetch runtimes"));
- });
-
- it("errors when studios POST fails", async () => {
- const jsonPath = writeJson("valid.json", {
- members: [{ role: "leader", instructions: "x" }],
- });
-
- getJSONMock
- .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }])
- .mockResolvedValueOnce([]);
-
- postJSONMock.mockRejectedValueOnce(new Error("500 internal server error"));
-
- await expect(runInit(["--json-file", jsonPath])).rejects.toThrow("process.exit(1)");
- expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("failed to create workspace"));
- });
-
- it("selects online runtime over offline one", async () => {
- const jsonPath = writeJson("valid.json", {
- members: [{ role: "leader", instructions: "x" }],
- });
-
- const oldDate = new Date(Date.now() - 10 * 60 * 1000).toISOString(); // 10 min ago (offline)
- const recentDate = new Date().toISOString(); // now (online)
-
- getJSONMock
- .mockResolvedValueOnce([
- { id: "rt_offline", machineLastSeenAt: oldDate },
- { id: "rt_online", machineLastSeenAt: recentDate },
- ])
- .mockResolvedValueOnce([]); // no existing agents
-
- postJSONMock.mockResolvedValueOnce({
- studio: { name: "" },
- workspace: { id: "ws_test", name: "WS", slug: "ws" },
- agents: [{ id: "ag1", name: "Y", email_handle: "y" }],
- links: [],
- });
-
- await runInit(["--json-file", jsonPath]);
-
- // The online runtime should be selected
- expect(postJSONMock).toHaveBeenCalledWith("/api/studios", expect.objectContaining({
- members: expect.arrayContaining([
- expect.objectContaining({ runtime_id: "rt_online" }),
- ]),
- }));
- });
-});
-
-describe("workspace init — self-resolve (no workspaceId)", () => {
- let consoleSpy: ReturnType<typeof vi.spyOn>;
- let consoleErrSpy: ReturnType<typeof vi.spyOn>;
- let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
- let mockExit: ReturnType<typeof vi.spyOn>;
-
- beforeEach(() => {
- vi.clearAllMocks();
- mkdirSync(TMP_DIR, { recursive: true });
- consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
- consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
- mockExit = vi.spyOn(process, "exit").mockImplementation((code) => { throw new Error(`process.exit(${code})`); });
-
- // Return no workspaceId — triggers self-resolve path
- mockedResolvePartial.mockReturnValue({
- serverUrl: "http://localhost:3000",
- token: "test-token",
- workspaceId: undefined,
- });
- mockedLoadConfig.mockReturnValue({
- server_url: "http://localhost:3000",
- watched_workspaces: [{ id: "sp_ws1", name: "Existing", token: "test-token", status: "active" }],
- });
- });
-
- afterEach(() => {
- rmSync(TMP_DIR, { recursive: true, force: true });
- consoleSpy.mockRestore();
- consoleErrSpy.mockRestore();
- consoleWarnSpy.mockRestore();
- mockExit.mockRestore();
- });
-
- function writeJson(filename: string, data: unknown) {
- const path = join(TMP_DIR, filename);
- writeFileSync(path, JSON.stringify(data));
- return path;
- }
-
- async function runInit(args: string[]) {
- const cmd = workspaceCommand();
- await cmd.parseAsync(["node", "workspace", "init", ...args]);
- }
-
- it("finds empty workspace from server and uses it", async () => {
- const jsonPath = writeJson("valid.json", {
- name: "My WS",
- members: [{ role: "leader", instructions: "You lead" }],
- });
-
- getJSONMock
- .mockResolvedValueOnce([{ id: "sp_ws1", name: "Existing WS" }]) // GET /api/workspaces
- .mockResolvedValueOnce([]) // GET /api/agents?workspace_id=sp_ws1 (empty!)
- .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]); // GET /api/runtimes
-
- postJSONMock
- .mockResolvedValueOnce({ // POST /api/studios
- studio: { name: "My WS" },
- workspace: { id: "sp_ws1", name: "My WS", slug: "my-ws" },
- agents: [{ id: "ag1", name: "Leader", email_handle: "leader" }],
- });
-
- await runInit(["--json-file", jsonPath]);
-
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Workspace initialized"));
- });
-
- it("creates new workspace when all existing ones have agents", async () => {
- const jsonPath = writeJson("valid.json", {
- name: "Fresh WS",
- members: [{ role: "leader", instructions: "You lead" }],
- });
-
- getJSONMock
- .mockResolvedValueOnce([{ id: "sp_ws1", name: "Full WS" }]) // GET /api/workspaces
- .mockResolvedValueOnce([{ id: "ag_existing" }]) // GET /api/agents?workspace_id=sp_ws1 (has agents)
- .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]); // GET /api/runtimes (polling)
-
- postJSONMock
- .mockResolvedValueOnce({ id: "sp_new", name: "Fresh WS" }) // POST /api/workspaces
- .mockResolvedValueOnce({ // POST /api/studios
- studio: { name: "Fresh WS" },
- workspace: { id: "sp_new", name: "Fresh WS", slug: "fresh-ws" },
- agents: [{ id: "ag1", name: "Leader", email_handle: "leader" }],
- });
-
- await runInit(["--json-file", jsonPath]);
-
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Created workspace"));
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Workspace initialized"));
- });
-
- it("creates workspace with 'Personal' name when no name configured", async () => {
- const jsonPath = writeJson("valid.json", {
- members: [{ role: "leader", instructions: "You lead" }],
- });
-
- getJSONMock
- .mockResolvedValueOnce([]) // GET /api/workspaces (empty — new user)
- .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]); // GET /api/runtimes
-
- postJSONMock
- .mockResolvedValueOnce({ id: "sp_personal", name: "Personal" }) // POST /api/workspaces
- .mockResolvedValueOnce({ // POST /api/studios
- studio: { name: "Personal" },
- workspace: { id: "sp_personal", name: "Personal", slug: "personal" },
- agents: [{ id: "ag1", name: "Leader", email_handle: "leader" }],
- });
-
- await runInit(["--json-file", jsonPath]);
-
- expect(postJSONMock).toHaveBeenCalledWith("/api/workspaces", expect.objectContaining({ name: "Personal" }));
- });
-
- it("polls for runtimes and errors if none appear", async () => {
- vi.useFakeTimers();
- const jsonPath = writeJson("valid.json", {
- members: [{ role: "leader", instructions: "x" }],
- });
-
- getJSONMock
- .mockResolvedValueOnce([{ id: "sp_ws1", name: "WS" }]) // GET /api/workspaces
- .mockResolvedValueOnce([]) // GET /api/agents (empty)
- .mockResolvedValue([]); // GET /api/runtimes (always empty)
-
- postJSONMock.mockResolvedValueOnce({}); // POST /api/machine-tokens/bind-workspace
-
- const promise = runInit(["--json-file", jsonPath]).catch((e) => e);
- for (let i = 0; i < 20; i++) {
- await vi.advanceTimersByTimeAsync(1100);
- }
- const err = await promise;
- expect(err).toBeInstanceOf(Error);
- expect((err as Error).message).toBe("process.exit(1)");
- expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("No daemon registered after waiting"));
- vi.useRealTimers();
- });
-});
diff --git a/src/cli/commands/workspace.ts b/src/cli/commands/workspace.ts
deleted file mode 100644
index 48432de24..000000000
--- a/src/cli/commands/workspace.ts
+++ /dev/null
@@ -1,268 +0,0 @@
-import { Command } from "commander";
-import { readFileSync } from "fs";
-import { toAlookAddress, sanitizeSlug } from "@alook/shared";
-import { APIClient } from "../lib/client.js";
-import { cmdPrefix } from "../lib/env.js";
-import { printJSON } from "../lib/output.js";
-import { resolveClientOptsPartial } from "../lib/resolve-client.js";
-import { loadCLIConfigForProfile, saveCLIConfigForProfile, markWorkspaceActive } from "../lib/config.js";
-import { getRootOpts } from "../lib/command-utils.js";
-
-interface RuntimeResponse {
- id: string;
- machineLastSeenAt?: string | null;
-}
-
-interface WorkspaceResponse {
- id: string;
- name: string;
-}
-
-interface StudioResponse {
- studio: { name: string };
- workspace: { id: string; name: string; slug: string };
- agents: Array<{ id: string; name: string; email_handle: string | null }>;
-}
-
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-async function resolveWorkspaceId(client: APIClient, configName?: string): Promise<{ workspaceId: string; created: boolean }> {
- let workspaces: WorkspaceResponse[];
- try {
- workspaces = await client.getJSON<WorkspaceResponse[]>("/api/workspaces");
- } catch (err) {
- console.error(`Error: failed to fetch workspaces: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
-
- // Find an empty workspace (no agents)
- for (const ws of workspaces) {
- try {
- const agents = await client.getJSON<Array<{ id: string }>>(`/api/agents?workspace_id=${ws.id}`);
- if (agents.length === 0) {
- return { workspaceId: ws.id, created: false };
- }
- } catch {
- // Skip workspaces we can't check
- }
- }
-
- // No empty workspace — create one
- const wsName = configName || "Personal";
- try {
- const newWs = await client.postJSON<{ id: string; name: string }>("/api/workspaces", { name: wsName, slug: sanitizeSlug(wsName) });
- console.log(`Created workspace: ${newWs.name} (${newWs.id})`);
- return { workspaceId: newWs.id, created: true };
- } catch (err) {
- console.error(`Error: failed to create workspace: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
-}
-
-export function workspaceCommand(): Command {
- const cmd = new Command("workspace").description("Manage workspaces");
-
- cmd
- .command("init")
- .description("Initialize a workspace from a JSON configuration file")
- .requiredOption("--json-file <path>", "Path to the JSON configuration file")
- .option("--name <name>", "Workspace name (overrides JSON)")
- .option("--json", "Output as JSON")
- .action(async (opts, command) => {
- const { serverUrl, token, workspaceId: resolvedWorkspaceId } = resolveClientOptsPartial(command);
- const client = new APIClient(serverUrl, token, resolvedWorkspaceId);
-
- // Read local JSON file
- let configJson: string;
- try {
- configJson = readFileSync(opts.jsonFile, "utf-8");
- } catch (err) {
- console.error(`Error: cannot read file '${opts.jsonFile}': ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
-
- let config: { name?: string; scenario?: string; members: Array<Record<string, unknown>> };
- try {
- config = JSON.parse(configJson);
- } catch {
- console.error("Error: invalid JSON in configuration file");
- process.exit(1);
- }
-
- if (!config.members || !Array.isArray(config.members) || config.members.length === 0) {
- console.error("Error: JSON must contain a 'members' array with at least one member");
- process.exit(1);
- }
-
- // Self-resolve workspace if not available from config/env
- const parentOpts = getRootOpts(command) as { profile?: string };
- let targetWorkspaceId = resolvedWorkspaceId;
- if (!targetWorkspaceId) {
- const resolved = await resolveWorkspaceId(client, opts.name || config.name);
- targetWorkspaceId = resolved.workspaceId;
-
- // Poll for runtime to appear
- let runtimes: RuntimeResponse[] = [];
- const wsClient = new APIClient(serverUrl, token, targetWorkspaceId);
- for (let attempt = 0; attempt < 15; attempt++) {
- try {
- runtimes = await wsClient.getJSON<RuntimeResponse[]>("/api/runtimes");
- if (runtimes.length > 0) break;
- } catch {
- // Retry
- }
- await sleep(1000);
- }
-
- if (runtimes.length === 0) {
- console.error(`Error: No daemon registered after waiting. Run '${cmdPrefix()} daemon start' first.`);
- process.exit(1);
- }
-
- // Pick runtime and continue
- const OFFLINE_THRESHOLD_MS = 5 * 60 * 1000;
- const now = Date.now();
- const onlineRuntime = runtimes.find((r) => {
- if (!r.machineLastSeenAt) return false;
- const lastSeen = new Date(r.machineLastSeenAt.includes("Z") ? r.machineLastSeenAt : r.machineLastSeenAt + "Z").getTime();
- return now - lastSeen < OFFLINE_THRESHOLD_MS;
- });
- const runtime = onlineRuntime || runtimes[0];
-
- const members = config.members.map((m) => ({
- ...m,
- runtime_id: runtime.id,
- }));
-
- const payload = {
- name: opts.name || config.name,
- scenario: config.scenario,
- members,
- };
-
- try {
- const res = await wsClient.postJSON<StudioResponse>("/api/studios", payload);
-
- // Update local config with the resolved workspace
- try {
- const freshCfg = loadCLIConfigForProfile(parentOpts.profile);
- freshCfg.watched_workspaces = markWorkspaceActive(freshCfg.watched_workspaces || [], {
- id: targetWorkspaceId,
- name: res.workspace.name,
- token,
- });
- saveCLIConfigForProfile(parentOpts.profile, freshCfg);
- } catch {
- // Best-effort config update
- }
-
- if (opts.json) return printJSON(res);
-
- console.log(`\nWorkspace initialized: ${res.studio.name || res.workspace.name}`);
- console.log("Agents created:");
- for (const agent of res.agents) {
- const email = agent.email_handle ? toAlookAddress(agent.email_handle) : "no email";
- console.log(` - ${agent.name} (${email})`);
- }
- console.log(`\n Open: ${serverUrl}/w/${res.workspace.slug}`);
- } catch (err) {
- console.error(`Error: failed to create workspace: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- return;
- }
-
- // Existing path: workspace was resolved from config/env
- let targetClient = new APIClient(serverUrl, token, targetWorkspaceId);
-
- // Get runtimes for this workspace
- let runtimes: RuntimeResponse[];
- try {
- runtimes = await targetClient.getJSON<RuntimeResponse[]>("/api/runtimes");
- } catch (err) {
- console.error(`Error: failed to fetch runtimes: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
-
- if (runtimes.length === 0) {
- console.error(`Error: No daemon registered. Run '${cmdPrefix()} daemon start' first.`);
- process.exit(1);
- }
-
- // Pick the first online runtime, or first one if none are online
- const OFFLINE_THRESHOLD_MS = 5 * 60 * 1000;
- const now = Date.now();
- const onlineRuntime = runtimes.find((r) => {
- if (!r.machineLastSeenAt) return false;
- const lastSeen = new Date(r.machineLastSeenAt.includes("Z") ? r.machineLastSeenAt : r.machineLastSeenAt + "Z").getTime();
- return now - lastSeen < OFFLINE_THRESHOLD_MS;
- });
- let runtime = onlineRuntime || runtimes[0];
-
- // Check if workspace already has agents — if so, create a new workspace
- try {
- const agents = await targetClient.getJSON<Array<{ id: string }>>(`/api/agents?workspace_id=${targetWorkspaceId}`);
- if (agents.length > 0) {
- console.log("Current workspace has existing agents. Creating a new workspace...");
- const wsName = opts.name || config.name || "New Workspace";
- const newWs = await targetClient.postJSON<{ id: string; name: string }>("/api/workspaces", { name: wsName, slug: sanitizeSlug(wsName) });
- targetWorkspaceId = newWs.id;
- targetClient = new APIClient(serverUrl, token, targetWorkspaceId);
- console.log(`Created workspace: ${newWs.name} (${newWs.id})`);
-
- // Re-fetch runtimes scoped to the new workspace
- try {
- const newRuntimes = await targetClient.getJSON<RuntimeResponse[]>("/api/runtimes");
- if (newRuntimes.length > 0) {
- const newOnlineRuntime = newRuntimes.find((r) => {
- if (!r.machineLastSeenAt) return false;
- const lastSeen = new Date(r.machineLastSeenAt.includes("Z") ? r.machineLastSeenAt : r.machineLastSeenAt + "Z").getTime();
- return now - lastSeen < OFFLINE_THRESHOLD_MS;
- });
- runtime = newOnlineRuntime || newRuntimes[0];
- } else {
- await targetClient.postJSON("/api/runtimes", { id: runtime.id });
- }
- } catch (err) {
- console.warn(`Warning: could not refresh runtimes for new workspace: ${err instanceof Error ? err.message : err}`);
- }
- }
- } catch (err) {
- console.warn(`Warning: could not check existing agents: ${err instanceof Error ? err.message : err}`);
- }
-
- // Inject runtime_id into each member
- const members = config.members.map((m) => ({
- ...m,
- runtime_id: runtime.id,
- }));
-
- const payload = {
- name: opts.name || config.name,
- scenario: config.scenario,
- members,
- };
-
- // POST to /api/studios
- try {
- const res = await targetClient.postJSON<StudioResponse>("/api/studios", payload);
-
- if (opts.json) return printJSON(res);
-
- console.log(`\nWorkspace initialized: ${res.studio.name || res.workspace.name}`);
- console.log("Agents created:");
- for (const agent of res.agents) {
- const email = agent.email_handle ? toAlookAddress(agent.email_handle) : "no email";
- console.log(` - ${agent.name} (${email})`);
- }
- console.log(`\n Open: ${serverUrl}/w/${res.workspace.slug}`);
- } catch (err) {
- console.error(`Error: failed to create workspace: ${err instanceof Error ? err.message : err}`);
- process.exit(1);
- }
- });
-
- return cmd;
-}
diff --git a/src/cli/daemon/agent/__tests__/claude.parseLine.test.ts b/src/cli/daemon/agent/__tests__/claude.parseLine.test.ts
deleted file mode 100644
index 262e2fc2b..000000000
--- a/src/cli/daemon/agent/__tests__/claude.parseLine.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { ClaudeBackend } from "../claude.js";
-
-const backend = new ClaudeBackend("claude");
-
-describe("ClaudeBackend.parseLine", () => {
- it("empty line returns empty", () => {
- expect(backend.parseLine("")).toEqual([]);
- expect(backend.parseLine(" ")).toEqual([]);
- });
-
- it("invalid JSON returns log event", () => {
- const events = backend.parseLine("not json");
- expect(events).toHaveLength(1);
- expect(events[0].kind).toBe("log");
- });
-
- it("system init → session_init", () => {
- const line = JSON.stringify({ type: "system", subtype: "init", session_id: "sess-123" });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "session_init", sessionId: "sess-123" }]);
- });
-
- it("assistant text → text", () => {
- const line = JSON.stringify({
- type: "assistant",
- message: { content: [{ type: "text", text: "hello world" }] },
- });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "text", text: "hello world" }]);
- });
-
- it("assistant thinking → thinking", () => {
- const line = JSON.stringify({
- type: "assistant",
- message: { content: [{ type: "thinking", text: "let me think" }] },
- });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "thinking", text: "let me think" }]);
- });
-
- it("assistant tool_use → tool_call", () => {
- const line = JSON.stringify({
- type: "assistant",
- message: { content: [{ type: "tool_use", name: "Bash", id: "tc-1", input: { command: "ls" } }] },
- });
- const events = backend.parseLine(line);
- expect(events).toEqual([{
- kind: "tool_call",
- name: "Bash",
- callId: "tc-1",
- input: { command: "ls" },
- }]);
- });
-
- it("tool_result → tool_output", () => {
- const line = JSON.stringify({ type: "tool_result", tool_use_id: "tc-1", content: "file.txt" });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "tool_output", callId: "tc-1", output: "file.txt" }]);
- });
-
- it("result → turn_end with sessionId + enriched telemetry", () => {
- const line = JSON.stringify({
- type: "result",
- result: "done",
- session_id: "s1",
- usage: {
- input_tokens: 100,
- output_tokens: 50,
- cache_read_input_tokens: 20,
- cache_creation_input_tokens: 10,
- service_tier: "default",
- },
- total_cost_usd: 0.005,
- duration_ms: 1200,
- });
- const events = backend.parseLine(line);
- expect(events).toHaveLength(2);
- expect(events[0]).toEqual({ kind: "turn_end", sessionId: "s1" });
- expect(events[1].kind).toBe("telemetry");
- const telemetry = events[1] as { kind: "telemetry"; attrs: Record<string, unknown>; source?: string };
- expect(telemetry.source).toBe("claude_result_usage");
- expect(telemetry.attrs.cachedInputTokens).toBe(20);
- expect(telemetry.attrs.cacheCreationInputTokens).toBe(10);
- expect(telemetry.attrs.totalCostUsd).toBe(0.005);
- expect(telemetry.attrs.serviceTier).toBe("default");
- });
-
- it("result with is_error → error + turn_end", () => {
- const line = JSON.stringify({ type: "result", result: "something broke", is_error: true });
- const events = backend.parseLine(line);
- expect(events[0]).toEqual({ kind: "error", message: "something broke" });
- expect(events[1].kind).toBe("turn_end");
- });
-
- it("turn_end carries sessionId from result", () => {
- const line = JSON.stringify({ type: "result", result: "ok", session_id: "s42" });
- const events = backend.parseLine(line);
- const turnEnd = events.find((e) => e.kind === "turn_end") as { kind: "turn_end"; sessionId?: string };
- expect(turnEnd.sessionId).toBe("s42");
- });
-
- it("control_request → permission_request", () => {
- const line = JSON.stringify({ type: "control_request", request_id: "req-1", payload: { tool: "Bash" } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{
- kind: "permission_request",
- requestId: "req-1",
- payload: { tool: "Bash" },
- }]);
- });
-
- it("system compaction → compaction_started", () => {
- const line = JSON.stringify({ type: "system", subtype: "compaction" });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "compaction_started" }]);
- });
-
- it("system context_pruning → compaction_started", () => {
- const line = JSON.stringify({ type: "system", subtype: "context_pruning" });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "compaction_started" }]);
- });
-
- it("system compaction_finished → compaction_finished", () => {
- const line = JSON.stringify({ type: "system", subtype: "compaction_finished" });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "compaction_finished" }]);
- });
-
- it("system status → internal_progress with source and itemType", () => {
- const line = JSON.stringify({ type: "system", subtype: "status", status: "something" });
- const events = backend.parseLine(line);
- expect(events).toHaveLength(1);
- expect(events[0].kind).toBe("internal_progress");
- const ip = events[0] as { kind: "internal_progress"; source?: string; itemType?: string };
- expect(ip.source).toBe("claude_system");
- expect(ip.itemType).toBe("status");
- });
-
- it("system stream_event → internal_progress", () => {
- const line = JSON.stringify({ type: "system", subtype: "stream_event", data: {} });
- const events = backend.parseLine(line);
- expect(events).toHaveLength(1);
- expect(events[0].kind).toBe("internal_progress");
- const ip = events[0] as { kind: "internal_progress"; source?: string; itemType?: string };
- expect(ip.source).toBe("claude_system");
- expect(ip.itemType).toBe("stream_event");
- });
-});
-
-describe("ClaudeBackend.encodeStdinMessage", () => {
- it("encodes a user message", () => {
- const encoded = backend.encodeStdinMessage("hello", "idle");
- expect(encoded).not.toBeNull();
- const parsed = JSON.parse(encoded!);
- expect(parsed.type).toBe("user");
- expect(parsed.message.role).toBe("user");
- expect(parsed.message.content[0].text).toBe("hello");
- });
-
- it("includes session_id when provided", () => {
- const encoded = backend.encodeStdinMessage("hi", "busy", { sessionId: "s1" });
- const parsed = JSON.parse(encoded!);
- expect(parsed.session_id).toBe("s1");
- });
-});
diff --git a/src/cli/daemon/agent/__tests__/claude.test.ts b/src/cli/daemon/agent/__tests__/claude.test.ts
deleted file mode 100644
index b0f68328a..000000000
--- a/src/cli/daemon/agent/__tests__/claude.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { EventEmitter } from "events";
-import { Readable } from "stream";
-import { spawn } from "child_process";
-import type { AgentMessage } from "../../types.js";
-
-let currentMockProc: ReturnType<typeof createMockProc> | null = null;
-
-function createMockProc() {
- const stdinWrites: string[] = [];
- const stdout = new Readable({ read() {} });
- const stderr = new Readable({ read() {} });
- const proc = Object.assign(new EventEmitter(), {
- stdout,
- stderr,
- stdin: {
- write: (data: string) => {
- stdinWrites.push(data);
- return true;
- },
- },
- kill: vi.fn(),
- pid: 12345,
- });
- return { proc, stdout, stderr, stdinWrites };
-}
-
-vi.mock("child_process", () => ({
- spawn: vi.fn(() => {
- currentMockProc = createMockProc();
- return currentMockProc.proc;
- }),
-}));
-
-vi.mock("../../kill-tree.js", () => ({
- killProcessTree: vi.fn().mockResolvedValue(undefined),
- killGraceMs: () => 2000,
- isAlive: () => false,
-}));
-
-const tick = (ms = 15) => new Promise((r) => setTimeout(r, ms));
-
-async function collectMessages(
- messages: AsyncIterable<AgentMessage>,
- maxMessages = 50,
- timeoutMs = 500,
-): Promise<AgentMessage[]> {
- const collected: AgentMessage[] = [];
- const timeout = new Promise<void>((resolve) => setTimeout(resolve, timeoutMs));
- const iter = messages[Symbol.asyncIterator]();
- for (let i = 0; i < maxMessages; i++) {
- const next = iter.next();
- const result = await Promise.race([next, timeout.then(() => null)]);
- if (!result || result.done) break;
- collected.push(result.value);
- }
- return collected;
-}
-
-const { ClaudeBackend } = await import("../claude.js");
-
-describe("ClaudeBackend", () => {
- let backend: InstanceType<typeof ClaudeBackend>;
-
- beforeEach(() => {
- vi.clearAllMocks();
- currentMockProc = null;
- backend = new ClaudeBackend("/usr/bin/claude");
- });
-
- function getMock() {
- return currentMockProc!;
- }
-
- it("emits MessageText for assistant text blocks", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({
- type: "assistant",
- message: { content: [{ type: "text", text: "Hello world" }] },
- }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "Hello world" });
- });
-
- it("emits MessageThinking for thinking blocks", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({
- type: "assistant",
- message: { content: [{ type: "thinking", text: "Let me think..." }] },
- }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "thinking", content: "Let me think..." });
- });
-
- it("emits MessageToolUse for tool_use blocks", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({
- type: "assistant",
- message: {
- content: [
- { type: "tool_use", name: "read_file", id: "call_123", input: { path: "/tmp/test.txt" } },
- ],
- },
- }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({
- type: "tool-use",
- tool: "read_file",
- callId: "call_123",
- input: { path: "/tmp/test.txt" },
- });
- });
-
- it("emits MessageToolResult for tool_result events", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({ type: "tool_result", content: "file contents here", tool_use_id: "call_123" }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({
- type: "tool-result",
- callId: "call_123",
- output: "file contents here",
- });
- });
-
- it("writes correct control_request approval format", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({
- type: "control_request",
- request_id: "req_abc",
- payload: { input: '{"command":"ls"}' },
- }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- await session.result;
-
- const approvalWrite = mock.stdinWrites.find((w) => w.includes("control_response"));
- expect(approvalWrite).toBeDefined();
- const parsed = JSON.parse(approvalWrite!.trim());
- expect(parsed.type).toBe("control_response");
- expect(parsed.response.subtype).toBe("success");
- expect(parsed.response.request_id).toBe("req_abc");
- expect(parsed.response.response.behavior).toBe("allow");
- expect(parsed.response.response.updatedInput).toEqual({ command: "ls" });
- });
-
- it("does not write approval when request_id is missing", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "control_request" }) + "\n");
- await tick();
- mock.proc.emit("close", 0);
-
- await session.result;
-
- const approvalWrite = mock.stdinWrites.find((w) => w.includes("control_response"));
- expect(approvalWrite).toBeUndefined();
- });
-
- it("captures session ID from system event (subtype init)", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({ type: "system", subtype: "init", session_id: "sess_123" }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.sessionId).toBe("sess_123");
- });
-
- it("captures session ID from result event", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({ type: "result", result: "done", session_id: "sess_456" }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.sessionId).toBe("sess_456");
- });
-
- it("sets status to failed when result event has is_error", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({ type: "result", result: "something went wrong", is_error: true }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("failed");
- expect(result.error).toBe("something went wrong");
- });
-
- it("handles invalid JSON gracefully", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push("not json at all\n");
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "log", content: "not json at all", level: "debug" });
- });
-
- it("sets status to timeout when process is killed by timeout", async () => {
- vi.useFakeTimers();
- const killTree = await vi.importMock<typeof import("../../kill-tree.js")>("../../kill-tree.js");
- const session = backend.execute("hello", { cwd: "/tmp", timeout: 1000 });
- const mock = getMock();
-
- vi.advanceTimersByTime(1000);
- expect(killTree.killProcessTree).toHaveBeenCalledWith(12345);
-
- mock.proc.emit("close", null);
-
- const result = await session.result;
- expect(result.status).toBe("timeout");
- vi.useRealTimers();
- });
-
- it("TC8: spawns the CLI detached on POSIX so its group can be reaped", () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- expect(session.pid).toBe(12345);
- const opts = vi.mocked(spawn).mock.calls.at(-1)![2] as Record<string, unknown>;
- expect(opts.detached).toBe(process.platform !== "win32");
- });
-});
diff --git a/src/cli/daemon/agent/__tests__/codex.parseLine.test.ts b/src/cli/daemon/agent/__tests__/codex.parseLine.test.ts
deleted file mode 100644
index d94fdddb9..000000000
--- a/src/cli/daemon/agent/__tests__/codex.parseLine.test.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { CodexBackend } from "../codex.js";
-
-const backend = new CodexBackend("codex");
-
-describe("CodexBackend.parseLine — raw protocol", () => {
- it("empty line returns empty", () => {
- expect(backend.parseLine("")).toEqual([]);
- });
-
- it("invalid JSON returns log event", () => {
- const events = backend.parseLine("not json");
- expect(events[0].kind).toBe("log");
- });
-
- it("turn/completed → turn_end", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "turn/completed", params: { turn: { status: "completed" } } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "turn_end" }]);
- });
-
- it("turn/completed with error → error + turn_end", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "turn/completed", params: { turn: { status: "failed", error: { message: "oops" } } } });
- const events = backend.parseLine(line);
- expect(events[0]).toEqual({ kind: "error", message: "oops" });
- expect(events[1]).toEqual({ kind: "turn_end" });
- });
-
- it("item/completed agentMessage → text", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "agentMessage", text: "answer" } } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "text", text: "answer" }]);
- });
-
- it("item/started commandExecution → tool_call", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "commandExecution", id: "cmd-1" } } });
- const events = backend.parseLine(line);
- expect(events[0].kind).toBe("tool_call");
- expect((events[0] as { callId: string }).callId).toBe("cmd-1");
- });
-
- it("item/completed commandExecution → tool_output", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "commandExecution", id: "cmd-1", aggregatedOutput: "result" } } });
- const events = backend.parseLine(line);
- expect(events[0].kind).toBe("tool_output");
- expect((events[0] as { output: string }).output).toBe("result");
- });
-
- it("error notification → error", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "error", params: { error: { message: "bad things" }, willRetry: false } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "error", message: "bad things" }]);
- });
-
- it("error with willRetry=true emits nothing", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "error", params: { error: { message: "transient" }, willRetry: true } });
- const events = backend.parseLine(line);
- expect(events).toHaveLength(0);
- });
-
- it("thread/status/changed idle → turn_end", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "thread/status/changed", params: { status: { type: "idle" } } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "turn_end" }]);
- });
-
- it("response (has id, no method) returns empty", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", id: 1, result: {} });
- expect(backend.parseLine(line)).toEqual([]);
- });
-
- it("server request (has id AND method) returns empty", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "item/commandExecution/requestApproval", params: {} });
- expect(backend.parseLine(line)).toEqual([]);
- });
-
- // --- New event mappings ---
-
- it("item/started mcpToolCall → tool_call with mcp_ prefix", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "mcpToolCall", name: "readFile", id: "mcp-1" } } });
- const events = backend.parseLine(line);
- expect(events).toHaveLength(1);
- expect(events[0].kind).toBe("tool_call");
- expect((events[0] as { name: string }).name).toBe("mcp_readFile");
- });
-
- it("item/started webSearch → tool_call web_search", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "webSearch", id: "ws-1" } } });
- const events = backend.parseLine(line);
- expect(events).toHaveLength(1);
- expect(events[0].kind).toBe("tool_call");
- expect((events[0] as { name: string }).name).toBe("web_search");
- });
-
- it("item/started collabAgentToolCall → tool_call collab_agent", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "collabAgentToolCall", id: "ca-1" } } });
- const events = backend.parseLine(line);
- expect(events).toHaveLength(1);
- expect(events[0].kind).toBe("tool_call");
- expect((events[0] as { name: string }).name).toBe("collab_agent");
- });
-
- it("item/started contextCompaction → compaction_started", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "contextCompaction" } } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "compaction_started" }]);
- });
-
- it("item/completed reasoning → thinking", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "reasoning", text: "I think..." } } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "thinking", text: "I think..." }]);
- });
-
- it("item/completed mcpToolCall → tool_output", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "mcpToolCall", name: "readFile", id: "mcp-1", output: "file contents" } } });
- const events = backend.parseLine(line);
- expect(events).toHaveLength(1);
- expect(events[0].kind).toBe("tool_output");
- expect((events[0] as { name: string }).name).toBe("mcp_readFile");
- });
-
- it("item/completed contextCompaction → compaction_finished", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "contextCompaction" } } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "compaction_finished" }]);
- });
-
- it("item/agentMessage/delta → text (not internal_progress)", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "item/agentMessage/delta", params: { delta: "streaming..." } });
- const events = backend.parseLine(line);
- expect(events).toHaveLength(1);
- expect(events[0].kind).toBe("text");
- expect((events[0] as { text: string }).text).toBe("streaming...");
- });
-});
-
-describe("CodexBackend.parseLine — legacy protocol", () => {
- it("codex/event agent_message → text", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "codex/event", params: { type: "agent_message", text: "hello" } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "text", text: "hello" }]);
- });
-
- it("codex/event task_complete → turn_end", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "codex/event", params: { type: "task_complete" } });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "turn_end" }]);
- });
-
- it("codex/event exec_command_begin → tool_call", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "codex/event", params: { type: "exec_command_begin", id: "c1" } });
- const events = backend.parseLine(line);
- expect(events[0].kind).toBe("tool_call");
- });
-
- it("codex/event exec_command_end → tool_output", () => {
- const line = JSON.stringify({ jsonrpc: "2.0", method: "codex/event", params: { type: "exec_command_end", id: "c1", output: "done" } });
- const events = backend.parseLine(line);
- expect(events[0].kind).toBe("tool_output");
- });
-});
-
-describe("CodexBackend.encodeStdinMessage", () => {
- it("returns null without threadId", () => {
- expect(backend.encodeStdinMessage("hi", "idle")).toBeNull();
- });
-
- it("encodes idle mode as turn/start", () => {
- const encoded = backend.encodeStdinMessage("hi", "idle", { threadId: "t1", requestId: 5 });
- const parsed = JSON.parse(encoded!);
- expect(parsed.method).toBe("turn/start");
- expect(parsed.params.threadId).toBe("t1");
- expect(parsed.params.input[0].text).toBe("hi");
- });
-
- it("encodes busy mode as turn/steer", () => {
- const encoded = backend.encodeStdinMessage("hi", "busy", { threadId: "t1", requestId: 6 });
- const parsed = JSON.parse(encoded!);
- expect(parsed.method).toBe("turn/steer");
- });
-});
diff --git a/src/cli/daemon/agent/__tests__/codex.test.ts b/src/cli/daemon/agent/__tests__/codex.test.ts
deleted file mode 100644
index 6dcc68d11..000000000
--- a/src/cli/daemon/agent/__tests__/codex.test.ts
+++ /dev/null
@@ -1,997 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { EventEmitter } from "events";
-import { Readable } from "stream";
-import type { AgentMessage } from "../../types.js";
-
-let currentMockProc: ReturnType<typeof createMockProc> | null = null;
-let lastSpawnOpts: Record<string, unknown> | null = null;
-
-function createMockProc() {
- const stdinWrites: string[] = [];
- const stdout = new Readable({ read() {} });
- const stderr = new Readable({ read() {} });
- const stdinEnd = vi.fn();
- const proc = Object.assign(new EventEmitter(), {
- stdout,
- stderr,
- stdin: {
- write: (data: string) => {
- stdinWrites.push(data);
- return true;
- },
- end: stdinEnd,
- },
- kill: vi.fn(),
- pid: 12345,
- });
- return { proc, stdout, stderr, stdinWrites, stdinEnd };
-}
-
-vi.mock("child_process", () => ({
- spawn: vi.fn((_cmd: string, _args: string[], opts: Record<string, unknown>) => {
- lastSpawnOpts = opts;
- currentMockProc = createMockProc();
- return currentMockProc.proc;
- }),
-}));
-
-vi.mock("../../kill-tree.js", () => ({
- killProcessTree: vi.fn().mockResolvedValue(undefined),
- killGraceMs: () => 2000,
- isAlive: () => false,
-}));
-
-async function collectMessages(
- messages: AsyncIterable<AgentMessage>,
- maxMessages = 100,
- timeoutMs = 500,
-): Promise<AgentMessage[]> {
- const collected: AgentMessage[] = [];
- const timeout = new Promise<void>((resolve) => setTimeout(resolve, timeoutMs));
- const iter = messages[Symbol.asyncIterator]();
- for (let i = 0; i < maxMessages; i++) {
- const next = iter.next();
- const result = await Promise.race([next, timeout.then(() => null)]);
- if (!result || result.done) break;
- collected.push(result.value);
- }
- return collected;
-}
-
-const { CodexBackend, extractThreadID } = await import("../codex.js");
-
-function getMock() {
- return currentMockProc!;
-}
-
-function sendResponse(id: number, result: unknown) {
- getMock().stdout.push(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n");
-}
-
-function sendError(id: number, error: { code: number; message: string }) {
- getMock().stdout.push(JSON.stringify({ jsonrpc: "2.0", id, error }) + "\n");
-}
-
-function sendNotification(method: string, params?: Record<string, unknown>) {
- const msg: Record<string, unknown> = { jsonrpc: "2.0", method };
- if (params) msg.params = params;
- getMock().stdout.push(JSON.stringify(msg) + "\n");
-}
-
-function sendServerRequest(id: number, method: string, params?: Record<string, unknown>) {
- const msg: Record<string, unknown> = { jsonrpc: "2.0", id, method };
- if (params) msg.params = params;
- getMock().stdout.push(JSON.stringify(msg) + "\n");
-}
-
-async function completeHandshake(threadId = "thread_abc") {
- await tick();
- sendResponse(1, { capabilities: {} }); // initialize response
- await tick();
- sendResponse(2, { thread: { id: threadId } }); // thread/start response
- await tick();
- sendResponse(3, {}); // turn/start response
- await tick();
-}
-
-function tick(ms = 15) {
- return new Promise((r) => setTimeout(r, ms));
-}
-
-describe("extractThreadID", () => {
- it("extracts from nested response", () => {
- expect(extractThreadID({ result: { thread: { id: "t_1" } } })).toBe("t_1");
- });
-
- it("extracts from flat thread object", () => {
- expect(extractThreadID({ thread: { id: "t_2" } })).toBe("t_2");
- });
-
- it("returns empty string when missing", () => {
- expect(extractThreadID(null)).toBe("");
- expect(extractThreadID({})).toBe("");
- expect(extractThreadID({ thread: {} })).toBe("");
- });
-});
-
-describe("CodexBackend", () => {
- let backend: InstanceType<typeof CodexBackend>;
-
- beforeEach(() => {
- vi.clearAllMocks();
- currentMockProc = null;
- lastSpawnOpts = null;
- backend = new CodexBackend("/usr/bin/codex");
- });
-
- it("spawns codex with sandbox_mode=danger-full-access config override", async () => {
- const { spawn } = await import("child_process");
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- const spawnCall = (spawn as any).mock.calls[0];
- expect(spawnCall[1]).toEqual(["app-server", "--listen", "stdio://", "--config", "sandbox_mode=danger-full-access"]);
-
- mock.proc.emit("close", 0);
- await session.result;
- });
-
- it("sends structured initialize params", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await tick();
-
- const initWrite = mock.stdinWrites.find((w) => w.includes('"initialize"'));
- expect(initWrite).toBeDefined();
- const parsed = JSON.parse(initWrite!);
- expect(parsed.params.clientInfo.name).toBe("alook-daemon");
- expect(parsed.params.clientInfo.title).toBe("Alook Agent SDK");
- expect(parsed.params.capabilities.experimentalApi).toBe(true);
- expect(parsed.id).toBe(1);
-
- mock.proc.emit("close", 1);
- await session.result;
- });
-
- it("sends initialized notification after initialize response", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await tick();
- sendResponse(1, { capabilities: {} });
- await tick();
-
- const initializedWrite = mock.stdinWrites.find((w) => w.includes('"initialized"'));
- expect(initializedWrite).toBeDefined();
- const parsed = JSON.parse(initializedWrite!);
- expect(parsed.method).toBe("initialized");
- expect(parsed.id).toBeUndefined();
-
- mock.proc.emit("close", 1);
- await session.result;
- });
-
- it("thread/start includes danger-full-access sandbox and no developerInstructions", async () => {
- const session = backend.execute("hello", {
- cwd: "/tmp",
- model: "gpt-4",
- });
- const mock = getMock();
-
- await tick();
- sendResponse(1, {});
- await tick(30);
-
- const threadWrite = mock.stdinWrites.find((w) => w.includes('"thread/start"'));
- expect(threadWrite).toBeDefined();
- const parsed = JSON.parse(threadWrite!);
- expect(parsed.params.cwd).toBe("/tmp");
- expect(parsed.params.sandboxPolicy).toEqual({ type: "dangerFullAccess" });
- expect(parsed.params.approvalPolicy).toBe("never");
- expect(parsed.params.persistExtendedHistory).toBe(true);
- expect(parsed.params.experimentalRawEvents).toBe(false);
- expect(parsed.params.developerInstructions).toBeUndefined();
- expect(parsed.params.model).toBe("gpt-4");
-
- mock.proc.emit("close", 1);
- await session.result;
- });
-
- it("turn/start RPC sent with threadId and prompt", async () => {
- const session = backend.execute("do stuff", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake("thread_xyz");
-
- const turnWrite = mock.stdinWrites.find((w) => w.includes('"turn/start"'));
- expect(turnWrite).toBeDefined();
- const parsed = JSON.parse(turnWrite!);
- expect(parsed.params.threadId).toBe("thread_xyz");
- expect(parsed.params.input).toEqual([{ type: "text", text: "do stuff" }]);
-
- mock.proc.emit("close", 0);
- await session.result;
- });
-
- it("extracts session ID from thread/start response", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake("my_thread_id");
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.sessionId).toBe("my_thread_id");
- });
-
- it("JSON-RPC error response rejects pending request", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await tick();
- sendError(1, { code: -1, message: "init failed" });
- await tick(30);
-
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.status).toBe("failed");
- expect(result.error).toContain("init failed");
- });
-
- it("JSON-RPC error response (id + error, no method) routed to response resolution", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await tick();
- // Send error response — should NOT go to notification handler
- sendError(1, { code: -32600, message: "bad request" });
- await tick(30);
-
- mock.proc.emit("close", 1);
- const result = await session.result;
- expect(result.error).toContain("bad request");
- });
-
- it("routes server requests (id + method) to handleServerRequest", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendServerRequest(99, "item/commandExecution/requestApproval", {});
- await tick();
-
- const resp = mock.stdinWrites.find((w) => w.includes('"id":99') && w.includes('"decision"'));
- expect(resp).toBeDefined();
- expect(JSON.parse(resp!).result.decision).toBe("accept");
-
- mock.proc.emit("close", 0);
- await session.result;
- });
-
- it("sends {decision: accept} for item/fileChange/requestApproval", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendServerRequest(100, "item/fileChange/requestApproval", {});
- await tick();
-
- const resp = mock.stdinWrites.find((w) => w.includes('"id":100'));
- expect(JSON.parse(resp!).result.decision).toBe("accept");
-
- mock.proc.emit("close", 0);
- await session.result;
- });
-
- it("sends {decision: accept} for execCommandApproval", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendServerRequest(101, "execCommandApproval", {});
- await tick();
-
- const resp = mock.stdinWrites.find((w) => w.includes('"id":101'));
- expect(JSON.parse(resp!).result.decision).toBe("accept");
-
- mock.proc.emit("close", 0);
- await session.result;
- });
-
- it("sends {decision: accept} for applyPatchApproval", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendServerRequest(102, "applyPatchApproval", {});
- await tick();
-
- const resp = mock.stdinWrites.find((w) => w.includes('"id":102'));
- expect(JSON.parse(resp!).result.decision).toBe("accept");
-
- mock.proc.emit("close", 0);
- await session.result;
- });
-
- it("sends empty {} for unknown server requests", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendServerRequest(200, "unknown/method", {});
- await tick();
-
- const resp = mock.stdinWrites.find((w) => w.includes('"id":200'));
- expect(resp).toBeDefined();
- expect(JSON.parse(resp!).result).toEqual({});
-
- mock.proc.emit("close", 0);
- await session.result;
- });
-
- // Legacy protocol tests
- it("legacy codex/event — task_started emits status running", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("codex/event", { type: "task_started" });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).not.toContainEqual(expect.objectContaining({ type: "status" }));
- });
-
- it("legacy codex/event — agent_message emits MessageText", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("codex/event", { type: "agent_message", text: "I found the issue" });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "I found the issue" });
- });
-
- it("legacy codex/event — exec_command_begin/end emits tool-use + tool-result", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("codex/event", { type: "exec_command_begin", id: "cmd_1", command: "ls" });
- sendNotification("codex/event", { type: "exec_command_end", id: "cmd_1", output: "total 0" });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual(
- expect.objectContaining({ type: "tool-use", tool: "exec_command", callId: "cmd_1" }),
- );
- expect(messages).toContainEqual(
- expect.objectContaining({ type: "tool-result", callId: "cmd_1", output: "total 0" }),
- );
- });
-
- it("legacy codex/event — patch_apply_begin/end emits tool-use + tool-result", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("codex/event", { type: "patch_apply_begin", id: "patch_1" });
- sendNotification("codex/event", { type: "patch_apply_end", id: "patch_1", output: "applied" });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual(
- expect.objectContaining({ type: "tool-use", tool: "patch_apply", callId: "patch_1" }),
- );
- expect(messages).toContainEqual(
- expect.objectContaining({ type: "tool-result", callId: "patch_1", output: "applied" }),
- );
- });
-
- it("legacy codex/event — task_complete triggers turn done (not aborted)", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("codex/event", { type: "task_complete", output: "all done" });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.output).toBe("all done");
- });
-
- it("legacy codex/event — turn_aborted triggers aborted", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("codex/event", { type: "turn_aborted" });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("aborted");
- });
-
- // Raw protocol tests
- it("raw protocol — turn/started sets turnStarted flag", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/started", { turn: { id: "turn_1" } });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).not.toContainEqual(expect.objectContaining({ type: "status" }));
- });
-
- it("raw protocol — turn/completed (nested) with completed triggers turn done", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
- expect(mock.stdinEnd).toHaveBeenCalled();
- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- });
-
- it("raw protocol — turn/completed (flat params) backward compat", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/completed", { turnId: "turn_1", status: "completed" });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- });
-
- it("raw protocol — turn/completed with cancelled triggers aborted", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/completed", { turn: { id: "turn_1", status: "cancelled" } });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("aborted");
- });
-
- it("raw protocol — turn/completed with interrupted triggers aborted", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/completed", { turn: { id: "turn_2", status: "interrupted" } });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("aborted");
- });
-
- it("raw protocol — turn/completed with failed captures error message", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/completed", { turn: { id: "turn_f", status: "failed", error: { message: "rate limit exceeded" } } });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("failed");
- expect(result.error).toBe("rate limit exceeded");
- });
-
- it("raw protocol — turn/completed with failed uses fallback message when no error.message", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/completed", { turn: { id: "turn_f2", status: "failed" } });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("failed");
- expect(result.error).toBe("codex turn failed");
- });
-
- it("raw protocol — duplicate turn/completed for same turnId is deduplicated", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
- sendNotification("turn/completed", { turn: { id: "turn_1", status: "failed" } });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- });
-
- it("raw protocol — item/started (commandExecution) emits tool-use", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("item/started", {
- item: { type: "commandExecution", id: "cmd_1", command: "ls" },
- });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual(
- expect.objectContaining({ type: "tool-use", tool: "exec_command", callId: "cmd_1" }),
- );
- });
-
- it("raw protocol — item/completed (commandExecution) emits tool-result with aggregatedOutput", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("item/completed", {
- item: { type: "commandExecution", id: "cmd_1", aggregatedOutput: "total 0\n" },
- });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual(
- expect.objectContaining({ type: "tool-result", callId: "cmd_1", output: "total 0\n" }),
- );
- });
-
- it("raw protocol — item/started (fileChange) emits tool-use patch_apply", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("item/started", { item: { type: "fileChange", id: "fc_1" } });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual(
- expect.objectContaining({ type: "tool-use", tool: "patch_apply", callId: "fc_1" }),
- );
- });
-
- it("raw protocol — item/completed (fileChange) emits tool-result", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("item/completed", { item: { type: "fileChange", id: "fc_1" } });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual(
- expect.objectContaining({ type: "tool-result", callId: "fc_1", output: "" }),
- );
- });
-
- it("raw protocol — item/completed (agentMessage) reads item.text (flat)", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("item/completed", {
- item: {
- type: "agentMessage",
- text: "Flat text answer",
- },
- });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "Flat text answer" });
- });
-
- it("raw protocol — item/completed (agentMessage) falls back to item.content[] when item.text absent", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("item/completed", {
- item: {
- type: "agentMessage",
- content: [{ type: "text", text: "Content array answer" }],
- },
- });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "Content array answer" });
- });
-
- it("raw protocol — item/completed (agentMessage, phase=final_answer) triggers turn done", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("item/completed", {
- item: {
- type: "agentMessage",
- phase: "final_answer",
- text: "Here is the answer",
- },
- });
- expect(mock.stdinEnd).toHaveBeenCalled();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "Here is the answer" });
- });
-
- it("raw protocol — thread/status/changed (nested idle) triggers turn done when turnStarted", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/started", { turn: { id: "turn_1" } });
- sendNotification("thread/status/changed", { status: { type: "idle" } });
- expect(mock.stdinEnd).toHaveBeenCalled();
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- });
-
- it("raw protocol — thread/status/changed (flat idle) backward compat", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/started", { turn: { id: "turn_1" } });
- sendNotification("thread/status/changed", { status: "idle" });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- });
-
- it("raw protocol — thread/status/changed (idle) does NOT trigger turn done if turnStarted is false", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- // No turn/started sent — turnStarted remains false
- sendNotification("thread/status/changed", { status: { type: "idle" } });
- expect(mock.stdinEnd).not.toHaveBeenCalled();
- mock.proc.emit("close", 0);
-
- // Process exits with code 0 but turnDone was never triggered, status stays "completed" (default)
- const result = await session.result;
- expect(result.status).toBe("completed");
- });
-
- // triggerTurnDone idempotency
- it("triggerTurnDone is idempotent — second call does not double-kill", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
- // First call: stdin.end + kill
- expect(mock.stdinEnd).toHaveBeenCalledTimes(1);
- expect(mock.proc.kill).toHaveBeenCalledTimes(1);
-
- // Second completion signal (e.g. thread/status/changed also fires)
- sendNotification("turn/started", { turn: { id: "turn_1" } });
- sendNotification("thread/status/changed", { status: { type: "idle" } });
- // Should not call again
- expect(mock.stdinEnd).toHaveBeenCalledTimes(1);
- expect(mock.proc.kill).toHaveBeenCalledTimes(1);
-
- mock.proc.emit("close", 0);
- const result = await session.result;
- expect(result.status).toBe("completed");
- });
-
- // Subagent thread filtering
- it("subagent thread notifications are ignored — no text, no turn completion", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake("thread_main");
-
- // Subagent sends agentMessage from different thread
- sendNotification("item/completed", {
- threadId: "thread_subagent",
- item: { type: "agentMessage", text: "subagent leak" },
- });
- // Subagent sends turn/completed from different thread
- sendNotification("turn/completed", {
- threadId: "thread_subagent",
- turn: { id: "sub_turn", status: "completed" },
- });
-
- expect(mock.stdinEnd).not.toHaveBeenCalled();
-
- // Main thread completes normally
- sendNotification("turn/completed", {
- threadId: "thread_main",
- turn: { id: "main_turn", status: "completed" },
- });
- expect(mock.stdinEnd).toHaveBeenCalled();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).not.toContainEqual(expect.objectContaining({ content: "subagent leak" }));
- });
-
- it("subagent item/completed with phase=final_answer from different thread is ignored", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake("thread_main");
-
- sendNotification("item/completed", {
- threadId: "thread_subagent",
- item: { type: "agentMessage", text: "subagent final", phase: "final_answer" },
- });
-
- expect(mock.stdinEnd).not.toHaveBeenCalled();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).not.toContainEqual(expect.objectContaining({ content: "subagent final" }));
- });
-
- // Error notifications
- it("error notification with willRetry=false captures turnError", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("error", { error: { message: "server crashed" }, willRetry: false });
- // error does NOT trigger turnDone — the process may still send turn/completed
- expect(mock.stdinEnd).not.toHaveBeenCalled();
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.status).toBe("failed");
- expect(result.error).toBe("server crashed");
- });
-
- it("error notification with willRetry=true does NOT set turnError", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("error", { error: { message: "reconnecting" }, willRetry: true });
- sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.error).toBe("");
- });
-
- // turnError first-write-wins
- it("turnError has first-write-wins semantics", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- // First error
- sendNotification("error", { error: { message: "first error" }, willRetry: false });
- // Second error — should be ignored
- sendNotification("error", { error: { message: "second error" }, willRetry: false });
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.error).toBe("first error");
- });
-
- // item/agentMessage/delta protocol detection
- it("item/agentMessage/delta triggers raw protocol detection", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("item/agentMessage/delta", {
- itemId: "msg_1",
- delta: "Hello",
- });
- // Should be logged as debug (default case) since no specific handler
- // But protocol should now be locked to raw
- sendNotification("codex/event", { type: "agent_message", text: "should be ignored" });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- // The legacy event should NOT produce a text message since protocol is locked to raw
- expect(messages).not.toContainEqual({ type: "text", content: "should be ignored" });
- });
-
- // Full integration test
- it("full integration: handshake → deltas → turn/completed → result resolves", async () => {
- const session = backend.execute("hello world", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake("thread_xyz");
-
- // Agent starts turn
- sendNotification("turn/started", { threadId: "thread_xyz", turn: { id: "turn_1" } });
-
- // Agent sends deltas (logged as debug, not accumulated)
- sendNotification("item/agentMessage/delta", { threadId: "thread_xyz", itemId: "msg_1", delta: "Hi" });
- sendNotification("item/agentMessage/delta", { threadId: "thread_xyz", itemId: "msg_1", delta: " there" });
-
- // Agent completes with full text
- sendNotification("item/completed", {
- threadId: "thread_xyz",
- item: { type: "agentMessage", id: "msg_1", text: "Hi there" },
- });
-
- // Turn completes
- sendNotification("turn/completed", { threadId: "thread_xyz", turn: { id: "turn_1", status: "completed" } });
-
- expect(mock.stdinEnd).toHaveBeenCalled();
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.output).toBe("Hi there");
- expect(result.sessionId).toBe("thread_xyz");
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "Hi there" });
- });
-
- // Protocol detection / locking
- it("first legacy event locks protocol to legacy", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("codex/event", { type: "task_started" });
- sendNotification("turn/started", { turnId: "turn_1" });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- // Legacy event processed but no status messages emitted; raw event ignored
- expect(messages).not.toContainEqual(expect.objectContaining({ type: "status" }));
- });
-
- it("first raw event locks protocol to raw", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/started", { turnId: "turn_1" });
- sendNotification("codex/event", { type: "agent_message", text: "ignored" });
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- // Raw event processed but no status messages emitted; legacy event ignored
- expect(messages).not.toContainEqual(expect.objectContaining({ type: "status" }));
- expect(messages).not.toContainEqual({ type: "text", content: "ignored" });
- });
-
- it("turn completed successfully + non-zero exit code → status completed (not failed)", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- });
-
- it("non-zero exit code before turn completes (no output) → status failed", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("turn/started", { turn: { id: "turn_1" } });
- // Process exits before turn/completed and without any agent output
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.status).toBe("failed");
- });
-
- it("non-zero exit code before turn completes but agent produced output → status completed", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake("thread_abc");
- sendNotification("turn/started", { threadId: "thread_abc", turn: { id: "turn_1" } });
- sendNotification("item/completed", {
- threadId: "thread_abc",
- item: { type: "agentMessage", id: "msg_1", text: "Hi. What can I help with?" },
- });
- // Process exits with non-zero code (e.g. MCP transport crash) without turn/completed
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.output).toBe("Hi. What can I help with?");
- });
-
- it("turn completed successfully + non-zero exit + turnError → status failed with turnError", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- sendNotification("error", { error: { message: "rate limit" }, willRetry: false });
- sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.status).toBe("failed");
- expect(result.error).toBe("rate limit");
- });
-
- it("strips ANSI escape codes from stderr", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await completeHandshake();
- mock.stderr.push("\x1b[31mERROR\x1b[0m something broke\n");
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.error).toBe("ERROR something broke\n");
- expect(result.error).not.toContain("\x1b[");
- });
-
- it("handles invalid JSON gracefully", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push("not valid json\n");
- await tick();
- mock.proc.emit("close", 1);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "log", content: "not valid json", level: "debug" });
- });
-
- it("closeAllPending sends error to all pending RPC callbacks on process close", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- // Don't respond to initialize — let process close while it's pending
- await tick(30);
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- // Process exiting with code 1 without responding sets failed status
- expect(result.status).toBe("failed");
- });
-
- it("timeout kills process and sets status to timeout", async () => {
- vi.useFakeTimers();
- const killTree = await vi.importMock<typeof import("../../kill-tree.js")>("../../kill-tree.js");
- const session = backend.execute("hello", { cwd: "/tmp", timeout: 5000 });
- const mock = getMock();
-
- vi.advanceTimersByTime(5000);
- expect(killTree.killProcessTree).toHaveBeenCalledWith(12345);
-
- mock.proc.emit("close", null);
-
- const result = await session.result;
- expect(result.status).toBe("timeout");
- vi.useRealTimers();
- });
-
- it("TC8: spawns the CLI detached on POSIX so its group can be reaped", () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- expect(session.pid).toBe(12345);
- expect(lastSpawnOpts!.detached).toBe(process.platform !== "win32");
- });
-});
diff --git a/src/cli/daemon/agent/__tests__/index.test.ts b/src/cli/daemon/agent/__tests__/index.test.ts
deleted file mode 100644
index 45116bc30..000000000
--- a/src/cli/daemon/agent/__tests__/index.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { createBackend } from "../index.js";
-import { ClaudeBackend } from "../claude.js";
-import { CodexBackend } from "../codex.js";
-import { OpenCodeBackend } from "../opencode.js";
-
-describe("createBackend", () => {
- it('returns ClaudeBackend for "claude"', () => {
- const backend = createBackend("claude", "/usr/bin/claude");
- expect(backend).toBeInstanceOf(ClaudeBackend);
- expect(backend.name).toBe("claude");
- });
-
- it('returns CodexBackend for "codex"', () => {
- const backend = createBackend("codex", "/usr/bin/codex");
- expect(backend).toBeInstanceOf(CodexBackend);
- expect(backend.name).toBe("codex");
- });
-
- it('returns OpenCodeBackend for "opencode"', () => {
- const backend = createBackend("opencode", "/usr/bin/opencode");
- expect(backend).toBeInstanceOf(OpenCodeBackend);
- expect(backend.name).toBe("opencode");
- });
-
- it("throws for unknown provider", () => {
- expect(() => createBackend("unknown", "/usr/bin/unknown")).toThrow(
- "Unknown provider: unknown",
- );
- });
-});
diff --git a/src/cli/daemon/agent/__tests__/opencode.parseLine.test.ts b/src/cli/daemon/agent/__tests__/opencode.parseLine.test.ts
deleted file mode 100644
index 82798db20..000000000
--- a/src/cli/daemon/agent/__tests__/opencode.parseLine.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { OpenCodeBackend } from "../opencode.js";
-
-const backend = new OpenCodeBackend("opencode");
-
-describe("OpenCodeBackend.parseLine", () => {
- it("empty line returns empty", () => {
- expect(backend.parseLine("")).toEqual([]);
- });
-
- it("invalid JSON returns log event", () => {
- const events = backend.parseLine("not json");
- expect(events[0].kind).toBe("log");
- });
-
- it("session → session_init", () => {
- const line = JSON.stringify({ type: "session", session_id: "oc-1" });
- const events = backend.parseLine(line);
- expect(events).toEqual([{ kind: "session_init", sessionId: "oc-1" }]);
- });
-
- it("text with part → text", () => {
- const line = JSON.stringify({ type: "text", part: { text: "answer" } });
- const events = backend.parseLine(line);
- expect(events).toContainEqual({ kind: "text", text: "answer" });
- });
-
- it("thinking → thinking", () => {
- const line = JSON.stringify({ type: "thinking", part: { thinking: "hmm" } });
- const events = backend.parseLine(line);
- expect(events).toContainEqual({ kind: "thinking", text: "hmm" });
- });
-
- it("tool_call → tool_call", () => {
- const line = JSON.stringify({ type: "tool_call", name: "Bash", call_id: "tc-1", input: { cmd: "ls" } });
- const events = backend.parseLine(line);
- expect(events).toContainEqual({
- kind: "tool_call",
- name: "Bash",
- callId: "tc-1",
- input: { cmd: "ls" },
- });
- });
-
- it("tool_result → tool_output", () => {
- const line = JSON.stringify({ type: "tool_result", call_id: "tc-1", output: "files" });
- const events = backend.parseLine(line);
- expect(events).toContainEqual({
- kind: "tool_output",
- callId: "tc-1",
- output: "files",
- });
- });
-
- it("done → turn_end", () => {
- const line = JSON.stringify({ type: "done", output: "result", session_id: "s1" });
- const events = backend.parseLine(line);
- const turnEnds = events.filter((e) => e.kind === "turn_end");
- expect(turnEnds.length).toBeGreaterThanOrEqual(1);
- });
-
- it("complete with error status → error + turn_end", () => {
- const line = JSON.stringify({ type: "complete", status: "error", output: "failed" });
- const events = backend.parseLine(line);
- expect(events).toContainEqual({ kind: "error", message: "failed" });
- expect(events).toContainEqual({ kind: "turn_end" });
- });
-
- it("step_finish reason=stop → turn_end", () => {
- const line = JSON.stringify({ type: "step_finish", part: { reason: "stop" } });
- const events = backend.parseLine(line);
- expect(events).toContainEqual({ kind: "turn_end" });
- });
-
- it("step_finish reason=end_turn → turn_end", () => {
- const line = JSON.stringify({ type: "step_finish", part: { reason: "end_turn" } });
- const events = backend.parseLine(line);
- expect(events).toContainEqual({ kind: "turn_end" });
- });
-
- it("error → error + turn_end", () => {
- const line = JSON.stringify({ type: "error", message: "boom" });
- const events = backend.parseLine(line);
- expect(events).toContainEqual({ kind: "error", message: "boom" });
- expect(events).toContainEqual({ kind: "turn_end" });
- });
-
- it("message with role=assistant → text", () => {
- const line = JSON.stringify({ type: "message", role: "assistant", content: "hello" });
- const events = backend.parseLine(line);
- expect(events).toContainEqual({ kind: "text", text: "hello" });
- });
-});
-
-describe("OpenCodeBackend.encodeStdinMessage", () => {
- it("always returns null", () => {
- expect(backend.encodeStdinMessage("hi", "idle")).toBeNull();
- expect(backend.encodeStdinMessage("hi", "busy")).toBeNull();
- });
-});
diff --git a/src/cli/daemon/agent/__tests__/opencode.test.ts b/src/cli/daemon/agent/__tests__/opencode.test.ts
deleted file mode 100644
index 4f716f568..000000000
--- a/src/cli/daemon/agent/__tests__/opencode.test.ts
+++ /dev/null
@@ -1,555 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { EventEmitter } from "events";
-import { Readable } from "stream";
-import type { AgentMessage } from "../../types.js";
-
-let currentMockProc: ReturnType<typeof createMockProc> | null = null;
-let lastSpawnArgs: { cmd: string; args: string[]; opts: Record<string, unknown> } | null = null;
-
-function createMockProc() {
- const stdout = new Readable({ read() {} });
- const stderr = new Readable({ read() {} });
- const proc = Object.assign(new EventEmitter(), {
- stdout,
- stderr,
- stdin: null,
- kill: vi.fn(),
- pid: 12345,
- });
- return { proc, stdout, stderr };
-}
-
-vi.mock("child_process", () => ({
- spawn: vi.fn((cmd: string, args: string[], opts: Record<string, unknown>) => {
- lastSpawnArgs = { cmd, args, opts };
- currentMockProc = createMockProc();
- return currentMockProc.proc;
- }),
-}));
-
-vi.mock("../../kill-tree.js", () => ({
- killProcessTree: vi.fn().mockResolvedValue(undefined),
- killGraceMs: () => 2000,
- isAlive: () => false,
-}));
-
-const tick = (ms = 15) => new Promise((r) => setTimeout(r, ms));
-
-async function collectMessages(
- messages: AsyncIterable<AgentMessage>,
- maxMessages = 50,
- timeoutMs = 500,
-): Promise<AgentMessage[]> {
- const collected: AgentMessage[] = [];
- const timeout = new Promise<void>((resolve) => setTimeout(resolve, timeoutMs));
- const iter = messages[Symbol.asyncIterator]();
- for (let i = 0; i < maxMessages; i++) {
- const next = iter.next();
- const result = await Promise.race([next, timeout.then(() => null)]);
- if (!result || result.done) break;
- collected.push(result.value);
- }
- return collected;
-}
-
-const { OpenCodeBackend } = await import("../opencode.js");
-
-function getMock() {
- return currentMockProc!;
-}
-
-describe("OpenCodeBackend", () => {
- let backend: InstanceType<typeof OpenCodeBackend>;
-
- beforeEach(() => {
- vi.clearAllMocks();
- currentMockProc = null;
- lastSpawnArgs = null;
- backend = new OpenCodeBackend("/usr/bin/opencode");
- });
-
- it("emits MessageText for assistant message events", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "message", role: "assistant", content: "Hi there" }) + "\n");
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "Hi there" });
- });
-
- it("does not emit for empty message content", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "message", role: "assistant", content: "" }) + "\n");
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- const textMessages = messages.filter((m) => m.type === "text");
- expect(textMessages).toHaveLength(0);
- });
-
- it("emits tool-use for tool_call events", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({ type: "tool_call", name: "read_file", call_id: "call_1", input: { path: "/test" } }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({
- type: "tool-use",
- tool: "read_file",
- callId: "call_1",
- input: { path: "/test" },
- });
- });
-
- it("emits tool-result for tool_result events", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({ type: "tool_result", call_id: "call_1", output: "file contents" }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({
- type: "tool-result",
- callId: "call_1",
- output: "file contents",
- });
- });
-
- it("emits error event and sets error", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "error", message: "something broke" }) + "\n");
- await tick();
- mock.proc.emit("close", 1);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "error", content: "something broke" });
- });
-
- it("marks the run failed on an error event (so failTask persists the error)", async () => {
- // Regression guard: an `error` event must set result.status="failed" — the
- // same as codex and opencode's done/spawn-error branches. Otherwise the run
- // ends "completed", failTask never runs, and the error is lost on reload.
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "error", message: "boom on run" }) + "\n");
- await tick();
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.status).toBe("failed");
- expect(result.error).toBe("boom on run");
- });
-
- it("error event with content fallback works", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "error", content: "fallback error" }) + "\n");
- await tick();
- mock.proc.emit("close", 1);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "error", content: "fallback error" });
- });
-
- it("captures session ID from session event", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "session", session_id: "sess_abc" }) + "\n");
- await tick();
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.sessionId).toBe("sess_abc");
- });
-
- it("session ID uses last non-empty value", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "session", session_id: "first" }) + "\n");
- mock.stdout.push(JSON.stringify({ type: "session", session_id: "" }) + "\n");
- mock.stdout.push(JSON.stringify({ type: "session", session_id: "last" }) + "\n");
- await tick();
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.sessionId).toBe("last");
- });
-
- it("handles empty lines and invalid JSON gracefully", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push("\n");
- mock.stdout.push(" \n");
- mock.stdout.push("not json\n");
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "log", content: "not json", level: "debug" });
- });
-
- it("spawns with stdin ignored to prevent opencode from blocking on pipe", () => {
- backend.execute("hello", { cwd: "/tmp" });
- expect(lastSpawnArgs).toBeTruthy();
- const stdio = lastSpawnArgs!.opts.stdio as string[];
- expect(stdio[0]).toBe("ignore");
- expect(stdio[1]).toBe("pipe");
- expect(stdio[2]).toBe("pipe");
- });
-
- it("OPENCODE_PERMISSION env var is set on subprocess", () => {
- backend.execute("hello", { cwd: "/tmp" });
- expect(lastSpawnArgs).toBeTruthy();
- const env = lastSpawnArgs!.opts.env as Record<string, string>;
- expect(env.OPENCODE_PERMISSION).toBe('{"*":"allow"}');
- });
-
- it("merges execenv vars into spawn env and OPENCODE_PERMISSION wins", () => {
- backend.execute("hello", {
- cwd: "/tmp",
- env: { ALOOK_WORKSPACE_ID: "ws1", OPENCODE_PERMISSION: "should-be-overridden" },
- });
- expect(lastSpawnArgs).toBeTruthy();
- const env = lastSpawnArgs!.opts.env as Record<string, string>;
- expect(env.ALOOK_WORKSPACE_ID).toBe("ws1");
- expect(env.OPENCODE_PERMISSION).toBe('{"*":"allow"}');
- });
-
- it("does not pass --prompt flag, user prompt is positional", () => {
- backend.execute("do things", { cwd: "/tmp" });
- expect(lastSpawnArgs).toBeTruthy();
- const args = lastSpawnArgs!.args;
- // On win32 the args are pre-quoted for cmd.exe (see win-quote.ts), so
- // "do things" arrives as `"do things"`. Strip a single wrapping quote
- // pair for the positional-arg assertion.
- const last = args[args.length - 1];
- const unwrapped = process.platform === "win32" && last.startsWith("\"") && last.endsWith("\"")
- ? last.slice(1, -1)
- : last;
- expect(args).not.toContain("--prompt");
- expect(unwrapped).toBe("do things");
- });
-
- it("TC8: spawns the CLI detached on POSIX so its group can be reaped", () => {
- backend.execute("hello", { cwd: "/tmp" });
- expect(lastSpawnArgs).toBeTruthy();
- expect(lastSpawnArgs!.opts.detached).toBe(process.platform !== "win32");
- });
-
- it("sets status to timeout when process is killed by timeout", async () => {
- vi.useFakeTimers();
- const killTree = await vi.importMock<typeof import("../../kill-tree.js")>("../../kill-tree.js");
- const session = backend.execute("hello", { cwd: "/tmp", timeout: 3000 });
- const mock = getMock();
-
- vi.advanceTimersByTime(3000);
- expect(killTree.killProcessTree).toHaveBeenCalledWith(12345);
-
- mock.proc.emit("close", null);
-
- const result = await session.result;
- expect(result.status).toBe("timeout");
- vi.useRealTimers();
- });
-
- it("error event with nil error emits empty content", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "error" }) + "\n");
- await tick();
- mock.proc.emit("close", 1);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "error", content: "" });
- });
-
- it("tool_call with missing fields does not crash", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "tool_call" }) + "\n");
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual(
- expect.objectContaining({ type: "tool-use", tool: "" }),
- );
- });
-
- it("done/complete event updates output and session ID", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(
- JSON.stringify({ type: "done", output: "final output", session_id: "sess_done", status: "completed" }) + "\n",
- );
- await tick();
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.output).toBe("final output");
- expect(result.sessionId).toBe("sess_done");
- });
-
- // --- Turn completion: process lifecycle ---
-
- it("done event kills the process", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "done", output: "all done" }) + "\n");
- await tick();
-
- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
-
- mock.proc.emit("close", 0);
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.output).toBe("all done");
- });
-
- it("complete event kills the process", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "complete", output: "finished" }) + "\n");
- await tick();
-
- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
-
- mock.proc.emit("close", 0);
- const result = await session.result;
- expect(result.status).toBe("completed");
- });
-
- it("error event kills the process", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "error", message: "fatal error" }) + "\n");
- await tick();
-
- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
-
- mock.proc.emit("close", 1);
- const result = await session.result;
- expect(result.error).toBe("fatal error");
- });
-
- it("turnDone is idempotent — done after error does not double-kill", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "error", message: "boom" }) + "\n");
- await tick();
- mock.stdout.push(JSON.stringify({ type: "done", output: "done anyway" }) + "\n");
- await tick();
-
- expect(mock.proc.kill).toHaveBeenCalledTimes(1);
-
- mock.proc.emit("close", 1);
- await session.result;
- });
-
- it("full flow: message → tool_call → tool_result → done → result resolves", async () => {
- const session = backend.execute("fix the bug", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "session", session_id: "sess_123" }) + "\n");
- mock.stdout.push(JSON.stringify({ type: "message", role: "assistant", content: "Let me check" }) + "\n");
- mock.stdout.push(JSON.stringify({ type: "tool_call", name: "read_file", call_id: "c1", input: { path: "/bug.ts" } }) + "\n");
- mock.stdout.push(JSON.stringify({ type: "tool_result", call_id: "c1", output: "buggy code" }) + "\n");
- mock.stdout.push(JSON.stringify({ type: "message", role: "assistant", content: "Found the bug" }) + "\n");
- mock.stdout.push(JSON.stringify({ type: "done", output: "Found the bug", session_id: "sess_123" }) + "\n");
- await tick();
-
- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.output).toBe("Found the bug");
- expect(result.sessionId).toBe("sess_123");
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "Let me check" });
- expect(messages).toContainEqual({ type: "text", content: "Found the bug" });
- expect(messages).toContainEqual(expect.objectContaining({ type: "tool-use", tool: "read_file", callId: "c1" }));
- expect(messages).toContainEqual(expect.objectContaining({ type: "tool-result", callId: "c1", output: "buggy code" }));
- });
-
- // --- v1.14+ format tests ---
-
- it("v1.14+: emits text from part.text field", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({
- type: "text",
- timestamp: 1777626241755,
- sessionID: "ses_abc123",
- part: { id: "prt_1", messageID: "msg_1", sessionID: "ses_abc123", type: "text", text: "Hello from v1.14!" },
- }) + "\n");
- await tick();
- mock.proc.emit("close", 0);
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "Hello from v1.14!" });
-
- const result = await session.result;
- expect(result.output).toBe("Hello from v1.14!");
- expect(result.sessionId).toBe("ses_abc123");
- });
-
- it("v1.14+: step_finish with reason=stop calls turnDone", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({
- type: "step_start",
- sessionID: "ses_abc",
- part: { type: "step-start" },
- }) + "\n");
- mock.stdout.push(JSON.stringify({
- type: "text",
- sessionID: "ses_abc",
- part: { type: "text", text: "Done!" },
- }) + "\n");
- mock.stdout.push(JSON.stringify({
- type: "step_finish",
- sessionID: "ses_abc",
- part: { type: "step-finish", reason: "stop", tokens: { total: 100 } },
- }) + "\n");
- await tick();
-
- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.output).toBe("Done!");
- });
-
- it("v1.14+: extracts sessionID from event-level field", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({
- type: "step_start",
- sessionID: "ses_from_event",
- part: { type: "step-start" },
- }) + "\n");
- await tick();
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.sessionId).toBe("ses_from_event");
- });
-
- it("v1.14+: full flow with new format", async () => {
- const session = backend.execute("你是谁", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({
- type: "step_start",
- sessionID: "ses_new",
- part: { id: "prt_1", messageID: "msg_1", sessionID: "ses_new", type: "step-start" },
- }) + "\n");
- mock.stdout.push(JSON.stringify({
- type: "text",
- sessionID: "ses_new",
- part: { id: "prt_2", messageID: "msg_1", sessionID: "ses_new", type: "text", text: "我是トニー大木" },
- }) + "\n");
- mock.stdout.push(JSON.stringify({
- type: "step_finish",
- sessionID: "ses_new",
- part: { id: "prt_3", reason: "stop", messageID: "msg_1", sessionID: "ses_new", type: "step-finish", tokens: { total: 20145, input: 6, output: 34 }, cost: 0.12 },
- }) + "\n");
- await tick();
-
- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
- mock.proc.emit("close", 0);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.output).toBe("我是トニー大木");
- expect(result.sessionId).toBe("ses_new");
-
- const messages = await collectMessages(session.messages);
- expect(messages).toContainEqual({ type: "text", content: "我是トニー大木" });
- });
-
- it("v1.14+: non-zero exit after turnDone still reports completed", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({
- type: "text",
- sessionID: "ses_x",
- part: { type: "text", text: "Done!" },
- }) + "\n");
- mock.stdout.push(JSON.stringify({
- type: "step_finish",
- sessionID: "ses_x",
- part: { type: "step-finish", reason: "stop" },
- }) + "\n");
- await tick();
-
- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
- // Process exits with non-zero due to SIGTERM (143)
- mock.proc.emit("close", 143);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.output).toBe("Done!");
- });
-
- it("non-zero exit with output but no turnDone still reports completed", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- mock.stdout.push(JSON.stringify({ type: "message", role: "assistant", content: "Got it" }) + "\n");
- await tick();
- // Process crashes after producing output
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.status).toBe("completed");
- expect(result.output).toBe("Got it");
- });
-
- it("non-zero exit with no output and no turnDone reports failed", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
- const mock = getMock();
-
- await tick();
- mock.proc.emit("close", 1);
-
- const result = await session.result;
- expect(result.status).toBe("failed");
- });
-});
diff --git a/src/cli/daemon/agent/__tests__/win-quote.test.ts b/src/cli/daemon/agent/__tests__/win-quote.test.ts
deleted file mode 100644
index d91cce059..000000000
--- a/src/cli/daemon/agent/__tests__/win-quote.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { quoteWinArg, quoteWinArgs } from "../win-quote.js";
-
-describe("quoteWinArg", () => {
- it("leaves simple tokens untouched", () => {
- expect(quoteWinArg("simple")).toBe("simple");
- expect(quoteWinArg("--flag")).toBe("--flag");
- expect(quoteWinArg("value123")).toBe("value123");
- });
-
- it("wraps paths containing spaces", () => {
- expect(quoteWinArg("C:\\Users\\John Doe\\.alook")).toBe(
- "\"C:\\Users\\John Doe\\.alook\"",
- );
- });
-
- it("escapes embedded double quotes", () => {
- expect(quoteWinArg('say "hi"')).toBe('"say \\"hi\\""');
- });
-
- it("doubles trailing backslashes before the closing quote when quoting", () => {
- // Only relevant when we DO quote — a bare `trailing\` needs no quoting so
- // MSVCRT parses it as-is. But `path with space\` must be quoted, and the
- // trailing backslash must be doubled so MSVCRT doesn't read the closing
- // quote as escaped.
- expect(quoteWinArg("path with\\")).toBe("\"path with\\\\\"");
- expect(quoteWinArg("has space\\\\")).toBe("\"has space\\\\\\\\\"");
- expect(quoteWinArg("trailing\\")).toBe("trailing\\");
- });
-
- it("preserves backslashes that don't precede a quote", () => {
- expect(quoteWinArg("a\\b c")).toBe("\"a\\b c\"");
- });
-
- it("doubles a backslash run that precedes an embedded quote", () => {
- // MSVCRT rule: N backslashes before a `"` become 2N+1 backslashes + `"`.
- // Two backslashes + `"` → four backslashes + escaped quote.
- expect(quoteWinArg('a\\\\"b c')).toBe('"a\\\\\\\\\\"b c"');
- // One backslash + `"` → two backslashes + escaped quote.
- expect(quoteWinArg('a\\"b c')).toBe('"a\\\\\\"b c"');
- });
-
- it("quotes args containing cmd metachars", () => {
- expect(quoteWinArg("a&b")).toBe("\"a&b\"");
- expect(quoteWinArg("a|b")).toBe("\"a|b\"");
- expect(quoteWinArg("a>b")).toBe("\"a>b\"");
- expect(quoteWinArg("100%")).toBe("\"100%\"");
- });
-
- it("quotes empty string", () => {
- expect(quoteWinArg("")).toBe("\"\"");
- });
-
- it("maps arrays through quoteWinArgs", () => {
- expect(
- quoteWinArgs([
- "run",
- "--dir",
- "C:\\Users\\John Doe\\.alook\\workspaces",
- "hello world",
- ]),
- ).toEqual([
- "run",
- "--dir",
- "\"C:\\Users\\John Doe\\.alook\\workspaces\"",
- "\"hello world\"",
- ]);
- });
-});
diff --git a/src/cli/daemon/agent/claude.ts b/src/cli/daemon/agent/claude.ts
deleted file mode 100644
index bcf2ede09..000000000
--- a/src/cli/daemon/agent/claude.ts
+++ /dev/null
@@ -1,570 +0,0 @@
-import { spawn, type ChildProcess } from "child_process";
-import { createInterface } from "readline";
-import type { AgentBackend, AgentSession } from "./index.js";
-import type {
- ExecOptions,
- AgentMessage,
- AgentResult,
- ParsedEvent,
- StdinMode,
- DriverLifecycle,
- BusyDeliveryMode,
- EncodeOpts,
-} from "../types.js";
-import { killProcessTree } from "../kill-tree.js";
-import { quoteWinArg, quoteWinArgs } from "./win-quote.js";
-
-export class ClaudeBackend implements AgentBackend {
- name = "claude";
- lifecycle: DriverLifecycle = { kind: "persistent", stdin: "gated", inFlightWake: "queue" };
- busyDeliveryMode: BusyDeliveryMode = "gated";
- supportsStdinNotification = true;
-
- constructor(private cliPath: string) {}
-
- parseLine(line: string): ParsedEvent[] {
- if (!line.trim()) return [];
- let event: Record<string, unknown>;
- try {
- event = JSON.parse(line);
- } catch {
- return [{ kind: "log", content: line, level: "debug" }];
- }
-
- const events: ParsedEvent[] = [];
- const eventType = event.type as string | undefined;
-
- switch (eventType) {
- case "assistant": {
- const message = event.message as Record<string, unknown> | undefined;
- if (!message) break;
- const content = message.content as
- | { type: string; text?: string; name?: string; id?: string; input?: Record<string, unknown> }[]
- | undefined;
- if (!Array.isArray(content)) break;
-
- for (const block of content) {
- if (block.type === "text") {
- events.push({ kind: "text", text: block.text || "" });
- } else if (block.type === "thinking") {
- events.push({ kind: "thinking", text: block.text || "" });
- } else if (block.type === "tool_use") {
- events.push({ kind: "tool_call", name: block.name || "", input: block.input, callId: block.id });
- }
- }
- break;
- }
-
- case "result": {
- const result = event.result as string | undefined;
- const isError = event.is_error as boolean | undefined;
- if (isError) {
- events.push({ kind: "error", message: result || "unknown error" });
- }
- const resultSessionId = event.session_id as string | undefined;
- events.push({ kind: "turn_end", sessionId: resultSessionId || undefined });
- const usage = event.usage as Record<string, unknown> | undefined;
- if (usage || event.total_cost_usd != null) {
- events.push({
- kind: "telemetry",
- name: "token_usage",
- source: "claude_result_usage",
- usageKind: "per_turn",
- attrs: {
- inputTokens: usage?.input_tokens,
- outputTokens: usage?.output_tokens,
- cachedInputTokens: usage?.cache_read_input_tokens,
- cacheCreationInputTokens: usage?.cache_creation_input_tokens,
- totalCostUsd: event.total_cost_usd,
- durationMs: event.duration_ms,
- durationApiMs: event.duration_api_ms,
- numTurns: event.num_turns,
- resultSubtype: event.subtype,
- resultIsError: event.is_error,
- serviceTier: usage?.service_tier,
- },
- });
- }
- break;
- }
-
- case "tool_result": {
- const toolUseId = event.tool_use_id as string | undefined;
- const content = event.content as string | undefined;
- events.push({ kind: "tool_output", callId: toolUseId, output: content });
- break;
- }
-
- case "system": {
- const subtype = event.subtype as string | undefined;
- if (subtype === "init") {
- const sid = event.session_id as string | undefined;
- events.push({ kind: "session_init", sessionId: sid || "" });
- } else if (subtype === "context_pruning" || subtype === "compaction") {
- events.push({ kind: "compaction_started" });
- } else if (subtype === "compaction_finished" || subtype === "context_pruning_finished") {
- events.push({ kind: "compaction_finished" });
- } else if (subtype === "status" || subtype === "stream_event") {
- events.push({
- kind: "internal_progress",
- source: "claude_system",
- itemType: subtype,
- payloadBytes: line.length,
- });
- }
- break;
- }
-
- case "control_request": {
- const requestId = event.request_id as string | undefined;
- if (requestId) {
- events.push({ kind: "permission_request", requestId, payload: event.payload });
- }
- break;
- }
-
- default: {
- events.push({ kind: "log", content: line, level: "debug" });
- }
- }
-
- return events;
- }
-
- encodeStdinMessage(text: string, mode: StdinMode, opts?: EncodeOpts): string | null {
- const msg: Record<string, unknown> = {
- type: "user",
- message: {
- role: "user",
- content: [{ type: "text", text }],
- },
- };
- if (opts?.sessionId) {
- msg.session_id = opts.sessionId;
- }
- return JSON.stringify(msg);
- }
-
- execute(prompt: string, options: ExecOptions): AgentSession {
- // When steering is enabled, use --input-format stream-json and deliver
- // the initial prompt via stdin JSON write instead of -p. This allows
- // mid-turn message injection on the same stdin pipe. Without steering,
- // use the normal -p flag (--input-format stream-json + -p causes a hang).
- const useStdinPrompt = options.steeringEnabled === true;
-
- const args: string[] = [];
- if (!useStdinPrompt) {
- args.push("-p", prompt);
- }
- args.push(
- "--output-format",
- "stream-json",
- "--verbose",
- "--permission-mode",
- "bypassPermissions",
- );
- if (useStdinPrompt) {
- args.push("--input-format", "stream-json");
- }
-
- if (options.model) {
- args.push("--model", options.model);
- }
- if (options.maxTurns) {
- args.push("--max-turns", String(options.maxTurns));
- }
- if (options.resumeSessionId) {
- args.push("--resume", options.resumeSessionId);
- }
-
- const isWin = process.platform === "win32";
- const spawnCmd = isWin ? quoteWinArg(this.cliPath) : this.cliPath;
- const spawnArgs = isWin ? quoteWinArgs(args) : args;
-
- const proc = spawn(spawnCmd, spawnArgs, {
- cwd: options.cwd,
- stdio: ["pipe", "pipe", "pipe"],
- env: { ...process.env, ...options.env },
- shell: isWin,
- windowsHide: true,
- // POSIX: own process group (pgid === pid) so the session-runner can reap
- // the CLI *and* its tool/MCP subprocesses via a group kill. No unref() —
- // we keep the handle for stdio streaming and the result promise.
- detached: process.platform !== "win32",
- });
-
- if (!proc.pid) {
- const error = `Failed to start ${this.cliPath}: binary not found or not executable. Is 'claude' installed and on PATH?`;
- const failedResult: AgentResult = { status: "failed", output: "", error, durationMs: 0, sessionId: "" };
- const emptyMessages: AsyncIterable<AgentMessage> = { [Symbol.asyncIterator]() { return { async next() { return { value: undefined as unknown as AgentMessage, done: true }; } }; } };
- return { pid: undefined, messages: emptyMessages, sessionId: Promise.resolve(""), result: Promise.resolve(failedResult) };
- }
-
- let timedOut = false;
- let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
- if (options.timeout) {
- timeoutTimer = setTimeout(() => {
- timedOut = true;
- // Reap the whole group (CLI + tool/MCP subprocesses), not just the leader.
- if (proc.pid !== undefined) void killProcessTree(proc.pid);
- }, options.timeout);
- }
-
- const startTime = Date.now();
- let lastSessionId = "";
- let lastOutput = "";
- let lastError = "";
- let resultStatus: AgentResult["status"] = "completed";
- let resolveSessionId: (id: string) => void;
- const sessionIdPromise = new Promise<string>((resolve) => {
- resolveSessionId = resolve;
- });
-
- const messageQueue: AgentMessage[] = [];
- let messageResolve: (() => void) | null = null;
- let messageDone = false;
-
- const pushMessage = (msg: AgentMessage) => {
- messageQueue.push(msg);
- if (messageResolve) {
- const r = messageResolve;
- messageResolve = null;
- r();
- }
- };
-
- // ParsedEvent queue — parallel stream for steering layer observation
- const parsedEventQueue: ParsedEvent[] = [];
- let parsedEventResolve: (() => void) | null = null;
- let parsedEventDone = false;
-
- const pushParsedEvent = (evt: ParsedEvent) => {
- parsedEventQueue.push(evt);
- if (parsedEventResolve) {
- const r = parsedEventResolve;
- parsedEventResolve = null;
- r();
- }
- };
-
- // Serialized stdin write queue — prevents interleaved writes
- // from concurrent control_response and steering messages.
- const stdinWriteQueue: string[] = [];
- let stdinDraining = false;
-
- const enqueueStdinWrite = (data: string) => {
- stdinWriteQueue.push(data);
- drainStdinQueue();
- };
-
- const drainStdinQueue = () => {
- if (stdinDraining) return;
- stdinDraining = true;
- while (stdinWriteQueue.length > 0) {
- const line = stdinWriteQueue.shift()!;
- try {
- proc.stdin?.write(line + "\n");
- } catch {
- // stdin closed
- }
- }
- stdinDraining = false;
- };
-
- const resultPromise = new Promise<AgentResult>((resolve) => {
- const stderrChunks: string[] = [];
-
- proc.stderr?.on("data", (chunk: Buffer) => {
- stderrChunks.push(chunk.toString());
- });
-
- const rl = createInterface({ input: proc.stdout! });
-
- // When steering mode, deliver the initial prompt via stdin JSON
- if (useStdinPrompt) {
- const initialMsg = JSON.stringify({
- type: "user",
- message: {
- role: "user",
- content: [{ type: "text", text: prompt }],
- },
- });
- enqueueStdinWrite(initialMsg);
- }
-
- rl.on("line", (line: string) => {
- if (!line.trim()) return;
-
- // Emit ParsedEvents for steering layer
- const parsed = this.parseLine(line);
- for (const pe of parsed) pushParsedEvent(pe);
-
- let event: Record<string, unknown>;
- try {
- event = JSON.parse(line);
- } catch {
- pushMessage({ type: "log", content: line, level: "debug" });
- return;
- }
-
- const eventType = event.type as string | undefined;
-
- switch (eventType) {
- case "assistant": {
- const message = event.message as Record<string, unknown> | undefined;
- if (!message) break;
- const content = message.content as
- | { type: string; text?: string; name?: string; id?: string; input?: Record<string, unknown> }[]
- | undefined;
- if (!Array.isArray(content)) break;
-
- for (const block of content) {
- if (block.type === "text") {
- lastOutput = block.text || "";
- pushMessage({ type: "text", content: block.text });
- } else if (block.type === "thinking") {
- pushMessage({ type: "thinking", content: block.text });
- } else if (block.type === "tool_use") {
- pushMessage({
- type: "tool-use",
- tool: block.name,
- callId: block.id,
- input: block.input,
- });
- }
- }
- break;
- }
-
- case "result": {
- const result = event.result as string | undefined;
- const sessionId = event.session_id as string | undefined;
- if (result) lastOutput = result;
- if (sessionId) lastSessionId = sessionId;
-
- const isError = event.is_error as boolean | undefined;
- if (isError) {
- resultStatus = "failed";
- lastError = result || "unknown error";
- }
-
- // In steering mode (--input-format stream-json), Claude keeps the
- // process alive waiting for more stdin. Defer stdin close to allow
- // the steering layer to flush pending messages on turn_end first.
- // The session-runner calls closeStdin() after the flush completes.
- if (useStdinPrompt) {
- setTimeout(() => {
- try { proc.stdin?.end(); } catch { /* already closed */ }
- }, 100);
- }
- break;
- }
-
- case "tool_result": {
- const content = event.content as string | undefined;
- const toolUseId = event.tool_use_id as string | undefined;
- pushMessage({
- type: "tool-result",
- callId: toolUseId,
- output: content,
- });
- break;
- }
-
- case "system": {
- const subtype = event.subtype as string | undefined;
- if (subtype === "init") {
- const sid = event.session_id as string | undefined;
- if (sid) {
- lastSessionId = sid;
- resolveSessionId(sid);
- }
- }
- break;
- }
-
- case "control_request": {
- handleControlRequest(proc, event, enqueueStdinWrite);
- break;
- }
-
- default: {
- pushMessage({
- type: "log",
- content: line,
- level: "debug",
- });
- }
- }
- });
-
- proc.on("error", (err: Error) => {
- resultStatus = "failed";
- lastError = `spawn error: ${err.message}`;
- resolveSessionId(lastSessionId);
- messageDone = true;
- parsedEventDone = true;
- if (messageResolve) {
- const r = messageResolve;
- messageResolve = null;
- r();
- }
- if (parsedEventResolve) {
- const r = parsedEventResolve;
- parsedEventResolve = null;
- r();
- }
- resolve({
- status: "failed",
- output: "",
- error: lastError,
- durationMs: Date.now() - startTime,
- sessionId: lastSessionId,
- });
- });
-
- proc.on("close", (code: number | null) => {
- if (timeoutTimer) clearTimeout(timeoutTimer);
-
- if (timedOut) {
- resultStatus = "timeout";
- } else if (code !== 0 && resultStatus === "completed") {
- resultStatus = "failed";
- }
-
- const stderr = stderrChunks.join("");
- if (stderr && !lastError) {
- lastError = stderr;
- }
-
- // Resolve sessionId promise (fallback if system/init never fired)
- resolveSessionId(lastSessionId);
-
- messageDone = true;
- parsedEventDone = true;
- if (messageResolve) {
- const r = messageResolve;
- messageResolve = null;
- r();
- }
- if (parsedEventResolve) {
- const r = parsedEventResolve;
- parsedEventResolve = null;
- r();
- }
-
- resolve({
- status: resultStatus,
- output: lastOutput,
- error: lastError,
- durationMs: Date.now() - startTime,
- sessionId: lastSessionId,
- });
- });
- });
-
- const messages: AsyncIterable<AgentMessage> = {
- [Symbol.asyncIterator]() {
- return {
- async next(): Promise<IteratorResult<AgentMessage>> {
- while (messageQueue.length === 0 && !messageDone) {
- await new Promise<void>((resolve) => {
- messageResolve = resolve;
- });
- }
- if (messageQueue.length > 0) {
- return { value: messageQueue.shift()!, done: false };
- }
- return { value: undefined as unknown as AgentMessage, done: true };
- },
- };
- },
- };
-
- const parsedEvents: AsyncIterable<ParsedEvent> = {
- [Symbol.asyncIterator]() {
- return {
- async next(): Promise<IteratorResult<ParsedEvent>> {
- while (parsedEventQueue.length === 0 && !parsedEventDone) {
- await new Promise<void>((resolve) => {
- parsedEventResolve = resolve;
- });
- }
- if (parsedEventQueue.length > 0) {
- return { value: parsedEventQueue.shift()!, done: false };
- }
- return { value: undefined as unknown as ParsedEvent, done: true };
- },
- };
- },
- };
-
- const send = (text: string, mode: StdinMode): { ok: boolean; reason?: string } => {
- const encoded = this.encodeStdinMessage(text, mode, { sessionId: lastSessionId || undefined });
- if (!encoded) return { ok: false, reason: "encoding failed" };
- if (!proc.stdin || proc.stdin.destroyed) return { ok: false, reason: "stdin closed" };
- enqueueStdinWrite(encoded);
- return { ok: true };
- };
-
- const descriptor = {
- lifecycle: this.lifecycle,
- busyDeliveryMode: this.busyDeliveryMode,
- supportsStdinNotification: this.supportsStdinNotification,
- };
-
- const closeStdin = () => {
- try {
- if (proc.stdin && !proc.stdin.destroyed) proc.stdin.end();
- } catch { /* already closed */ }
- };
-
- return { pid: proc.pid, messages, parsedEvents, sessionId: sessionIdPromise, result: resultPromise, send, closeStdin, descriptor };
- }
-}
-
-function handleControlRequest(
- proc: ChildProcess,
- event: Record<string, unknown>,
- enqueueStdinWrite?: (data: string) => void,
-): void {
- const requestId = event.request_id as string | undefined;
- if (!requestId) return;
-
- let updatedInput: unknown = undefined;
- const payload = event.payload as Record<string, unknown> | undefined;
- if (payload) {
- const input = payload.input;
- if (typeof input === "string") {
- try {
- updatedInput = JSON.parse(input);
- } catch {
- updatedInput = input;
- }
- } else if (input !== undefined) {
- updatedInput = input;
- }
- }
-
- const approval = JSON.stringify({
- type: "control_response",
- response: {
- subtype: "success",
- request_id: requestId,
- response: {
- behavior: "allow",
- updatedInput,
- },
- },
- });
-
- if (enqueueStdinWrite) {
- enqueueStdinWrite(approval);
- } else {
- try {
- proc.stdin?.write(approval + "\n");
- } catch {
- // stdin may be closed
- }
- }
-}
diff --git a/src/cli/daemon/agent/codex.ts b/src/cli/daemon/agent/codex.ts
deleted file mode 100644
index 2fff239cf..000000000
--- a/src/cli/daemon/agent/codex.ts
+++ /dev/null
@@ -1,893 +0,0 @@
-import { spawn } from "child_process";
-import { createInterface } from "readline";
-import type { AgentBackend, AgentSession } from "./index.js";
-import type {
- ExecOptions,
- AgentMessage,
- AgentResult,
- ParsedEvent,
- StdinMode,
- DriverLifecycle,
- BusyDeliveryMode,
- EncodeOpts,
-} from "../types.js";
-import { killProcessTree } from "../kill-tree.js";
-import { quoteWinArg, quoteWinArgs } from "./win-quote.js";
-
-interface JsonRpcMessage {
- jsonrpc: "2.0";
- id?: number;
- method?: string;
- params?: Record<string, unknown>;
- result?: unknown;
- error?: { code: number; message: string };
-}
-
-type NotificationProtocol = "unknown" | "legacy" | "raw";
-
-const RAW_DETECTION_METHODS = new Set([
- "turn/started",
- "turn/completed",
- "thread/started",
- "item/started",
- "item/completed",
- "item/agentMessage/delta",
-]);
-
-/** Extract thread ID from a thread/start response. */
-export function extractThreadID(response: unknown): string {
- if (response && typeof response === "object") {
- const r = response as Record<string, unknown>;
- // Try nested result.thread.id first, then thread.id, then top-level id
- const thread =
- (r.result as Record<string, unknown> | undefined)?.thread ??
- (r.thread as Record<string, unknown> | undefined);
- if (thread && typeof thread === "object") {
- const id = (thread as Record<string, unknown>).id;
- if (typeof id === "string" && id) return id;
- }
- if (typeof r.id === "string" && r.id) return r.id;
- }
- return "";
-}
-
-export class CodexBackend implements AgentBackend {
- name = "codex";
- lifecycle: DriverLifecycle = { kind: "persistent", stdin: "direct", inFlightWake: "steer" };
- busyDeliveryMode: BusyDeliveryMode = "direct";
- supportsStdinNotification = true;
-
- private _rpcId = 0;
-
- constructor(private cliPath: string) {}
-
- parseLine(line: string): ParsedEvent[] {
- if (!line.trim()) return [];
- let msg: JsonRpcMessage;
- try {
- msg = JSON.parse(line);
- } catch {
- return [{ kind: "log", content: line, level: "debug" }];
- }
-
- // Response (has id, no method) — not a parseable event
- if (msg.id !== undefined && !msg.method) return [];
-
- // Server request (has both id AND method) — not a parseable event
- if (msg.id !== undefined && msg.method) return [];
-
- // Notification (has method, no id)
- if (!msg.method) return [{ kind: "log", content: line, level: "debug" }];
-
- const method = msg.method;
- const params = msg.params || {};
-
- // Legacy protocol
- if (method === "codex/event") {
- return this.parseLegacyEvent(params);
- }
-
- // Raw protocol
- const events: ParsedEvent[] = [];
- switch (method) {
- case "turn/started":
- break;
-
- case "turn/completed": {
- const turn = params.turn as Record<string, unknown> | undefined;
- const status = (turn?.status as string) || (params.status as string) || "";
- if (status === "error" || status === "failed") {
- const turnErr = turn?.error as Record<string, unknown> | undefined;
- events.push({ kind: "error", message: (turnErr?.message as string) || "codex turn failed" });
- }
- events.push({ kind: "turn_end" });
- break;
- }
-
- case "error": {
- const errObj = params.error as Record<string, unknown> | undefined;
- const errMsg = (errObj?.message as string) || (params.message as string) || "";
- const willRetry = params.willRetry === true;
- if (errMsg && !willRetry) {
- events.push({ kind: "error", message: errMsg });
- }
- break;
- }
-
- case "thread/status/changed": {
- const statusObj = params.status as Record<string, unknown> | string | undefined;
- const statusType = typeof statusObj === "object" && statusObj !== null
- ? (statusObj.type as string) || ""
- : (statusObj as string) || "";
- if (statusType === "idle") {
- events.push({ kind: "turn_end" });
- }
- break;
- }
-
- case "item/started": {
- const item = params.item as Record<string, unknown> | undefined;
- if (!item) break;
- const itemType = item.type as string | undefined;
- if (itemType === "commandExecution" || itemType === "fileChange") {
- events.push({
- kind: "tool_call",
- name: itemType === "commandExecution" ? "exec_command" : "patch_apply",
- callId: item.id as string,
- input: item as Record<string, unknown>,
- });
- } else if (itemType === "mcpToolCall") {
- events.push({
- kind: "tool_call",
- name: `mcp_${(item.name as string) || "tool"}`,
- callId: item.id as string,
- input: item as Record<string, unknown>,
- });
- } else if (itemType === "webSearch") {
- events.push({
- kind: "tool_call",
- name: "web_search",
- callId: item.id as string,
- input: item as Record<string, unknown>,
- });
- } else if (itemType === "collabAgentToolCall") {
- events.push({
- kind: "tool_call",
- name: "collab_agent",
- callId: item.id as string,
- input: item as Record<string, unknown>,
- });
- } else if (itemType === "contextCompaction") {
- events.push({ kind: "compaction_started" });
- }
- break;
- }
-
- case "item/completed": {
- const item = params.item as Record<string, unknown> | undefined;
- if (!item) break;
- const itemType = item.type as string | undefined;
- if (itemType === "commandExecution") {
- events.push({ kind: "tool_output", callId: item.id as string, output: (item.aggregatedOutput as string) || "" });
- } else if (itemType === "fileChange") {
- events.push({ kind: "tool_output", callId: item.id as string, output: "" });
- } else if (itemType === "mcpToolCall") {
- events.push({ kind: "tool_output", callId: item.id as string, name: `mcp_${(item.name as string) || "tool"}`, output: (item.output as string) || "" });
- } else if (itemType === "agentMessage") {
- const flatText = item.text as string | undefined;
- if (flatText) {
- events.push({ kind: "text", text: flatText });
- } else {
- const content = item.content as { type: string; text?: string }[] | undefined;
- if (Array.isArray(content)) {
- for (const block of content) {
- if ((block.type === "output_text" || block.type === "text") && block.text) {
- events.push({ kind: "text", text: block.text });
- }
- }
- }
- }
- } else if (itemType === "reasoning") {
- events.push({ kind: "thinking", text: (item.text as string) || "" });
- } else if (itemType === "contextCompaction") {
- events.push({ kind: "compaction_finished" });
- }
- break;
- }
-
- case "item/agentMessage/delta": {
- const delta = params.delta as string | undefined;
- if (delta) events.push({ kind: "text", text: delta });
- break;
- }
-
- default:
- events.push({ kind: "log", content: JSON.stringify(msg), level: "debug" });
- }
- return events;
- }
-
- private parseLegacyEvent(params: Record<string, unknown>): ParsedEvent[] {
- const eventType = params.type as string | undefined;
- if (!eventType) return [];
-
- const events: ParsedEvent[] = [];
- switch (eventType) {
- case "agent_message": {
- const text = (params.text as string) || (params.message as string) || "";
- if (text) events.push({ kind: "text", text });
- break;
- }
- case "exec_command_begin":
- events.push({ kind: "tool_call", name: "exec_command", callId: params.id as string, input: params as Record<string, unknown> });
- break;
- case "exec_command_end":
- events.push({ kind: "tool_output", callId: params.id as string, output: (params.output as string) || "" });
- break;
- case "patch_apply_begin":
- events.push({ kind: "tool_call", name: "patch_apply", callId: params.id as string, input: params as Record<string, unknown> });
- break;
- case "patch_apply_end":
- events.push({ kind: "tool_output", callId: params.id as string, output: (params.output as string) || "" });
- break;
- case "task_complete":
- events.push({ kind: "turn_end" });
- break;
- case "turn_aborted":
- events.push({ kind: "turn_end" });
- break;
- default:
- break;
- }
- return events;
- }
-
- encodeStdinMessage(text: string, mode: StdinMode, opts?: EncodeOpts): string | null {
- const threadId = opts?.threadId;
- if (!threadId) return null;
- const id = opts?.requestId ?? ++this._rpcId;
- const method = mode === "busy" ? "turn/steer" : "turn/start";
- return JSON.stringify({
- jsonrpc: "2.0",
- id,
- method,
- params: {
- threadId,
- input: [{ type: "text", text }],
- },
- });
- }
-
- execute(prompt: string, options: ExecOptions): AgentSession {
- const isWin = process.platform === "win32";
- const rawArgs = ["app-server", "--listen", "stdio://", "--config", "sandbox_mode=danger-full-access"];
- const spawnCmd = isWin ? quoteWinArg(this.cliPath) : this.cliPath;
- const spawnArgs = isWin ? quoteWinArgs(rawArgs) : rawArgs;
-
- const proc = spawn(spawnCmd, spawnArgs, {
- cwd: options.cwd,
- stdio: ["pipe", "pipe", "pipe"],
- env: { ...process.env, ...options.env },
- shell: isWin,
- windowsHide: true,
- // POSIX: own process group (pgid === pid) so the session-runner can reap
- // the CLI *and* its spawned workers via a group kill. No unref() — we keep
- // the handle for stdio streaming and the result promise.
- detached: process.platform !== "win32",
- });
-
- if (!proc.pid) {
- const error = `Failed to start ${this.cliPath}: binary not found or not executable. Is 'codex' installed and on PATH?`;
- const failedResult: AgentResult = { status: "failed", output: "", error, durationMs: 0, sessionId: "" };
- const emptyMessages: AsyncIterable<AgentMessage> = { [Symbol.asyncIterator]() { return { async next() { return { value: undefined as unknown as AgentMessage, done: true }; } }; } };
- return { pid: undefined, messages: emptyMessages, sessionId: Promise.resolve(""), result: Promise.resolve(failedResult) };
- }
-
- let timedOut = false;
- let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
- if (options.timeout) {
- timeoutTimer = setTimeout(() => {
- timedOut = true;
- // Reap the whole group (CLI + spawned workers), not just the leader.
- if (proc.pid !== undefined) void killProcessTree(proc.pid);
- }, options.timeout);
- }
-
- const startTime = Date.now();
- let requestId = 0;
- let lastOutput = "";
- let lastError = "";
- let resultStatus: AgentResult["status"] = "completed";
- let sessionId = "";
- let resolveSessionId: (id: string) => void;
- const sessionIdPromise = new Promise<string>((resolve) => {
- resolveSessionId = resolve;
- });
-
- // Protocol detection state
- let notificationProtocol: NotificationProtocol = "unknown";
-
- // Turn lifecycle state
- let turnStarted = false;
- let turnDoneTriggered = false;
- let turnCompletedSuccessfully = false;
- let lastCompletedTurnId = "";
- let turnError = "";
-
- // Pending RPC callbacks
- const pendingRequests = new Map<
- number,
- { resolve: (value: unknown) => void; reject: (err: Error) => void }
- >();
-
- const messageQueue: AgentMessage[] = [];
- let messageResolve: (() => void) | null = null;
- let messageDone = false;
-
- const parsedEventQueue: ParsedEvent[] = [];
- let parsedEventResolve: (() => void) | null = null;
- let parsedEventDone = false;
-
- const pushMessage = (msg: AgentMessage) => {
- messageQueue.push(msg);
- if (messageResolve) {
- const r = messageResolve;
- messageResolve = null;
- r();
- }
- };
-
- const pushParsedEvent = (evt: ParsedEvent) => {
- parsedEventQueue.push(evt);
- if (parsedEventResolve) {
- const r = parsedEventResolve;
- parsedEventResolve = null;
- r();
- }
- };
-
- const writeStdin = (data: string) => {
- try {
- proc.stdin?.write(data + "\n");
- } catch {
- // stdin closed
- }
- };
-
- const sendRpc = (
- method: string,
- params: Record<string, unknown>,
- ): Promise<unknown> => {
- const id = ++requestId;
- const msg: JsonRpcMessage = { jsonrpc: "2.0", id, method, params };
- writeStdin(JSON.stringify(msg));
- return new Promise((resolve, reject) => {
- pendingRequests.set(id, { resolve, reject });
- });
- };
-
- const sendNotification = (method: string) => {
- const msg = { jsonrpc: "2.0" as const, method };
- writeStdin(JSON.stringify(msg));
- };
-
- const sendResponse = (id: number, result: unknown) => {
- const msg = { jsonrpc: "2.0" as const, id, result };
- writeStdin(JSON.stringify(msg));
- };
-
- /** Cancel all pending RPC requests. */
- const closeAllPending = (reason: string) => {
- for (const [, cb] of pendingRequests) {
- cb.reject(new Error(reason));
- }
- pendingRequests.clear();
- };
-
- const setTurnError = (msg: string) => {
- if (msg && !turnError) turnError = msg;
- };
-
- const steeringKeepAlive = options.steeringEnabled === true;
-
- const triggerTurnDone = (aborted: boolean) => {
- if (turnDoneTriggered) return;
- turnDoneTriggered = true;
- resultStatus = aborted ? "aborted" : "completed";
- if (!steeringKeepAlive) {
- try { proc.stdin?.end(); } catch { /* already closed */ }
- try { proc.kill("SIGTERM"); } catch { /* already dead */ }
- }
- };
-
- const handleServerRequest = (msg: JsonRpcMessage) => {
- const method = msg.method!;
- const id = msg.id!;
-
- switch (method) {
- case "item/commandExecution/requestApproval":
- case "execCommandApproval":
- case "item/fileChange/requestApproval":
- case "applyPatchApproval":
- sendResponse(id, { decision: "accept" });
- break;
- default:
- sendResponse(id, {});
- break;
- }
- };
-
- const handleNotification = (msg: JsonRpcMessage) => {
- const method = msg.method!;
- const params = msg.params || {};
-
- // Legacy protocol detection
- if (method === "codex/event") {
- if (notificationProtocol === "raw") return; // locked to raw, ignore legacy
- notificationProtocol = "legacy";
- handleLegacyEvent(params);
- return;
- }
-
- // Raw protocol detection — these methods trigger detection
- if (RAW_DETECTION_METHODS.has(method)) {
- if (notificationProtocol === "legacy") return; // locked to legacy, ignore raw
- notificationProtocol = "raw";
- }
-
- // thread/status/changed and error are raw-only but NOT detection triggers
- if ((method === "thread/status/changed" || method === "error") && notificationProtocol === "legacy") {
- return;
- }
-
- // Subagent thread filtering: ignore notifications from threads other than ours
- const notifThreadId = params.threadId as string | undefined;
- if (sessionId && notifThreadId && notifThreadId !== sessionId) {
- return;
- }
-
- switch (method) {
- case "turn/started": {
- turnStarted = true;
- break;
- }
-
- case "turn/completed": {
- const turn = params.turn as Record<string, unknown> | undefined;
- const turnId = (turn?.id as string) || (params.turnId as string) || "";
- if (turnId && turnId === lastCompletedTurnId) return;
- if (turnId) lastCompletedTurnId = turnId;
-
- const status = (turn?.status as string) || (params.status as string) || "";
- if (status === "completed" || status === "finished") {
- turnCompletedSuccessfully = true;
- triggerTurnDone(false);
- } else if (status === "cancelled" || status === "aborted" || status === "interrupted") {
- triggerTurnDone(true);
- } else if (status === "error" || status === "failed") {
- const turnErr = turn?.error as Record<string, unknown> | undefined;
- setTurnError((turnErr?.message as string) || "codex turn failed");
- triggerTurnDone(false);
- }
- break;
- }
-
- case "error": {
- const errObj = params.error as Record<string, unknown> | undefined;
- const errMsg = (errObj?.message as string) || (params.message as string) || "";
- const willRetry = params.willRetry === true;
- if (errMsg && !willRetry) {
- setTurnError(errMsg);
- }
- break;
- }
-
- case "thread/status/changed": {
- const statusObj = params.status as Record<string, unknown> | string | undefined;
- const statusType = typeof statusObj === "object" && statusObj !== null
- ? (statusObj.type as string) || ""
- : (statusObj as string) || "";
- if (statusType === "idle" && turnStarted) {
- triggerTurnDone(false);
- }
- break;
- }
-
- case "item/started": {
- const item = params.item as Record<string, unknown> | undefined;
- if (!item) break;
- const itemType = item.type as string | undefined;
-
- if (itemType === "commandExecution") {
- pushMessage({
- type: "tool-use",
- tool: "exec_command",
- callId: item.id as string,
- input: item as Record<string, unknown>,
- });
- } else if (itemType === "fileChange") {
- pushMessage({
- type: "tool-use",
- tool: "patch_apply",
- callId: item.id as string,
- input: item as Record<string, unknown>,
- });
- }
- break;
- }
-
- case "item/completed": {
- const item = params.item as Record<string, unknown> | undefined;
- if (!item) break;
- const itemType = item.type as string | undefined;
-
- if (itemType === "commandExecution") {
- const output = (item.aggregatedOutput as string) || "";
- pushMessage({
- type: "tool-result",
- callId: item.id as string,
- output,
- });
- } else if (itemType === "fileChange") {
- pushMessage({
- type: "tool-result",
- callId: item.id as string,
- output: "",
- });
- } else if (itemType === "agentMessage") {
- const flatText = item.text as string | undefined;
- if (flatText) {
- pushMessage({ type: "text", content: flatText });
- lastOutput = flatText;
- } else {
- const content = item.content as
- | { type: string; text?: string }[]
- | undefined;
- if (Array.isArray(content)) {
- for (const block of content) {
- if (block.type === "output_text" || block.type === "text") {
- if (block.text) {
- pushMessage({ type: "text", content: block.text });
- lastOutput = block.text;
- }
- }
- }
- }
- }
- const phase = item.phase as string | undefined;
- if (phase === "final_answer") {
- triggerTurnDone(false);
- }
- }
- break;
- }
-
- default: {
- pushMessage({
- type: "log",
- content: JSON.stringify(msg),
- level: "debug",
- });
- }
- }
- };
-
- const handleLegacyEvent = (params: Record<string, unknown>) => {
- const eventType = params.type as string | undefined;
- if (!eventType) return;
-
- switch (eventType) {
- case "task_started":
- break;
-
- case "agent_message": {
- const text = (params.text as string) || (params.message as string) || "";
- if (text) {
- pushMessage({ type: "text", content: text });
- lastOutput = text;
- }
- break;
- }
-
- case "exec_command_begin":
- pushMessage({
- type: "tool-use",
- tool: "exec_command",
- callId: params.id as string,
- input: params as Record<string, unknown>,
- });
- break;
-
- case "exec_command_end":
- pushMessage({
- type: "tool-result",
- callId: params.id as string,
- output: (params.output as string) || "",
- });
- break;
-
- case "patch_apply_begin":
- pushMessage({
- type: "tool-use",
- tool: "patch_apply",
- callId: params.id as string,
- input: params as Record<string, unknown>,
- });
- break;
-
- case "patch_apply_end":
- pushMessage({
- type: "tool-result",
- callId: params.id as string,
- output: (params.output as string) || "",
- });
- break;
-
- case "task_complete": {
- const output = params.output as string | undefined;
- if (output) lastOutput = output;
- triggerTurnDone(false);
- break;
- }
-
- case "turn_aborted":
- triggerTurnDone(true);
- break;
- }
- };
-
- const resultPromise = new Promise<AgentResult>((resolve) => {
- const stderrChunks: string[] = [];
-
- proc.stderr?.on("data", (chunk: Buffer) => {
- stderrChunks.push(chunk.toString());
- });
-
- const rl = createInterface({ input: proc.stdout! });
-
- rl.on("line", (line: string) => {
- if (!line.trim()) return;
-
- // Emit ParsedEvents for steering layer
- const parsed = this.parseLine(line);
- for (const pe of parsed) pushParsedEvent(pe);
-
- let msg: JsonRpcMessage;
- try {
- msg = JSON.parse(line);
- } catch {
- pushMessage({ type: "log", content: line, level: "debug" });
- return;
- }
-
- // Route: server request (has both id AND method)
- if (msg.id !== undefined && msg.method) {
- handleServerRequest(msg);
- return;
- }
-
- // Route: notification (has method, no id)
- if (msg.method && msg.id === undefined) {
- handleNotification(msg);
- return;
- }
-
- // Route: response (has id, no method) — both success and error
- if (msg.id !== undefined && !msg.method) {
- const pending = pendingRequests.get(msg.id);
- if (pending) {
- pendingRequests.delete(msg.id);
- if (msg.error) {
- pending.reject(new Error(msg.error.message));
- } else {
- pending.resolve(msg.result);
- }
- }
- return;
- }
-
- // Fallback
- pushMessage({
- type: "log",
- content: JSON.stringify(msg),
- level: "debug",
- });
- });
-
- // Handshake: initialize → initialized → thread/start → turn/start
- const startHandshake = async () => {
- try {
- // 1. Initialize
- await sendRpc("initialize", {
- clientInfo: {
- name: "alook-daemon",
- title: "Alook Agent SDK",
- version: "0.1.0",
- },
- capabilities: { experimentalApi: true },
- });
-
- // 2. Send initialized notification
- sendNotification("initialized");
-
- // 3. Start or resume thread
- let threadResponse: unknown;
- if (options.resumeSessionId) {
- // thread/resume reopens an existing thread by ID
- threadResponse = await sendRpc("thread/resume", {
- threadId: options.resumeSessionId,
- ...(options.model ? { model: options.model } : {}),
- });
- sessionId = options.resumeSessionId;
- } else {
- // thread/start creates a new thread
- const threadParams: Record<string, unknown> = {
- cwd: options.cwd,
- sandboxPolicy: { type: "dangerFullAccess" },
- approvalPolicy: "never",
- persistExtendedHistory: true,
- experimentalRawEvents: false,
- };
- if (options.model) {
- threadParams.model = options.model;
- }
- threadResponse = await sendRpc("thread/start", threadParams);
- sessionId = extractThreadID(threadResponse);
- }
-
- resolveSessionId(sessionId);
-
- // 5. Send turn/start with the prompt
- await sendRpc("turn/start", {
- threadId: sessionId,
- input: [{ type: "text", text: prompt }],
- sandboxPolicy: { type: "dangerFullAccess" },
- approvalPolicy: "never",
- });
- } catch (err) {
- const errMsg =
- err instanceof Error ? err.message : "handshake failed";
- lastError = errMsg;
- resultStatus = "failed";
- pushMessage({ type: "error", content: errMsg });
- }
- };
-
- startHandshake();
-
- proc.on("error", (err: Error) => {
- resultStatus = "failed";
- lastError = `spawn error: ${err.message}`;
- closeAllPending("spawn error");
- resolveSessionId(sessionId);
- messageDone = true;
- parsedEventDone = true;
- if (messageResolve) {
- const r = messageResolve;
- messageResolve = null;
- r();
- }
- if (parsedEventResolve) {
- const r = parsedEventResolve;
- parsedEventResolve = null;
- r();
- }
- resolve({
- status: "failed",
- output: "",
- error: lastError,
- durationMs: Date.now() - startTime,
- sessionId,
- });
- });
-
- proc.on("close", (code: number | null) => {
- if (timeoutTimer) clearTimeout(timeoutTimer);
-
- closeAllPending("process closed");
-
- if (timedOut) {
- resultStatus = "timeout";
- } else if (code !== 0 && resultStatus === "completed" && !turnCompletedSuccessfully) {
- // If agent already produced output, treat as completed despite non-zero exit
- // (e.g. MCP transport errors can crash the process after a successful response)
- if (!lastOutput) {
- resultStatus = "failed";
- }
- }
-
- const stderr = stderrChunks.join("").replace(/\x1b\[[0-9;]*m/g, "");
- if (stderr && !lastError) {
- lastError = stderr;
- }
-
- if (turnError) {
- resultStatus = "failed";
- lastError = turnError;
- }
-
- // Resolve sessionId promise (fallback if handshake never completed)
- resolveSessionId(sessionId);
-
- messageDone = true;
- parsedEventDone = true;
- if (messageResolve) {
- const r = messageResolve;
- messageResolve = null;
- r();
- }
- if (parsedEventResolve) {
- const r = parsedEventResolve;
- parsedEventResolve = null;
- r();
- }
-
- resolve({
- status: resultStatus,
- output: lastOutput,
- error: lastError,
- durationMs: Date.now() - startTime,
- sessionId,
- });
- });
- });
-
- const messages: AsyncIterable<AgentMessage> = {
- [Symbol.asyncIterator]() {
- return {
- async next(): Promise<IteratorResult<AgentMessage>> {
- while (messageQueue.length === 0 && !messageDone) {
- await new Promise<void>((resolve) => {
- messageResolve = resolve;
- });
- }
- if (messageQueue.length > 0) {
- return { value: messageQueue.shift()!, done: false };
- }
- return { value: undefined as unknown as AgentMessage, done: true };
- },
- };
- },
- };
-
- const parsedEvents: AsyncIterable<ParsedEvent> = {
- [Symbol.asyncIterator]() {
- return {
- async next(): Promise<IteratorResult<ParsedEvent>> {
- while (parsedEventQueue.length === 0 && !parsedEventDone) {
- await new Promise<void>((resolve) => {
- parsedEventResolve = resolve;
- });
- }
- if (parsedEventQueue.length > 0) {
- return { value: parsedEventQueue.shift()!, done: false };
- }
- return { value: undefined as unknown as ParsedEvent, done: true };
- },
- };
- },
- };
-
- const send = (text: string, mode: StdinMode): { ok: boolean; reason?: string } => {
- if (!proc.stdin || proc.stdin.destroyed) return { ok: false, reason: "stdin closed" };
- const encoded = this.encodeStdinMessage(text, mode, { threadId: sessionId, requestId: ++requestId });
- if (!encoded) return { ok: false, reason: "encoding failed (no threadId)" };
- writeStdin(encoded);
- return { ok: true };
- };
-
- const descriptor = {
- lifecycle: this.lifecycle,
- busyDeliveryMode: this.busyDeliveryMode,
- supportsStdinNotification: this.supportsStdinNotification,
- };
-
- const closeStdin = () => {
- try {
- if (proc.stdin && !proc.stdin.destroyed) proc.stdin.end();
- } catch { /* already closed */ }
- };
-
- return { pid: proc.pid, messages, parsedEvents, sessionId: sessionIdPromise, result: resultPromise, send, closeStdin, descriptor };
- }
-}
diff --git a/src/cli/daemon/agent/index.ts b/src/cli/daemon/agent/index.ts
deleted file mode 100644
index d282bcc09..000000000
--- a/src/cli/daemon/agent/index.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import type {
- ExecOptions,
- AgentMessage,
- AgentResult,
- ParsedEvent,
- StdinMode,
- RuntimeSessionDescriptor,
- DriverLifecycle,
- BusyDeliveryMode,
- EncodeOpts,
-} from "../types.js";
-import { ClaudeBackend } from "./claude.js";
-import { CodexBackend } from "./codex.js";
-import { OpenCodeBackend } from "./opencode.js";
-import { execSync } from "child_process";
-
-export interface AgentSession {
- pid: number | undefined;
- messages: AsyncIterable<AgentMessage>;
- parsedEvents?: AsyncIterable<ParsedEvent>;
- sessionId: Promise<string>;
- result: Promise<AgentResult>;
- send?(text: string, mode: StdinMode): { ok: boolean; reason?: string };
- closeStdin?(): void;
- descriptor?: RuntimeSessionDescriptor;
-}
-
-export interface AgentBackend {
- name: string;
- execute(prompt: string, options: ExecOptions): AgentSession;
- lifecycle?: DriverLifecycle;
- busyDeliveryMode?: BusyDeliveryMode;
- supportsStdinNotification?: boolean;
- parseLine?(line: string): ParsedEvent[];
- encodeStdinMessage?(text: string, mode: StdinMode, opts?: EncodeOpts): string | null;
-}
-
-export function createBackend(
- provider: string,
- cliPath: string,
-): AgentBackend {
- switch (provider) {
- case "claude":
- return new ClaudeBackend(cliPath);
- case "codex":
- return new CodexBackend(cliPath);
- case "opencode":
- return new OpenCodeBackend(cliPath);
- default:
- throw new Error(`Unknown provider: ${provider}`);
- }
-}
-
-export async function detectVersion(cliPath: string): Promise<string> {
- try {
- return execSync(`${cliPath} --version`, { encoding: "utf-8" }).trim();
- } catch {
- return "unknown";
- }
-}
diff --git a/src/cli/daemon/agent/opencode.ts b/src/cli/daemon/agent/opencode.ts
deleted file mode 100644
index f714bbc77..000000000
--- a/src/cli/daemon/agent/opencode.ts
+++ /dev/null
@@ -1,477 +0,0 @@
-import { spawn } from "child_process";
-import { createInterface } from "readline";
-import type { AgentBackend, AgentSession } from "./index.js";
-import type {
- ExecOptions,
- AgentMessage,
- AgentResult,
- ParsedEvent,
- DriverLifecycle,
- BusyDeliveryMode,
-} from "../types.js";
-import { killProcessTree } from "../kill-tree.js";
-import { quoteWinArg, quoteWinArgs } from "./win-quote.js";
-
-export class OpenCodeBackend implements AgentBackend {
- name = "opencode";
- lifecycle: DriverLifecycle = { kind: "per_turn", inFlightWake: "coalesce_into_pending" };
- busyDeliveryMode: BusyDeliveryMode = "none";
- supportsStdinNotification = false;
-
- constructor(private cliPath: string) {}
-
- parseLine(line: string): ParsedEvent[] {
- if (!line.trim()) return [];
- let event: Record<string, unknown>;
- try {
- event = JSON.parse(line);
- } catch {
- return [{ kind: "log", content: line, level: "debug" }];
- }
-
- const events: ParsedEvent[] = [];
- const eventType = event.type as string | undefined;
- const part = event.part as Record<string, unknown> | undefined;
-
- const eventSessionId = (event.sessionID as string) || (event.session_id as string);
-
- switch (eventType) {
- case "session": {
- const sessionId = event.session_id as string | undefined;
- if (sessionId) events.push({ kind: "session_init", sessionId });
- break;
- }
-
- case "message": {
- const role = event.role as string | undefined;
- const content = event.content as string | undefined;
- if (role === "assistant" && content) {
- events.push({ kind: "text", text: content });
- }
- break;
- }
-
- case "text": {
- const text = (part?.text as string) || (event.content as string) || "";
- if (text) events.push({ kind: "text", text });
- break;
- }
-
- case "thinking": {
- const content = (part?.thinking as string) || (event.content as string) || "";
- events.push({ kind: "thinking", text: content });
- break;
- }
-
- case "tool_call":
- events.push({
- kind: "tool_call",
- name: (event.name as string) || (part?.name as string) || "",
- callId: (event.call_id as string) || (part?.id as string) || "",
- input: (event.input as Record<string, unknown>) || (part?.input as Record<string, unknown>),
- });
- break;
-
- case "tool_result":
- events.push({
- kind: "tool_output",
- callId: (event.call_id as string) || (part?.id as string) || "",
- output: (event.output as string) || (part?.output as string) || "",
- });
- break;
-
- case "error": {
- const content = (event.message as string) || (event.content as string) || (part?.error as string) || "";
- events.push({ kind: "error", message: content });
- events.push({ kind: "turn_end" });
- break;
- }
-
- case "step_start":
- break;
-
- case "step_finish": {
- const reason = part?.reason as string | undefined;
- if (reason === "stop" || reason === "end_turn") {
- events.push({ kind: "turn_end" });
- }
- break;
- }
-
- case "done":
- case "complete": {
- const status = event.status as string | undefined;
- if (status === "error" || status === "failed") {
- const output = event.output as string | undefined;
- events.push({ kind: "error", message: output || "task failed" });
- }
- events.push({ kind: "turn_end" });
- break;
- }
-
- default:
- events.push({ kind: "log", content: line, level: "debug" });
- }
-
- // Attach session info if available as first event
- if (eventSessionId && events.length > 0 && events[0].kind !== "session_init") {
- events.unshift({ kind: "session_init", sessionId: eventSessionId });
- }
-
- return events;
- }
-
- encodeStdinMessage(): string | null {
- return null;
- }
-
- execute(prompt: string, options: ExecOptions): AgentSession {
- const args = ["run", "--format", "json", "--dir", options.cwd];
-
- if (options.model) {
- args.push("--model", options.model);
- }
- if (options.resumeSessionId) {
- args.push("--session", options.resumeSessionId);
- }
-
- // User prompt as positional argument (no flag)
- args.push(prompt);
-
- // spawn({ shell: true }) on Windows joins args with spaces without quoting
- // — see win-quote.ts. Pre-quote so args with spaces (workspace paths under
- // C:\Users\<name with space>\.alook\...) survive cmd.exe parsing.
- const isWin = process.platform === "win32";
- const spawnCmd = isWin ? quoteWinArg(this.cliPath) : this.cliPath;
- const spawnArgs = isWin ? quoteWinArgs(args) : args;
-
- const proc = spawn(spawnCmd, spawnArgs, {
- cwd: options.cwd,
- stdio: ["ignore", "pipe", "pipe"],
- env: { ...process.env, ...options.env, OPENCODE_PERMISSION: '{"*":"allow"}' },
- shell: isWin,
- windowsHide: true,
- // POSIX: own process group (pgid === pid) so the session-runner can reap
- // the CLI *and* its tool subprocesses via a group kill. No unref() — we
- // keep the handle for stdio streaming and the result promise.
- detached: process.platform !== "win32",
- });
-
- if (!proc.pid) {
- const error = `Failed to start ${this.cliPath}: binary not found or not executable. Is 'opencode' installed and on PATH?`;
- const failedResult: AgentResult = { status: "failed", output: "", error, durationMs: 0, sessionId: "" };
- const emptyMessages: AsyncIterable<AgentMessage> = { [Symbol.asyncIterator]() { return { async next() { return { value: undefined as unknown as AgentMessage, done: true }; } }; } };
- return { pid: undefined, messages: emptyMessages, sessionId: Promise.resolve(""), result: Promise.resolve(failedResult) };
- }
-
- let timedOut = false;
- let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
- if (options.timeout) {
- timeoutTimer = setTimeout(() => {
- timedOut = true;
- // Reap the whole group (CLI + tool subprocesses), not just the leader.
- if (proc.pid !== undefined) void killProcessTree(proc.pid);
- }, options.timeout);
- }
-
- const startTime = Date.now();
- let lastSessionId = "";
- let lastOutput = "";
- let lastError = "";
- let resultStatus: AgentResult["status"] = "completed";
- let resolveSessionId: (id: string) => void;
- const sessionIdPromise = new Promise<string>((resolve) => {
- resolveSessionId = resolve;
- });
-
- let turnDoneTriggered = false;
- const turnDone = () => {
- if (turnDoneTriggered) return;
- turnDoneTriggered = true;
- try { proc.kill("SIGTERM"); } catch { /* already dead */ }
- };
-
- const messageQueue: AgentMessage[] = [];
- let messageResolve: (() => void) | null = null;
- let messageDone = false;
-
- const parsedEventQueue: ParsedEvent[] = [];
- let parsedEventResolve: (() => void) | null = null;
- let parsedEventDone = false;
-
- const pushMessage = (msg: AgentMessage) => {
- messageQueue.push(msg);
- if (messageResolve) {
- const r = messageResolve;
- messageResolve = null;
- r();
- }
- };
-
- const pushParsedEvent = (evt: ParsedEvent) => {
- parsedEventQueue.push(evt);
- if (parsedEventResolve) {
- const r = parsedEventResolve;
- parsedEventResolve = null;
- r();
- }
- };
-
- const resultPromise = new Promise<AgentResult>((resolve) => {
- const stderrChunks: string[] = [];
-
- proc.stderr?.on("data", (chunk: Buffer) => {
- stderrChunks.push(chunk.toString());
- });
-
- const rl = createInterface({ input: proc.stdout! });
-
- rl.on("line", (line: string) => {
- if (!line.trim()) return;
-
- // Emit ParsedEvents for steering layer
- const parsed = this.parseLine(line);
- for (const pe of parsed) pushParsedEvent(pe);
-
- let event: Record<string, unknown>;
- try {
- event = JSON.parse(line);
- } catch {
- pushMessage({ type: "log", content: line, level: "debug" });
- return;
- }
-
- const eventType = event.type as string | undefined;
- const part = event.part as Record<string, unknown> | undefined;
-
- // Extract sessionID from any event (v1.14+ format)
- const eventSessionId = (event.sessionID as string) || (event.session_id as string);
- if (eventSessionId && !lastSessionId) {
- lastSessionId = eventSessionId;
- resolveSessionId(eventSessionId);
- }
-
- switch (eventType) {
- case "session": {
- const sessionId = event.session_id as string | undefined;
- if (sessionId) {
- lastSessionId = sessionId;
- resolveSessionId(sessionId);
- }
- break;
- }
-
- case "message": {
- const role = event.role as string | undefined;
- const content = event.content as string | undefined;
- if (role === "assistant" && content) {
- lastOutput = content;
- pushMessage({ type: "text", content });
- }
- break;
- }
-
- // v1.14+ format: { type: "text", part: { text: "..." } }
- case "text": {
- const text = (part?.text as string) || (event.content as string) || "";
- if (text) {
- lastOutput = text;
- pushMessage({ type: "text", content: text });
- }
- break;
- }
-
- case "thinking": {
- const content = (part?.thinking as string) || (event.content as string) || "";
- pushMessage({ type: "thinking", content });
- break;
- }
-
- case "tool_call": {
- pushMessage({
- type: "tool-use",
- tool: (event.name as string) || (part?.name as string) || "",
- callId: (event.call_id as string) || (part?.id as string) || "",
- input: (event.input as Record<string, unknown>) || (part?.input as Record<string, unknown>),
- });
- break;
- }
-
- case "tool_result": {
- pushMessage({
- type: "tool-result",
- callId: (event.call_id as string) || (part?.id as string) || "",
- output: (event.output as string) || (part?.output as string) || "",
- });
- break;
- }
-
- case "error": {
- const content = (event.message as string) || (event.content as string) || (part?.error as string) || "";
- lastError = content;
- // Mark the run failed (matches codex.ts + the done/spawn-error branches
- // below). Without this the run ends "completed", failTask never runs,
- // no assistant error message is persisted, and the error is lost on
- // reload — it only ever showed via the live task.messages broadcast.
- resultStatus = "failed";
- pushMessage({ type: "error", content });
- turnDone();
- break;
- }
-
- // v1.14+ signals
- case "step_start": {
- break;
- }
-
- case "step_finish": {
- const reason = part?.reason as string | undefined;
- if (reason === "stop" || reason === "end_turn") {
- turnDone();
- }
- break;
- }
-
- case "done":
- case "complete": {
- const output = event.output as string | undefined;
- const status = event.status as string | undefined;
- const sessionId = event.session_id as string | undefined;
-
- if (output) lastOutput = output;
- if (sessionId) lastSessionId = sessionId;
-
- if (status === "error" || status === "failed") {
- resultStatus = "failed";
- if (!lastError) lastError = output || "task failed";
- }
- turnDone();
- break;
- }
-
- default: {
- pushMessage({
- type: "log",
- content: line,
- level: "debug",
- });
- }
- }
- });
-
- proc.on("error", (err: Error) => {
- resultStatus = "failed";
- lastError = `spawn error: ${err.message}`;
- resolveSessionId(lastSessionId);
- messageDone = true;
- parsedEventDone = true;
- if (messageResolve) {
- const r = messageResolve;
- messageResolve = null;
- r();
- }
- if (parsedEventResolve) {
- const r = parsedEventResolve;
- parsedEventResolve = null;
- r();
- }
- resolve({
- status: "failed",
- output: "",
- error: lastError,
- durationMs: Date.now() - startTime,
- sessionId: lastSessionId,
- });
- });
-
- proc.on("close", (code: number | null) => {
- if (timeoutTimer) clearTimeout(timeoutTimer);
-
- if (timedOut) {
- resultStatus = "timeout";
- } else if (code !== 0 && resultStatus === "completed" && !turnDoneTriggered) {
- if (!lastOutput) {
- resultStatus = "failed";
- }
- }
-
- const stderr = stderrChunks.join("");
- if (stderr && !lastError) {
- lastError = stderr;
- }
-
- // Resolve sessionId promise (fallback if session event never fired)
- resolveSessionId(lastSessionId);
-
- messageDone = true;
- parsedEventDone = true;
- if (messageResolve) {
- const r = messageResolve;
- messageResolve = null;
- r();
- }
- if (parsedEventResolve) {
- const r = parsedEventResolve;
- parsedEventResolve = null;
- r();
- }
-
- resolve({
- status: resultStatus,
- output: lastOutput,
- error: lastError,
- durationMs: Date.now() - startTime,
- sessionId: lastSessionId,
- });
- });
- });
-
- const messages: AsyncIterable<AgentMessage> = {
- [Symbol.asyncIterator]() {
- return {
- async next(): Promise<IteratorResult<AgentMessage>> {
- while (messageQueue.length === 0 && !messageDone) {
- await new Promise<void>((resolve) => {
- messageResolve = resolve;
- });
- }
- if (messageQueue.length > 0) {
- return { value: messageQueue.shift()!, done: false };
- }
- return { value: undefined as unknown as AgentMessage, done: true };
- },
- };
- },
- };
-
- const parsedEvents: AsyncIterable<ParsedEvent> = {
- [Symbol.asyncIterator]() {
- return {
- async next(): Promise<IteratorResult<ParsedEvent>> {
- while (parsedEventQueue.length === 0 && !parsedEventDone) {
- await new Promise<void>((resolve) => {
- parsedEventResolve = resolve;
- });
- }
- if (parsedEventQueue.length > 0) {
- return { value: parsedEventQueue.shift()!, done: false };
- }
- return { value: undefined as unknown as ParsedEvent, done: true };
- },
- };
- },
- };
-
- const send = (): { ok: boolean; reason?: string } => {
- return { ok: false, reason: "unsupported" };
- };
-
- const descriptor = {
- lifecycle: this.lifecycle,
- busyDeliveryMode: this.busyDeliveryMode,
- supportsStdinNotification: this.supportsStdinNotification,
- };
-
- return { pid: proc.pid, messages, parsedEvents, sessionId: sessionIdPromise, result: resultPromise, send, descriptor };
- }
-}
diff --git a/src/cli/daemon/agent/win-quote.ts b/src/cli/daemon/agent/win-quote.ts
deleted file mode 100644
index 5796fe36d..000000000
--- a/src/cli/daemon/agent/win-quote.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-// Windows argument quoting for spawn({ shell: true }).
-//
-// Node's child_process.spawn does NOT quote individual args when `shell: true`
-// is set on Windows — it joins them with spaces and hands the raw string to
-// cmd.exe. Any arg containing whitespace (e.g. --dir C:\Users\John Doe\...) is
-// then split by cmd, causing "Failed to change dir to C:\Users\John".
-//
-// We can't drop `shell: true` because Node has blocked spawning .cmd/.bat
-// shims without a shell since CVE-2024-27980, and every npm-installed CLI we
-// launch (opencode, claude, codex) lands as a .cmd shim on Windows. So we
-// pre-quote each argument here.
-//
-// Strategy: wrap in double quotes whenever the arg contains whitespace or any
-// cmd.exe metachar (& | < > ^ ( ) " %), then apply the MSVCRT rules for
-// escaping backslashes and inner quotes. Inside "..." cmd itself does not
-// interpret & | < > ^ ( ) — so no ^-escaping is needed once quoted.
-//
-// Known cmd.exe residuals (out of scope for this helper — they are limitations
-// of ALL shell:true spawns on Windows, not regressions of this fix):
-// - CR/LF inside an arg terminates the cmd command line. Multi-line prompts
-// have to be delivered via stdin or a temp file, not argv, on Windows.
-// - %VAR% still expands inside "...". There is no reliable command-line
-// escape for % on Windows (%% only works in batch files). If arbitrary
-// user text with literal % must reach the child, use stdin.
-// Both were broken before this fix and remain broken; the space-in-path bug
-// (the reported one) is fully addressed.
-
-const NEEDS_QUOTING = /[\s"&|<>^()%]/;
-
-export function quoteWinArg(arg: string): string {
- if (arg.length > 0 && !NEEDS_QUOTING.test(arg)) return arg;
-
- let result = "\"";
- let backslashes = 0;
- for (const ch of arg) {
- if (ch === "\\") {
- backslashes++;
- continue;
- }
- if (ch === "\"") {
- result += "\\".repeat(backslashes * 2 + 1) + "\"";
- } else {
- result += "\\".repeat(backslashes) + ch;
- }
- backslashes = 0;
- }
- result += "\\".repeat(backslashes * 2) + "\"";
- return result;
-}
-
-export function quoteWinArgs(args: string[]): string[] {
- return args.map(quoteWinArg);
-}
diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.ts
deleted file mode 100644
index adaf79b3b..000000000
--- a/src/cli/daemon/client.test.ts
+++ /dev/null
@@ -1,569 +0,0 @@
-import { describe, it, expect, vi, afterEach } from "vitest";
-import { fromApiTask } from "./types.js";
-import type { TaskApi } from "@alook/shared";
-import { PollResponseSchema } from "@alook/shared";
-import { DaemonClient } from "./client.js";
-
-// ---------------------------------------------------------------------------
-// Schema-level validation tests
-// ---------------------------------------------------------------------------
-
-describe("PollResponseSchema validation", () => {
- it("parses valid response with tasks", () => {
- const raw = {
- tasks: [{
- id: "t1",
- agent_id: "a1",
- runtime_id: "r1",
- conversation_id: "c1",
- workspace_id: "w1",
- prompt: "do it",
- status: "dispatched",
- priority: 1,
- dispatched_at: "2024-01-01T00:00:00Z",
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: "2024-01-01T00:00:00Z",
- type: "user_dm_message",
- agent: { instructions: "help", name: "bot", runtime_config: {} },
- }],
- };
-
- const parsed = PollResponseSchema.parse(raw);
- expect(parsed.tasks).toHaveLength(1);
- expect(parsed.tasks[0].id).toBe("t1");
- expect(parsed.tasks[0].agent?.name).toBe("bot");
- });
-
- it("parses response with pending_rescan", () => {
- const parsed = PollResponseSchema.parse({ tasks: [], pending_rescan: true });
- expect(parsed.pending_rescan).toBe(true);
- });
-
- it("parses response without pending_rescan (optional)", () => {
- const parsed = PollResponseSchema.parse({ tasks: [] });
- expect(parsed.pending_rescan).toBeUndefined();
- });
-
- it("parses empty tasks array", () => {
- const parsed = PollResponseSchema.parse({ tasks: [] });
- expect(parsed.tasks).toEqual([]);
- });
-
- it("throws ZodError when tasks contains invalid items", () => {
- const raw = { tasks: [{ id: "t1" }] }; // missing required fields
- expect(() => PollResponseSchema.parse(raw)).toThrow();
- });
-
- it("parses task with email_handle in agent data", () => {
- const raw = {
- tasks: [{
- id: "t1",
- agent_id: "a1",
- runtime_id: "r1",
- conversation_id: "c1",
- workspace_id: "w1",
- prompt: "do it",
- status: "dispatched",
- priority: 1,
- dispatched_at: "2024-01-01T00:00:00Z",
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: "2024-01-01T00:00:00Z",
- type: "user_dm_message",
- agent: { instructions: "help", name: "bot", runtime_config: {}, email_handle: "myagent" },
- }],
- };
-
- const parsed = PollResponseSchema.parse(raw);
- expect(parsed.tasks[0].agent?.email_handle).toBe("myagent");
- });
-
- it("parses task with null email_handle", () => {
- const raw = {
- tasks: [{
- id: "t1",
- agent_id: "a1",
- runtime_id: "r1",
- conversation_id: "c1",
- workspace_id: "w1",
- prompt: "do it",
- status: "dispatched",
- priority: 1,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: "2024-01-01T00:00:00Z",
- type: "user_dm_message",
- agent: { instructions: "help", name: "bot", runtime_config: {}, email_handle: null },
- }],
- };
-
- const parsed = PollResponseSchema.parse(raw);
- expect(parsed.tasks[0].agent?.email_handle).toBeNull();
- });
-});
-
-// ---------------------------------------------------------------------------
-// DaemonClient.poll() integration tests with mocked fetch
-// ---------------------------------------------------------------------------
-
-function validPollResponse() {
- return {
- tasks: [{
- id: "t1",
- agent_id: "a1",
- runtime_id: "r1",
- conversation_id: "c1",
- workspace_id: "w1",
- prompt: "do it",
- status: "dispatched",
- priority: 1,
- dispatched_at: "2024-01-01T00:00:00Z",
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: "2024-01-01T00:00:00Z",
- type: "user_dm_message",
- }],
- };
-}
-
-describe("DaemonClient.poll() with mocked fetch", () => {
- const originalFetch = globalThis.fetch;
-
- afterEach(() => {
- globalThis.fetch = originalFetch;
- });
-
- it("sends correct POST body with daemon_id to /api/daemon/tasks/poll", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ tasks: [] }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- await client.poll("tok", "d1", 3);
-
- expect(globalThis.fetch).toHaveBeenCalledWith(
- "http://localhost:8080/api/daemon/tasks/poll",
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({ daemon_id: "d1", max_tasks: 3 }),
- }),
- );
- });
-
- it("passes token in Authorization header per-call", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ tasks: [] }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- await client.poll("my_token_123", "d1", 1);
-
- expect(globalThis.fetch).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({
- headers: expect.objectContaining({
- Authorization: "Bearer my_token_123",
- }),
- }),
- );
- });
-
- it("returns tasks and evicted: false on valid response", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve(validPollResponse()),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- const result = await client.poll("tok", "d1", 1);
- expect(result.tasks).toHaveLength(1);
- expect(result.tasks[0].id).toBe("t1");
- expect(result.evicted).toBe(false);
- });
-
- it("returns empty tasks and evicted: false when no tasks", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ tasks: [] }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- const result = await client.poll("tok", "d1", 1);
- expect(result.tasks).toEqual([]);
- expect(result.evicted).toBe(false);
- });
-
- it("returns pending_rescan when present in response", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ tasks: [], pending_rescan: true }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- const result = await client.poll("tok", "d1", 1);
- expect(result.tasks).toEqual([]);
- expect(result.pending_rescan).toBe(true);
- });
-
- it("returns undefined pending_rescan when absent", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ tasks: [] }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- const result = await client.poll("tok", "d1", 1);
- expect(result.pending_rescan).toBeUndefined();
- });
-
- it("returns evicted: true when server signals eviction", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ tasks: [], evicted: true }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- const result = await client.poll("tok", "d1", 1);
- expect(result.tasks).toEqual([]);
- expect(result.evicted).toBe(true);
- });
-
- it("throws ZodError when API returns wrong shape", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ unexpected: "data" }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- await expect(client.poll("tok", "d1", 1)).rejects.toThrow();
- });
-});
-
-// ---------------------------------------------------------------------------
-// DaemonClient.register() tests
-// ---------------------------------------------------------------------------
-
-describe("DaemonClient.register() with mocked fetch", () => {
- const originalFetch = globalThis.fetch;
-
- afterEach(() => {
- globalThis.fetch = originalFetch;
- });
-
- it("returns parsed RegisterResponse on valid response", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ runtimes: [{ id: "rt1" }] }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- const resp = await client.register("tok", {
- workspace_id: "w1",
- daemon_id: "d1",
- device_name: "mac",
- cli_version: "1.0",
- workspaces_root: "/home/.alook/workspaces",
- runtimes: [{ type: "claude", version: "1.0" }],
- });
- expect(resp.runtimes[0].id).toBe("rt1");
- });
-
- it("passes token in Authorization header", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ runtimes: [{ id: "rt1" }] }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- await client.register("my_ws_token", {
- workspace_id: "w1",
- daemon_id: "d1",
- device_name: "mac",
- cli_version: "1.0",
- workspaces_root: "/home/.alook/workspaces",
- runtimes: [{ type: "claude", version: "1.0" }],
- });
-
- expect(globalThis.fetch).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({
- headers: expect.objectContaining({
- Authorization: "Bearer my_ws_token",
- }),
- }),
- );
- });
-});
-
-// ---------------------------------------------------------------------------
-// DaemonClient.deregister() tests
-// ---------------------------------------------------------------------------
-
-describe("DaemonClient.deregister() with mocked fetch", () => {
- const originalFetch = globalThis.fetch;
-
- afterEach(() => {
- globalThis.fetch = originalFetch;
- });
-
- it("sends daemon_id in body", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 204,
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- await client.deregister("tok", "d1");
-
- expect(globalThis.fetch).toHaveBeenCalledWith(
- "http://localhost:8080/api/daemon/deregister",
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({ daemon_id: "d1" }),
- }),
- );
- });
-});
-
-// ---------------------------------------------------------------------------
-// DaemonClient fetch retry tests
-// ---------------------------------------------------------------------------
-
-describe("DaemonClient retries on TypeError (network failure)", () => {
- const originalFetch = globalThis.fetch;
-
- afterEach(() => {
- globalThis.fetch = originalFetch;
- });
-
- it("retries up to 3 times on TypeError then succeeds", async () => {
- const fetchMock = vi.fn()
- .mockRejectedValueOnce(new TypeError("fetch failed"))
- .mockRejectedValueOnce(new TypeError("fetch failed"))
- .mockResolvedValueOnce({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ tasks: [] }),
- });
- globalThis.fetch = fetchMock as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- const result = await client.poll("tok", "d1", 1);
-
- expect(result.tasks).toEqual([]);
- expect(fetchMock).toHaveBeenCalledTimes(3);
- });
-
- it("throws TypeError after exhausting all retries", async () => {
- const fetchMock = vi.fn().mockRejectedValue(new TypeError("fetch failed"));
- globalThis.fetch = fetchMock as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- await expect(client.poll("tok", "d1", 1)).rejects.toThrow(TypeError);
-
- expect(fetchMock).toHaveBeenCalledTimes(4); // 1 initial + 3 retries
- });
-
- it("does not retry on non-TypeError errors (e.g. HTTP errors)", async () => {
- const fetchMock = vi.fn().mockResolvedValue({
- ok: false,
- status: 500,
- text: () => Promise.resolve("Internal Server Error"),
- });
- globalThis.fetch = fetchMock as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- await expect(client.completeTask("tok", "t1", { output: "done" })).rejects.toThrow("HTTP 500");
-
- expect(fetchMock).toHaveBeenCalledTimes(1);
- });
-
- it("retries downloadArtifact on TypeError", async () => {
- const fetchMock = vi.fn()
- .mockRejectedValueOnce(new TypeError("fetch failed"))
- .mockResolvedValueOnce({
- ok: true,
- arrayBuffer: () => Promise.resolve(new ArrayBuffer(4)),
- });
- globalThis.fetch = fetchMock as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- const buf = await client.downloadArtifact("tok", "art1", "ws1");
-
- expect(buf.byteLength).toBe(4);
- expect(fetchMock).toHaveBeenCalledTimes(2);
- });
-});
-
-// ---------------------------------------------------------------------------
-// DaemonClient.heartbeat() tests
-// ---------------------------------------------------------------------------
-
-describe("DaemonClient.heartbeat() with mocked fetch", () => {
- const originalFetch = globalThis.fetch;
-
- afterEach(() => {
- globalThis.fetch = originalFetch;
- });
-
- it("sends daemon_id in body to /api/daemon/heartbeat", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ ok: true }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- await client.heartbeat("tok", "d1");
-
- expect(globalThis.fetch).toHaveBeenCalledWith(
- "http://localhost:8080/api/daemon/heartbeat",
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({ daemon_id: "d1" }),
- }),
- );
- });
-});
-
-// ---------------------------------------------------------------------------
-// DaemonClient.sweep() tests
-// ---------------------------------------------------------------------------
-
-describe("DaemonClient.sweep() with mocked fetch", () => {
- const originalFetch = globalThis.fetch;
-
- afterEach(() => {
- globalThis.fetch = originalFetch;
- });
-
- it("sends daemon_id in body to /api/daemon/sweep", async () => {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ ok: true }),
- }) as unknown as typeof fetch;
-
- const client = new DaemonClient("http://localhost:8080");
- await client.sweep("tok", "d1");
-
- expect(globalThis.fetch).toHaveBeenCalledWith(
- "http://localhost:8080/api/daemon/sweep",
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({ daemon_id: "d1" }),
- }),
- );
- });
-});
-
-// ---------------------------------------------------------------------------
-
-// ---------------------------------------------------------------------------
-// DaemonClient removed methods
-// ---------------------------------------------------------------------------
-
-describe("DaemonClient removed methods", () => {
- it("does not have claimTask method", () => {
- const client = new DaemonClient("http://localhost:8080");
- expect((client as any).claimTask).toBeUndefined();
- });
-});
-
-// ---------------------------------------------------------------------------
-// fromApiTask tests (unchanged)
-// ---------------------------------------------------------------------------
-
-function validApiTask(): TaskApi {
- return {
- id: "t1",
- agent_id: "a1",
- runtime_id: "r1",
- conversation_id: "c1",
- workspace_id: "w1",
- prompt: "do it",
- status: "dispatched",
- priority: 1,
- dispatched_at: "2024-01-01T00:00:00Z",
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: "2024-01-01T00:00:00Z",
- type: "user_dm_message",
- agent: { instructions: "help", name: "bot", runtime_config: {}, email_addresses: [], colleagues: [] },
- };
-}
-
-describe("fromApiTask", () => {
- it("correctly maps snake_case API response to camelCase Task", () => {
- const task = fromApiTask(validApiTask());
- expect(task.id).toBe("t1");
- expect(task.agentId).toBe("a1");
- expect(task.runtimeId).toBe("r1");
- expect(task.conversationId).toBe("c1");
- expect(task.workspaceId).toBe("w1");
- expect(task.prompt).toBe("do it");
- expect(task.status).toBe("dispatched");
- expect(task.priority).toBe(1);
- expect(task.type).toBe("user_dm_message");
- expect(task.agent?.name).toBe("bot");
- expect(task.agent?.instructions).toBe("help");
- expect(task.createdAt).toBe("2024-01-01T00:00:00Z");
- });
-
- it("handles missing repos field (defaults to undefined)", () => {
- const task = fromApiTask(validApiTask());
- expect(task.repos).toBeUndefined();
- });
-
- it("handles missing agent.id field (optional in API)", () => {
- const api = validApiTask();
- const task = fromApiTask(api);
- expect(task.agent?.id).toBeUndefined();
- expect(task.agent?.name).toBe("bot");
- });
-
- it("maps email_handle to emailHandle", () => {
- const api = validApiTask();
- api.agent = { instructions: "help", name: "bot", runtime_config: {}, email_handle: "myagent", email_addresses: [], colleagues: [] };
- const task = fromApiTask(api);
- expect(task.agent?.emailHandle).toBe("myagent");
- });
-
- it("maps null email_handle to undefined", () => {
- const api = validApiTask();
- api.agent = { instructions: "help", name: "bot", runtime_config: {}, email_handle: null, email_addresses: [], colleagues: [] };
- const task = fromApiTask(api);
- expect(task.agent?.emailHandle).toBeUndefined();
- });
-
- it("maps missing email_handle to undefined", () => {
- const api = validApiTask();
- // No email_handle field at all
- const task = fromApiTask(api);
- expect(task.agent?.emailHandle).toBeUndefined();
- });
-});
diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.ts
deleted file mode 100644
index c21062599..000000000
--- a/src/cli/daemon/client.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import {
- PollResponseSchema,
- RegisterResponseSchema,
- type CompleteTaskRequest,
- type FileRequestItem,
- type MessageItem,
- type PollMeetingItem,
- type PollResponse,
- type RegisterDaemonRequest,
- type RegisterResponse,
- type SkillSyncRequest,
- type TaskApi,
- type WorkspaceFileReport,
-} from "@alook/shared";
-
-export class DaemonClient {
- constructor(private baseURL: string) {}
-
- private async request<T>(
- method: string,
- path: string,
- token: string,
- body?: unknown,
- ): Promise<T> {
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- Authorization: `Bearer ${token}`,
- };
- const MAX_RETRIES = 3;
- const BASE_DELAY_MS = 500;
- let lastError: unknown;
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
- try {
- const res = await fetch(this.baseURL + path, {
- method,
- headers,
- body: body ? JSON.stringify(body) : undefined,
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
- if (res.status === 204) return undefined as T;
- return res.json();
- } catch (e) {
- if (e instanceof TypeError) {
- lastError = e;
- if (attempt < MAX_RETRIES) {
- await new Promise((r) => setTimeout(r, BASE_DELAY_MS * 2 ** attempt));
- continue;
- }
- }
- throw e;
- }
- }
- throw lastError;
- }
-
- async register(
- token: string,
- body: RegisterDaemonRequest,
- ): Promise<RegisterResponse> {
- const raw = await this.request<unknown>(
- "POST",
- "/api/daemon/register",
- token,
- body,
- );
- return RegisterResponseSchema.parse(raw);
- }
-
- heartbeat(token: string, daemonId: string): Promise<unknown> {
- return this.request("POST", "/api/daemon/heartbeat", token, {
- daemon_id: daemonId,
- });
- }
-
- sweep(token: string, daemonId: string): Promise<unknown> {
- return this.request("POST", "/api/daemon/sweep", token, {
- daemon_id: daemonId,
- });
- }
-
- deregister(token: string, daemonId: string) {
- return this.request("POST", "/api/daemon/deregister", token, {
- daemon_id: daemonId,
- });
- }
-
- async poll(
- token: string,
- daemonId: string,
- maxTasks: number,
- cliVersion?: string,
- ): Promise<{
- tasks: TaskApi[];
- evicted: boolean;
- pending_update?: { version: string };
- pending_rescan?: boolean;
- file_requests?: FileRequestItem[];
- meetings?: PollMeetingItem[];
- }> {
- const raw = await this.request<unknown>(
- "POST",
- "/api/daemon/tasks/poll",
- token,
- { daemon_id: daemonId, max_tasks: maxTasks, ...(cliVersion && { cli_version: cliVersion }) },
- );
- const resp: PollResponse = PollResponseSchema.parse(raw);
- return {
- tasks: resp.tasks,
- evicted: resp.evicted ?? false,
- pending_update: resp.pending_update,
- pending_rescan: resp.pending_rescan,
- file_requests: resp.file_requests,
- meetings: resp.meetings,
- };
- }
-
- startTask(token: string, taskId: string) {
- return this.request("POST", `/api/daemon/tasks/${taskId}/start`, token);
- }
-
- completeTask(
- token: string,
- taskId: string,
- body: CompleteTaskRequest,
- ) {
- return this.request(
- "POST",
- `/api/daemon/tasks/${taskId}/complete`,
- token,
- body,
- );
- }
-
- failTask(token: string, taskId: string, error: string) {
- return this.request("POST", `/api/daemon/tasks/${taskId}/fail`, token, {
- error,
- });
- }
-
- supersedeTask(token: string, taskId: string) {
- return this.request("POST", `/api/daemon/tasks/${taskId}/supersede`, token);
- }
-
- async getArtifactMeta(
- token: string,
- artifactId: string,
- workspaceId: string,
- ): Promise<{ id: string; filename: string; content_type: string; size: number }> {
- return this.request(
- "GET",
- `/api/artifacts/${artifactId}?workspace_id=${encodeURIComponent(workspaceId)}`,
- token,
- );
- }
-
- async downloadArtifact(
- token: string,
- artifactId: string,
- workspaceId: string,
- ): Promise<ArrayBuffer> {
- const MAX_RETRIES = 3;
- const BASE_DELAY_MS = 500;
- let lastError: unknown;
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
- try {
- const res = await fetch(
- `${this.baseURL}/api/artifacts/${artifactId}/content?workspace_id=${encodeURIComponent(workspaceId)}`,
- { headers: { Authorization: `Bearer ${token}` } },
- );
- if (!res.ok) {
- throw new Error(`artifact download failed: HTTP ${res.status}`);
- }
- return res.arrayBuffer();
- } catch (e) {
- if (e instanceof TypeError) {
- lastError = e;
- if (attempt < MAX_RETRIES) {
- await new Promise((r) => setTimeout(r, BASE_DELAY_MS * 2 ** attempt));
- continue;
- }
- }
- throw e;
- }
- }
- throw lastError;
- }
-
- reportMessages(
- token: string,
- taskId: string,
- messages: MessageItem[],
- ) {
- return this.request(
- "POST",
- `/api/daemon/tasks/${taskId}/messages`,
- token,
- { messages },
- );
- }
-
- reportFileData(token: string, body: WorkspaceFileReport) {
- return this.request(
- "POST",
- "/api/daemon/workspace/report",
- token,
- body,
- );
- }
-
- syncSkills(token: string, body: SkillSyncRequest) {
- return this.request(
- "POST",
- "/api/daemon/skills/sync",
- token,
- body,
- );
- }
-
-}
diff --git a/src/cli/daemon/config.test.ts b/src/cli/daemon/config.test.ts
deleted file mode 100644
index fe025b23c..000000000
--- a/src/cli/daemon/config.test.ts
+++ /dev/null
@@ -1,216 +0,0 @@
-import { vi, describe, it, expect, afterEach } from "vitest";
-import { hostname } from "os";
-import { join } from "path";
-import { homedir } from "os";
-import { loadDaemonConfig, normalizeServerBaseURL, daemonLogFilePath, daemonLogDir, sessionRunnerLogDir } from "./config.js";
-
-const DAEMON_ENV_KEYS = [
- "ALOOK_SERVER_URL",
- "ALOOK_PROJECT_ROOT",
- "ALOOK_DAEMON_POLL_INTERVAL",
- "ALOOK_AGENT_TIMEOUT",
- "ALOOK_DAEMON_MAX_CONCURRENT_TASKS",
- "ALOOK_CLAUDE_PATH",
- "ALOOK_DAEMON_ID",
- "ALOOK_WORKSPACES_ROOT",
- "ALOOK_DAEMON_DEVICE_NAME",
- "ALOOK_KEEP_ENV_AFTER_TASK",
- "ALOOK_CODEX_PATH",
- "ALOOK_OPENCODE_PATH",
- "ALOOK_CLAUDE_MODEL",
- "ALOOK_CODEX_MODEL",
- "ALOOK_OPENCODE_MODEL",
- "ALOOK_MESSAGE_INACTIVITY_TIMEOUT",
-];
-
-afterEach(() => {
- for (const key of DAEMON_ENV_KEYS) {
- delete process.env[key];
- }
-});
-
-describe("loadDaemonConfig defaults", () => {
- it("returns correct defaults when no env vars set", () => {
- const cfg = loadDaemonConfig();
-
- expect(cfg.serverURL).toBe("https://alook.ai");
- expect(cfg.pollInterval).toBe(3000);
- expect(cfg.wsPollInterval).toBe(60000);
- expect(cfg.agentTimeout).toBe(43200000);
- expect(cfg.maxConcurrentTasks).toBe(20);
- expect(cfg.claudePath).toBe("claude");
- expect(cfg.messageInactivityTimeout).toBe(1200000);
- });
-});
-
-describe("loadDaemonConfig env overrides", () => {
- it("ALOOK_SERVER_URL overrides serverURL", () => {
- process.env.ALOOK_SERVER_URL = "http://remote:9090";
- expect(loadDaemonConfig().serverURL).toBe("http://remote:9090");
- });
-
- it("ALOOK_DAEMON_POLL_INTERVAL='5s' → 5000", () => {
- process.env.ALOOK_DAEMON_POLL_INTERVAL = "5s";
- expect(loadDaemonConfig().pollInterval).toBe(5000);
- });
-
-
- it("ALOOK_DAEMON_MAX_CONCURRENT_TASKS='10' → 10", () => {
- process.env.ALOOK_DAEMON_MAX_CONCURRENT_TASKS = "10";
- expect(loadDaemonConfig().maxConcurrentTasks).toBe(10);
- });
-
- it("caps ALOOK_DAEMON_MAX_CONCURRENT_TASKS at the server poll limit", () => {
- process.env.ALOOK_DAEMON_MAX_CONCURRENT_TASKS = "125";
- expect(loadDaemonConfig().maxConcurrentTasks).toBe(50);
- });
-
- it("ALOOK_MESSAGE_INACTIVITY_TIMEOUT='10m' → 600000", () => {
- process.env.ALOOK_MESSAGE_INACTIVITY_TIMEOUT = "10m";
- expect(loadDaemonConfig().messageInactivityTimeout).toBe(600000);
- });
-});
-
-describe("normalizeServerBaseURL", () => {
- it("converts ws:// to http://", () => {
- expect(normalizeServerBaseURL("ws://localhost:8080")).toBe(
- "http://localhost:8080",
- );
- });
-
- it("converts wss:// to https://", () => {
- expect(normalizeServerBaseURL("wss://example.com")).toBe(
- "https://example.com",
- );
- });
-
- it("strips /ws suffix", () => {
- expect(normalizeServerBaseURL("http://example.com/ws")).toBe(
- "http://example.com",
- );
- });
-
- it("leaves http:// unchanged", () => {
- expect(normalizeServerBaseURL("http://example.com")).toBe(
- "http://example.com",
- );
- });
-});
-
-describe("daemonId profile suffix", () => {
- it("uses hostname when no profile", () => {
- const cfg = loadDaemonConfig();
- expect(cfg.daemonId).toBe(hostname());
- });
-
- it("appends -profile to hostname with profile", () => {
- const cfg = loadDaemonConfig("staging");
- expect(cfg.daemonId).toBe(`${hostname()}-staging`);
- });
-
- it("doesn't double-append when ALOOK_DAEMON_ID already has suffix", () => {
- process.env.ALOOK_DAEMON_ID = `myhost-staging`;
- const cfg = loadDaemonConfig("staging");
- expect(cfg.daemonId).toBe("myhost-staging");
- });
-});
-
-describe("daemonLogFilePath", () => {
- it("returns <configDir>/daemon/logs/YYYY-MM-DD.log for a fixed date", () => {
- const d = new Date(2026, 3, 17); // 2026-04-17 local
- const p = daemonLogFilePath(d);
- expect(p).toBe(join(homedir(), ".alook", "daemon", "logs", "2026-04-17.log"));
- });
-
- it("zero-pads month and day", () => {
- const d = new Date(2026, 0, 5); // 2026-01-05 local
- expect(daemonLogFilePath(d).endsWith("2026-01-05.log")).toBe(true);
- });
-});
-
-describe("daemonLogDir — three ALOOK_PROJECT_ROOT scenarios", () => {
- it("production: ~/.alook/daemon/logs", () => {
- delete process.env.ALOOK_PROJECT_ROOT;
- expect(daemonLogDir()).toBe(join(homedir(), ".alook", "daemon", "logs"));
- });
-
- it("dev mode: <PROJECT>/.alook/daemon/logs", () => {
- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";
- expect(daemonLogDir()).toBe(join("/tmp/my-project/.alook", "daemon", "logs"));
- });
-
- it("app mode: ~/.alook/self-hosted/daemon/logs", () => {
- process.env.ALOOK_PROJECT_ROOT = join(homedir(), ".alook", "self-hosted");
- expect(daemonLogDir()).toBe(join(homedir(), ".alook", "self-hosted", "daemon", "logs"));
- });
-});
-
-describe("workspacesRoot — three ALOOK_PROJECT_ROOT scenarios", () => {
- it("production: ~/.alook/workspaces", () => {
- delete process.env.ALOOK_PROJECT_ROOT;
- const cfg = loadDaemonConfig();
- expect(cfg.workspacesRoot).toBe(join(homedir(), ".alook", "workspaces"));
- });
-
- it("production + profile: ~/.alook/workspaces_{profile}", () => {
- delete process.env.ALOOK_PROJECT_ROOT;
- const cfg = loadDaemonConfig("dev");
- expect(cfg.workspacesRoot).toBe(
- join(homedir(), ".alook", "workspaces_dev"),
- );
- });
-
- it("dev mode: <PROJECT>/.alook/workspaces", () => {
- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";
- const cfg = loadDaemonConfig();
- expect(cfg.workspacesRoot).toBe(
- join("/tmp/my-project/.alook", "workspaces"),
- );
- });
-
- it("dev mode + profile: <PROJECT>/.alook/workspaces_{profile}", () => {
- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";
- const cfg = loadDaemonConfig("staging");
- expect(cfg.workspacesRoot).toBe(
- join("/tmp/my-project/.alook", "workspaces_staging"),
- );
- });
-
- it("app mode: ~/.alook/self-hosted/workspaces", () => {
- process.env.ALOOK_PROJECT_ROOT = join(homedir(), ".alook", "self-hosted");
- const cfg = loadDaemonConfig();
- expect(cfg.workspacesRoot).toBe(
- join(homedir(), ".alook", "self-hosted", "workspaces"),
- );
- });
-
- it("ALOOK_WORKSPACES_ROOT overrides all defaults", () => {
- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";
- process.env.ALOOK_WORKSPACES_ROOT = "/custom/path";
- const cfg = loadDaemonConfig();
- expect(cfg.workspacesRoot).toBe("/custom/path");
- });
-});
-
-describe("sessionRunnerLogDir — three ALOOK_PROJECT_ROOT scenarios", () => {
- it("production: ~/.alook/daemon/session-runners", () => {
- delete process.env.ALOOK_PROJECT_ROOT;
- expect(sessionRunnerLogDir()).toBe(
- join(homedir(), ".alook", "daemon", "session-runners"),
- );
- });
-
- it("dev mode: <PROJECT>/.alook/daemon/session-runners", () => {
- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";
- expect(sessionRunnerLogDir()).toBe(
- join("/tmp/my-project/.alook", "daemon", "session-runners"),
- );
- });
-
- it("app mode: ~/.alook/self-hosted/daemon/session-runners", () => {
- process.env.ALOOK_PROJECT_ROOT = join(homedir(), ".alook", "self-hosted");
- expect(sessionRunnerLogDir()).toBe(
- join(homedir(), ".alook", "self-hosted", "daemon", "session-runners"),
- );
- });
-});
diff --git a/src/cli/daemon/config.ts b/src/cli/daemon/config.ts
deleted file mode 100644
index c681d9bc3..000000000
--- a/src/cli/daemon/config.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { hostname } from "os";
-import { join } from "path";
-import { configDir } from "../lib/config.js";
-import { getServerUrl } from "../lib/env.js";
-import { getCurrentVersion } from "../lib/version.js";
-import { MAX_POLL_TASKS } from "@alook/shared";
-
-export function pidFilePath(profile?: string): string {
- const name = profile ? `daemon_${profile}.pid` : "daemon.pid";
- return join(configDir(), name);
-}
-
-export function lastUpdateMarkerPath(profile?: string): string {
- const name = profile ? `last_update_${profile}` : "last_update";
- return join(configDir(), name);
-}
-
-export function daemonLogDir(): string {
- return join(configDir(), "daemon", "logs");
-}
-
-export function sessionRunnerLogDir(): string {
- return join(configDir(), "daemon", "session-runners");
-}
-
-export function daemonLogFilePath(date: Date = new Date()): string {
- const y = date.getFullYear();
- const m = String(date.getMonth() + 1).padStart(2, "0");
- const d = String(date.getDate()).padStart(2, "0");
- return join(daemonLogDir(), `${y}-${m}-${d}.log`);
-}
-
-function parseDuration(s: string): number {
- if (!s) return 0;
- let total = 0;
- const regex = /(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/g;
- let match;
- while ((match = regex.exec(s)) !== null) {
- const val = parseFloat(match[1]);
- switch (match[2]) {
- case "ns":
- total += val / 1e6;
- break;
- case "us":
- case "µs":
- total += val / 1e3;
- break;
- case "ms":
- total += val;
- break;
- case "s":
- total += val * 1000;
- break;
- case "m":
- total += val * 60000;
- break;
- case "h":
- total += val * 3600000;
- break;
- }
- }
- return total;
-}
-
-export interface DaemonConfig {
- serverURL: string;
- claudePath: string;
- codexPath: string;
- opencodePath: string;
- claudeModel: string;
- codexModel: string;
- opencodeModel: string;
- pollInterval: number;
- wsPollInterval: number;
- heartbeatInterval: number;
- sweepInterval: number;
- agentTimeout: number;
- messageInactivityTimeout: number;
- maxConcurrentTasks: number;
- enableSteering: boolean;
- daemonId: string;
- deviceName: string;
- workspacesRoot: string;
- cliVersion: string;
-}
-
-export function loadDaemonConfig(profile?: string): DaemonConfig {
- const h = hostname();
- let daemonId = process.env.ALOOK_DAEMON_ID || h;
- if (profile && !daemonId.endsWith(`-${profile}`)) {
- daemonId = `${daemonId}-${profile}`;
- }
-
- const defaultRoot = join(
- configDir(),
- profile ? `workspaces_${profile}` : "workspaces",
- );
- const workspacesRoot = process.env.ALOOK_WORKSPACES_ROOT || defaultRoot;
-
- return {
- serverURL: normalizeServerBaseURL(getServerUrl()),
- claudePath: process.env.ALOOK_CLAUDE_PATH || "claude",
- codexPath: process.env.ALOOK_CODEX_PATH || "codex",
- opencodePath: process.env.ALOOK_OPENCODE_PATH || "opencode",
- claudeModel: process.env.ALOOK_CLAUDE_MODEL || "",
- codexModel: process.env.ALOOK_CODEX_MODEL || "",
- opencodeModel: process.env.ALOOK_OPENCODE_MODEL || "",
- pollInterval: parseDuration(
- process.env.ALOOK_DAEMON_POLL_INTERVAL || "3s",
- ),
- wsPollInterval: parseDuration(process.env.ALOOK_DAEMON_WS_POLL_INTERVAL || "60s"),
- heartbeatInterval: parseDuration(process.env.ALOOK_DAEMON_HEARTBEAT_INTERVAL || "15s"),
- sweepInterval: parseDuration(process.env.ALOOK_DAEMON_SWEEP_INTERVAL || "60s"),
- agentTimeout: parseDuration(process.env.ALOOK_AGENT_TIMEOUT || "12h"),
- messageInactivityTimeout: parseDuration(process.env.ALOOK_MESSAGE_INACTIVITY_TIMEOUT || "20m"),
- maxConcurrentTasks: Math.min(
- parseInt(process.env.ALOOK_DAEMON_MAX_CONCURRENT_TASKS || "20"),
- MAX_POLL_TASKS,
- ),
- enableSteering: process.env.ALOOK_ENABLE_STEERING === "1",
- daemonId,
- deviceName: process.env.ALOOK_DAEMON_DEVICE_NAME || h,
- workspacesRoot,
- cliVersion: getCurrentVersion(),
- };
-}
-
-export function normalizeServerBaseURL(url: string): string {
- return url
- .replace(/^ws:\/\//, "http://")
- .replace(/^wss:\/\//, "https://")
- .replace(/\/ws$/, "");
-}
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
deleted file mode 100644
index 88de25d13..000000000
--- a/src/cli/daemon/daemon.test.ts
+++ /dev/null
@@ -1,2782 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import type { EventEmitter } from "events";
-import path from "path";
-
-// Mock all external dependencies before importing
-const mockClientInstance = {
- register: vi.fn(async () => ({
- runtimes: [{ id: "rt1" }],
- })),
- deregister: vi.fn(async () => {}),
- poll: vi.fn(async () => ({ tasks: [], evicted: false })),
- startTask: vi.fn(async () => ({})),
- completeTask: vi.fn(async () => ({})),
- failTask: vi.fn(async () => ({})),
- supersedeTask: vi.fn(async () => ({})),
- reportMessages: vi.fn(async () => ({})),
- sweep: vi.fn(async () => ({})),
-};
-vi.mock("./client.js", () => {
- function MockDaemonClient() { return mockClientInstance; }
- return { DaemonClient: MockDaemonClient };
-});
-
-vi.mock("./config.js", () => ({
- loadDaemonConfig: vi.fn(() => ({
- serverURL: "http://localhost:8080",
- claudePath: "claude",
- codexPath: "codex",
- opencodePath: "opencode",
- claudeModel: "opus",
- codexModel: "gpt-4",
- opencodeModel: "",
- pollInterval: 3000,
- agentTimeout: 7200000,
- messageInactivityTimeout: 300000,
- maxConcurrentTasks: 20,
- daemonId: "d1",
- deviceName: "test-host",
- workspacesRoot: path.join("/tmp", "ws"),
- cliVersion: "0.1.0",
- wsPollInterval: 30000,
- sweepInterval: 60000,
- })),
- sessionRunnerLogDir: vi.fn(() => path.join("/tmp", "alook", "daemon", "session-runners")),
- daemonLogFilePath: vi.fn(() => path.join("/tmp", "alook", "daemon", "logs", "2026-01-01.log")),
- lastUpdateMarkerPath: vi.fn((profile?: string) =>
- profile ? path.join("/tmp", "alook", `last_update_${profile}`) : path.join("/tmp", "alook", "last_update"),
- ),
-}));
-
-vi.mock("./health.js", () => ({
- createHealthServer: vi.fn(() => ({
- setRuntimeCount: vi.fn(),
- server: { close: vi.fn((cb?: () => void) => { if (cb) cb(); }) },
- })),
-}));
-
-let capturedWsOnMessage: ((msg: any) => void) | null = null;
-let capturedWsOpts: any = null;
-vi.mock("./ws-client.js", () => {
- class MockDaemonWsClient {
- connect = vi.fn();
- close = vi.fn();
- isConnected = vi.fn(() => false);
- constructor(opts: any) {
- capturedWsOpts = opts;
- if (opts?.onMessage) capturedWsOnMessage = opts.onMessage;
- }
- }
- return { DaemonWsClient: MockDaemonWsClient };
-});
-
-vi.mock("./agent/index.js", () => ({
- detectVersion: vi.fn(async () => "1.0.0"),
- createBackend: vi.fn(() => ({ lifecycle: { kind: "per_turn" }, busyDeliveryMode: "none", supportsStdinNotification: false })),
-}));
-
-vi.mock("../lib/config.js", async (importActual) => ({
- ...(await importActual<typeof import("../lib/config.js")>()),
- loadCLIConfigForProfile: vi.fn(() => ({
- server_url: null,
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- })),
- saveCLIConfigForProfile: vi.fn(),
-}));
-
-vi.mock("./pidfile.js", () => ({
- acquireDaemonPid: vi.fn(() => true),
- releaseDaemonPid: vi.fn(),
-}));
-
-vi.mock("./update-handler.js", () => ({
- handleCliUpdate: vi.fn(),
- isUpdating: vi.fn(() => false),
- readUpdateMarker: vi.fn(() => null),
- clearUpdateMarker: vi.fn(),
-}));
-
-const mockFindRunningPidByTaskId = vi.fn();
-const mockFindSupersedablePredecessor = vi.fn<(...args: any[]) => any>(() => null);
-const mockUpdateEntry = vi.fn();
-vi.mock("./execenv/timeline.js", () => ({
- findRunningPidByTaskId: (...args: any[]) => mockFindRunningPidByTaskId(...(args as any[])),
- findSupersedablePredecessor: (...args: any[]) => mockFindSupersedablePredecessor(...(args as any[])),
- steerWarmupGraceMs: () => 30_000,
- updateEntry: (...args: any[]) => mockUpdateEntry(...(args as any[])),
-}));
-
-const mockDownloadAttachments = vi.fn<(...args: any[]) => any>(async () => []);
-const mockCleanupAttachments = vi.fn(async () => {});
-vi.mock("./session-runner.js", () => ({
- writeMarkerFile: vi.fn(),
- runSession: vi.fn(),
- downloadAttachments: (...args: any[]) => mockDownloadAttachments(...(args as any[])),
- cleanupAttachments: (...args: any[]) => mockCleanupAttachments(...(args as any[])),
-}));
-
-const mockBuildPrompt = vi.fn((..._args: any[]) => '{"type":"user_dm_message","instruction":"test"}');
-const mockBuildMergedPrompt = vi.fn((..._args: any[]) => '{"type":"merge_tasks","tasks":[]}');
-vi.mock("./prompt.js", () => ({
- buildPrompt: (...args: any[]) => mockBuildPrompt(...(args as any[])),
- buildMergedPrompt: (...args: any[]) => mockBuildMergedPrompt(...(args as any[])),
-}));
-
-const mockWriteKillIntent = vi.fn();
-const mockReadKillIntent = vi.fn(() => null);
-const mockClearKillIntent = vi.fn();
-const mockAcquireSteeringLock = vi.fn(() => true);
-const mockReleaseSteeringLock = vi.fn();
-const mockCleanupStaleIntents = vi.fn();
-vi.mock("./execenv/steering.js", () => ({
- writeKillIntent: (...args: any[]) => mockWriteKillIntent(...(args as any[])),
- readKillIntent: (...args: any[]) => mockReadKillIntent(...(args as any[])),
- clearKillIntent: (...args: any[]) => mockClearKillIntent(...(args as any[])),
- acquireSteeringLock: (...args: any[]) => mockAcquireSteeringLock(...(args as any[])),
- releaseSteeringLock: (...args: any[]) => mockReleaseSteeringLock(...(args as any[])),
- cleanupStaleIntents: (...args: any[]) => mockCleanupStaleIntents(...(args as any[])),
-}));
-
-vi.mock("./steering/mailbox.js", () => ({
- ensureMailboxDirs: vi.fn(),
- writeSteerMessage: vi.fn(() => "000001"),
- waitForAck: vi.fn(async () => ({ acked: false, nackReason: "mock" })),
- inboxDir: vi.fn(() => "/tmp/mock-inbox"),
-}));
-
-// Track spawned children
-interface MockChild extends EventEmitter {
- pid: number;
- unref: ReturnType<typeof vi.fn>;
-}
-
-const spawnedChildren: MockChild[] = [];
-let nextPid = 50000;
-
-vi.mock("child_process", () => {
- const { EventEmitter } = require("events");
-
- return {
- execSync: vi.fn(),
- spawn: vi.fn((_cmd: string, _args: string[], _opts: any) => {
- const child = new EventEmitter() as MockChild;
- child.pid = nextPid++;
- child.unref = vi.fn();
- spawnedChildren.push(child);
- return child;
- }),
- };
-});
-
-const mockOpenSync = vi.fn(() => 42);
-const mockCloseSync = vi.fn();
-const mockRenameSync = vi.fn();
-const mockMkdirSync = vi.fn();
-const mockReaddirSync = vi.fn(() => [] as string[]);
-const mockStatSync = vi.fn(() => ({ mtimeMs: 0 }));
-const mockUnlinkSync = vi.fn();
-
-vi.mock("fs", () => ({
- existsSync: vi.fn((p: string) => p.endsWith("session-runner.js")),
- openSync: (...args: any[]) => mockOpenSync(...(args as any[])),
- closeSync: (...args: any[]) => mockCloseSync(...(args as any[])),
- renameSync: (...args: any[]) => mockRenameSync(...(args as any[])),
- mkdirSync: (...args: any[]) => mockMkdirSync(...(args as any[])),
- readdirSync: (...args: any[]) => mockReaddirSync(...(args as any[])),
- statSync: (...args: any[]) => mockStatSync(...(args as any[])),
- unlinkSync: (...args: any[]) => mockUnlinkSync(...(args as any[])),
- realpathSync: vi.fn((p: string) => p),
- readFileSync: vi.fn(() => ""),
- writeFileSync: vi.fn(),
-}));
-
-const mockReaddir = vi.fn(async () => [] as string[]);
-const mockReadFile = vi.fn(async () => "");
-const mockUnlink = vi.fn(async () => undefined);
-const mockFsStat = vi.fn(async () => ({ mtimeMs: Date.now() }));
-vi.mock("fs/promises", () => ({
- readdir: (...args: any[]) => mockReaddir(...(args as any[])),
- readFile: (...args: any[]) => mockReadFile(...(args as any[])),
- unlink: (...args: any[]) => mockUnlink(...(args as any[])),
- stat: (...args: any[]) => mockFsStat(...(args as any[])),
-}));
-
-vi.mock("url", () => ({
- fileURLToPath: vi.fn(() => "/fake/daemon.ts"),
-}));
-
-vi.mock("path", async () => {
- const actual = await vi.importActual("path");
- return actual;
-});
-
-// Capture signal handlers and prevent actual process.exit.
-// We also intercept "once" registrations for exit/uncaughtException/unhandledRejection
-// so daemon safety-net handlers don't bleed across tests.
-const signalHandlers = new Map<string, (...args: any[]) => any>();
-const capturedEvents = new Set([
- "SIGTERM",
- "SIGINT",
- "SIGHUP",
- "exit",
- "uncaughtException",
- "unhandledRejection",
-]);
-const originalOn = process.on.bind(process);
-const mockProcessExit = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
-
-vi.spyOn(process, "on").mockImplementation(((event: string, handler: any) => {
- if (capturedEvents.has(event)) {
- signalHandlers.set(event, handler);
- return process;
- }
- return originalOn(event, handler);
-}) as any);
-
-vi.spyOn(process, "once").mockImplementation(((event: string, handler: any) => {
- if (capturedEvents.has(event)) {
- signalHandlers.set(event, handler);
- return process;
- }
- return process.on(event, handler);
-}) as any);
-
-// Track setInterval/clearInterval calls
-const realSetInterval = globalThis.setInterval;
-const realClearInterval = globalThis.clearInterval;
-const intervalTimers: NodeJS.Timeout[] = [];
-const intervalMsArgs: number[] = [];
-const intervalFns: Array<() => void> = [];
-
-vi.spyOn(globalThis, "setInterval").mockImplementation(((fn: any, ms: any) => {
- const timer = realSetInterval(() => {}, 999999) as NodeJS.Timeout;
- intervalTimers.push(timer);
- intervalMsArgs.push(ms);
- intervalFns.push(fn);
- return timer;
-}) as any);
-
-const clearedTimers: NodeJS.Timeout[] = [];
-vi.spyOn(globalThis, "clearInterval").mockImplementation(((timer: any) => {
- clearedTimers.push(timer);
- realClearInterval(timer);
-}) as any);
-
-import { spawn } from "child_process";
-import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
-import { releaseDaemonPid } from "./pidfile.js";
-import { handleCliUpdate, readUpdateMarker, clearUpdateMarker } from "./update-handler.js";
-import { startDaemon, spawnSessionRunner, pruneSessionRunnerLogs, isClientError, reconcilePendingCompletions } from "./daemon.js";
-
-const mockReleaseDaemonPid = vi.mocked(releaseDaemonPid);
-
-function decodeSpawnInput(call: any[]): any {
- // spawn(process.execPath, [sessionRunnerPath, encodedInput], opts)
- const args = call[1] as string[];
- const encoded = args[1];
- return JSON.parse(Buffer.from(encoded, "base64").toString("utf-8"));
-}
-
-describe("daemon session runner dispatch", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(42);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- function setupTaskClaim() {
- const fakeTask = {
- id: "t1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "do stuff",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- };
-
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) {
- claimed = true;
- return { tasks: [fakeTask], evicted: false };
- }
- return { tasks: [], evicted: false };
- }) as any);
-
- return fakeTask;
- }
-
- it("spawns a session runner when a task is polled", async () => {
- setupTaskClaim();
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(spawn).toHaveBeenCalledTimes(1);
- const call = vi.mocked(spawn).mock.calls[0];
- expect(call[0]).toBe(process.execPath);
- expect((call[1] as string[])[0]).toContain("session-runner.js");
- });
-
- it("passes correct SessionRunnerInput to session runner", async () => {
- setupTaskClaim();
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- const input = decodeSpawnInput(vi.mocked(spawn).mock.calls[0]);
- expect(input.task.id).toBe("t1");
- expect(input.task.prompt).toBe("do stuff");
- expect(input.provider).toBe("claude");
- expect(input.cliPath).toBe("claude");
- expect(input.model).toBe("opus");
- expect(input.serverURL).toBe("http://localhost:8080");
- expect(input.token).toBe("al_test_token");
- expect(input.workspacesRoot).toBe(path.join("/tmp", "ws"));
- expect(input.agentTimeout).toBe(7200000);
- expect(input.messageInactivityTimeout).toBe(300000);
- });
-
- it("uses runtime_config.model when set on agent", async () => {
- const fakeTask = {
- id: "t1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "do stuff",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: { name: "Agent 1", instructions: "be helpful", runtime_config: { model: "custom-model" } },
- };
-
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) {
- claimed = true;
- return { tasks: [fakeTask], evicted: false };
- }
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- const input = decodeSpawnInput(vi.mocked(spawn).mock.calls[0]);
- expect(input.model).toBe("custom-model");
- });
-
- it("falls back to config model when runtime_config.model is empty", async () => {
- setupTaskClaim();
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- const input = decodeSpawnInput(vi.mocked(spawn).mock.calls[0]);
- expect(input.model).toBe("opus");
- });
-
- it("spawns with detached: true, log file stdio, and calls unref()", async () => {
- setupTaskClaim();
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- const call = vi.mocked(spawn).mock.calls[0];
- expect((call[2] as any).detached).toBe(true);
- expect((call[2] as any).stdio).toEqual(["ignore", 42, 42]);
- expect(spawnedChildren[0].unref).toHaveBeenCalled();
- });
-
- it("activeTasks decrements on child close event", async () => {
- setupTaskClaim();
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // A close listener should have been registered
- expect(spawnedChildren[0].listenerCount("close")).toBe(1);
-
- // Simulate child process exit
- spawnedChildren[0].emit("close", 0);
-
- // After close, we verify indirectly: the next poll should request full capacity (20)
- // If activeTasks wasn't decremented, it would request 19
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
- // Manually invoke a poll by calling the function startDaemon set up
- // We verify the listener was attached — the decrement logic is straightforward
- });
-
- it("skips failTask when kill intent exists on close", async () => {
- setupTaskClaim();
- mockReadKillIntent.mockReturnValue({ reason: "cancelled", targetTaskId: "t1", expectedPid: 50000 });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // Simulate child process exit with non-zero code (killed)
- spawnedChildren[0].emit("close", 1);
- await new Promise((r) => setTimeout(r, 10));
-
- expect(mockClientInstance.failTask).not.toHaveBeenCalled();
- expect(mockClearKillIntent).toHaveBeenCalled();
- });
-
- it("calls failTask when no kill intent exists on close (genuine crash)", async () => {
- setupTaskClaim();
- mockReadKillIntent.mockReturnValue(null);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // Simulate child process crash
- spawnedChildren[0].emit("close", 1);
-
- await vi.waitFor(() => {
- expect(mockClientInstance.failTask).toHaveBeenCalledWith(
- "al_test_token",
- "t1",
- expect.stringContaining("exit"),
- );
- });
- });
-
- it("calls startTask before spawning session runner", async () => {
- setupTaskClaim();
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(mockClientInstance.startTask).toHaveBeenCalledWith("al_test_token", "t1");
- expect(spawn).toHaveBeenCalledTimes(1);
- });
-
- it("fails task and does not spawn if startTask fails", async () => {
- setupTaskClaim();
- mockClientInstance.startTask.mockRejectedValueOnce(new Error("server error"));
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(mockClientInstance.failTask).toHaveBeenCalledWith(
- "al_test_token",
- "t1",
- expect.stringContaining("start failed"),
- );
- expect(spawn).not.toHaveBeenCalled();
- });
-
- it("passes correct workspace token into session runner input", async () => {
- setupTaskClaim();
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- const input = decodeSpawnInput(vi.mocked(spawn).mock.calls[0]);
- expect(input.token).toBe("al_test_token");
- });
-});
-
-describe("daemon steering with pendingSteer merge", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(42);
- mockFindSupersedablePredecessor.mockReturnValue(null);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- function claimTaskWithContextKey() {
- const fakeTask = {
- id: "t_new",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "newcomer",
- status: "dispatched",
- priority: 0,
- context_key: "conv_thread",
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- };
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) {
- claimed = true;
- return { tasks: [fakeTask], evicted: false };
- }
- return { tasks: [], evicted: false };
- }) as any);
- return fakeTask;
- }
-
- // TC7 — the bug: predecessor pending (not started) → newcomer waits, then
- // predecessor starts (agent_started flips) → newcomer supersedes + spawns.
- it("waits for a warming-up predecessor, then supersedes once it starts", async () => {
- claimTaskWithContextKey();
- const pending = { pending: { task_id: "t_warmup", pid: 40000, context_key: "conv_thread" } };
- const started = { entry: { task_id: "t_warmup", pid: 40000, context_key: "conv_thread" }, reason: "agent-started" };
- // First call (initial classification) → pending; second call (re-classify in loop) → started.
- mockFindSupersedablePredecessor
- .mockReturnValueOnce(pending)
- .mockReturnValueOnce(started);
- mockFindRunningPidByTaskId.mockReturnValue(null);
-
- await startDaemon();
- // Wait for poll + wait loop + supersede + spawn.
- await vi.waitFor(() => { expect(spawn).toHaveBeenCalledTimes(1); }, { timeout: 2000 });
-
- expect(mockWriteKillIntent).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({ reason: "superseded", targetTaskId: "t_warmup", successorTaskId: "t_new" }),
- );
- expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("al_test_token", "t_warmup");
- });
-
- // TC8 — normal supersede unchanged: agent-started predecessor → kill + supersede immediately, spawn.
- it("supersedes a genuinely-running predecessor immediately (no wait)", async () => {
- claimTaskWithContextKey();
- mockFindSupersedablePredecessor.mockReturnValue({
- entry: { task_id: "t_live", pid: 40001, context_key: "conv_thread" },
- reason: "agent-started",
- });
- mockFindRunningPidByTaskId.mockReturnValue(null);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(mockWriteKillIntent).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({ reason: "superseded", targetTaskId: "t_live", successorTaskId: "t_new" }),
- );
- expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("al_test_token", "t_live");
- expect(spawn).toHaveBeenCalledTimes(1);
- });
-
- // TC9 — stale fallback: predecessor not started but stale → supersede immediately, spawn.
- it("supersedes a stale (crashed-warmup) predecessor immediately", async () => {
- claimTaskWithContextKey();
- mockFindSupersedablePredecessor.mockReturnValue({
- entry: { task_id: "t_stale", pid: 40002, context_key: "conv_thread" },
- reason: "stale",
- });
- mockFindRunningPidByTaskId.mockReturnValue(null);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("al_test_token", "t_stale");
- expect(spawn).toHaveBeenCalledTimes(1);
- });
-
- // TC10 — predecessor vanishes during wait → newcomer spawns, no kill intent.
- it("spawns without kill intent when predecessor vanishes during the wait", async () => {
- claimTaskWithContextKey();
- const pending = { pending: { task_id: "t_vanish", pid: 40003, context_key: "conv_thread" } };
- // First call → pending; second call (re-classify) → null (predecessor gone).
- mockFindSupersedablePredecessor
- .mockReturnValueOnce(pending)
- .mockReturnValueOnce(null);
-
- await startDaemon();
- await vi.waitFor(() => { expect(spawn).toHaveBeenCalledTimes(1); }, { timeout: 2000 });
-
- expect(mockWriteKillIntent).not.toHaveBeenCalled();
- expect(mockClientInstance.supersedeTask).not.toHaveBeenCalled();
- });
-
- // TC12 — no contextKey → never enters the steering/wait path.
- it("does not enter the steering path for a task without a context_key", async () => {
- const fakeTask = {
- id: "t_noctx",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "no ctx",
- status: "dispatched",
- priority: 0,
- context_key: null,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- };
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) { claimed = true; return { tasks: [fakeTask], evicted: false }; }
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(mockFindSupersedablePredecessor).not.toHaveBeenCalled();
- expect(spawn).toHaveBeenCalledTimes(1);
- });
-
- // TC15 — lock is released between wait ticks (not held across sleep).
- it("releases the steering lock between wait ticks so concurrent tasks are not bypassed", async () => {
- claimTaskWithContextKey();
- const pending = { pending: { task_id: "t_warmup", pid: 40000, context_key: "conv_thread" } };
- const started = { entry: { task_id: "t_warmup", pid: 40000, context_key: "conv_thread" }, reason: "agent-started" };
- mockFindSupersedablePredecessor
- .mockReturnValueOnce(pending)
- .mockReturnValueOnce(started);
- mockFindRunningPidByTaskId.mockReturnValue(null);
-
- await startDaemon();
- await vi.waitFor(() => { expect(spawn).toHaveBeenCalledTimes(1); }, { timeout: 2000 });
-
- // The lock was released at least once INSIDE the wait loop (before the sleep),
- // then re-acquired for the next classification. The initial acquire + loop
- // release + loop re-acquire means release was called MORE than just the
- // outer finally. Verify release was called at least twice (once inside loop,
- // once in finally).
- expect(mockReleaseSteeringLock.mock.calls.length).toBeGreaterThanOrEqual(2);
- // And re-acquire was called inside the loop (beyond the initial acquire).
- expect(mockAcquireSteeringLock.mock.calls.length).toBeGreaterThanOrEqual(2);
- });
-
- // TC11 — MERGE: B (owner) waits, C merges into entry, A starts → 1 spawn with merged prompt.
- // Assert: both spawn, C (newest) spawns LAST, supersede order is A then B.
- it("merges a second task and spawns once with merged prompt", async () => {
- const fakeB = {
- id: "t_B", agent_id: "a1", runtime_id: "rt1", conversation_id: "c1",
- workspace_id: "ws1", prompt: "B", status: "dispatched", priority: 0,
- context_key: "conv_thread", dispatched_at: null, started_at: null,
- completed_at: null, created_at: "2026-01-01T00:00:01Z",
- type: "user_dm_message", result: null, error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- };
- const fakeC = {
- id: "t_C", agent_id: "a1", runtime_id: "rt1", conversation_id: "c1",
- workspace_id: "ws1", prompt: "C", status: "dispatched", priority: 0,
- context_key: "conv_thread", dispatched_at: null, started_at: null,
- completed_at: null, created_at: "2026-01-01T00:00:02Z",
- type: "user_dm_message", result: null, error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- };
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) { claimed = true; return { tasks: [fakeB, fakeC], evicted: false }; }
- return { tasks: [], evicted: false };
- }) as any);
-
- // B initial → pending A (becomes owner). C initial → pending A (sees entry, merges, returns).
- // B loop → A started → supersede A + spawn with merged prompt [B,C].
- const pendingA = { pending: { task_id: "t_A", pid: 39000, context_key: "conv_thread" } };
- const startedA = { entry: { task_id: "t_A", pid: 39000, context_key: "conv_thread" }, reason: "agent-started" };
- mockFindSupersedablePredecessor
- .mockReturnValueOnce(pendingA) // B initial
- .mockReturnValueOnce(pendingA) // C initial
- .mockReturnValueOnce(startedA); // B loop re-classify → supersede A
- mockFindRunningPidByTaskId.mockReturnValue(null);
-
- await startDaemon();
- await vi.waitFor(() => { expect(spawn).toHaveBeenCalledTimes(1); }, { timeout: 3000 });
-
- // Only 1 spawn (owner B spawns for both B and C).
- expect(spawn).toHaveBeenCalledTimes(1);
- // buildMergedPrompt called (multi-task entry).
- expect(mockBuildMergedPrompt).toHaveBeenCalled();
- // Predecessor A was superseded.
- expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("al_test_token", "t_A");
- });
-
- // TC16 — Map cleanup: after owner spawns, pendingSteer key is deleted.
- it("cleans up the pendingSteer Map after the owner spawns", async () => {
- claimTaskWithContextKey();
- mockFindSupersedablePredecessor.mockReturnValue({
- entry: { task_id: "t_live", pid: 40001, context_key: "conv_thread" },
- reason: "agent-started",
- });
- mockFindRunningPidByTaskId.mockReturnValue(null);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(spawn).toHaveBeenCalledTimes(1);
- // Map cleanup is internal; verified by no errors + successful spawn.
- });
-});
-
-describe("daemon with multi-workspace config", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(42);
-
- // Configure two workspaces
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "Personal", token: "al_tok_ws1" },
- { id: "ws2", name: "Team", token: "al_tok_ws2" },
- ],
- });
-
- // Register returns different runtime IDs for each workspace
- let registerCall = 0;
- mockClientInstance.register.mockImplementation(async () => {
- registerCall++;
- return { runtimes: [{ id: `rt${registerCall}` }] };
- });
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- it("polls each workspace with its own token", async () => {
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
-
- await startDaemon();
-
- expect(mockClientInstance.poll).toHaveBeenCalledTimes(2);
- expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws1", "d1", 20, "0.1.0");
- expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws2", "d1", 20, "0.1.0");
- });
-
- it("registers each workspace with its own token", async () => {
- await startDaemon();
-
- expect(mockClientInstance.register).toHaveBeenCalledTimes(2);
- expect(mockClientInstance.register).toHaveBeenCalledWith(
- "al_tok_ws1",
- expect.objectContaining({ workspace_id: "ws1" }),
- );
- expect(mockClientInstance.register).toHaveBeenCalledWith(
- "al_tok_ws2",
- expect.objectContaining({ workspace_id: "ws2" }),
- );
- });
-
- it("concurrency accounting: spawned tasks reduce remaining for next workspace", async () => {
- const fakeTask = {
- id: "t1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "do stuff",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- };
-
- // W1 returns 3 tasks, W2 should get remaining (20 - 3 = 17)
- let pollCall = 0;
- mockClientInstance.poll.mockImplementation((async () => {
- pollCall++;
- if (pollCall === 1) return { tasks: [fakeTask, { ...fakeTask, id: "t2" }, { ...fakeTask, id: "t3" }], evicted: false };
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // W2 should be called with max_tasks = 20 - 3 = 17
- expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws2", "d1", 17, "0.1.0");
- });
-
- it("multi-workspace: passes correct token per workspace into session runner", async () => {
- const fakeTaskWs1 = {
- id: "t1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "ws1 task",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- };
-
- const fakeTaskWs2 = {
- ...fakeTaskWs1,
- id: "t2",
- runtime_id: "rt2",
- workspace_id: "ws2",
- prompt: "ws2 task",
- };
-
- let pollCall = 0;
- mockClientInstance.poll.mockImplementation((async () => {
- pollCall++;
- if (pollCall === 1) return { tasks: [fakeTaskWs1], evicted: false };
- if (pollCall === 2) return { tasks: [fakeTaskWs2], evicted: false };
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(spawn).toHaveBeenCalledTimes(2);
- const input1 = decodeSpawnInput(vi.mocked(spawn).mock.calls[0]);
- const input2 = decodeSpawnInput(vi.mocked(spawn).mock.calls[1]);
- expect(input1.token).toBe("al_tok_ws1");
- expect(input2.token).toBe("al_tok_ws2");
- });
-});
-
-describe("daemon shutdown", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
-
- // Restore default mock implementations after clearAllMocks
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
- mockClientInstance.startTask.mockResolvedValue({});
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- it("clears poll interval before calling deregister", async () => {
- await startDaemon();
-
- expect(intervalTimers.length).toBe(4); // pollTimer + heartbeatTimer + sweepTimer + skillScannerTimer
- const pollTimer = intervalTimers[0];
-
- const deregisterMock = mockClientInstance.deregister;
-
- let deregisterCalledAt = -1;
- let clearCalledCount = 0;
- deregisterMock.mockImplementation(async () => {
- deregisterCalledAt = clearCalledCount;
- });
-
- const originalClearMock = vi.mocked(globalThis.clearInterval);
- originalClearMock.mockImplementation(((timer: any) => {
- clearCalledCount++;
- clearedTimers.push(timer);
- realClearInterval(timer);
- }) as any);
-
- const shutdownHandler = signalHandlers.get("SIGTERM");
- expect(shutdownHandler).toBeDefined();
- await shutdownHandler!();
-
- expect(clearedTimers).toContain(pollTimer);
- expect(deregisterCalledAt).toBe(4); // After clearing all 4 timers (poll + heartbeat + sweep + skillScanner)
- });
-
- it("deregisters each workspace with correct token on shutdown", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "Personal", token: "al_tok_ws1" },
- { id: "ws2", name: "Team", token: "al_tok_ws2" },
- ],
- });
-
- let registerCall = 0;
- mockClientInstance.register.mockImplementation(async () => {
- registerCall++;
- return { runtimes: [{ id: `rt${registerCall}` }] };
- });
-
- await startDaemon();
-
- const shutdownHandler = signalHandlers.get("SIGTERM");
- expect(shutdownHandler).toBeDefined();
- await shutdownHandler!();
-
- expect(mockClientInstance.deregister).toHaveBeenCalledWith("al_tok_ws1", "d1");
- expect(mockClientInstance.deregister).toHaveBeenCalledWith("al_tok_ws2", "d1");
- });
-
- it("does not kill session runner children on shutdown", async () => {
- const fakeTask = {
- id: "t1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "do stuff",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- };
-
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) {
- claimed = true;
- return { tasks: [fakeTask], evicted: false };
- }
- return { tasks: [], evicted: false };
- }) as any);
- mockClientInstance.startTask.mockResolvedValue({});
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(spawnedChildren.length).toBe(1);
-
- // Shutdown — should NOT kill the child
- const shutdownHandler = signalHandlers.get("SIGTERM");
- await shutdownHandler!();
-
- // Child should still be alive — unref was called, no kill signal sent
- expect(spawnedChildren[0].unref).toHaveBeenCalled();
- });
-});
-
-describe("daemon agent_ids lazy sync", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
-
- // Restore default mock implementations after clearAllMocks
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.startTask.mockResolvedValue({});
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- function makeFakeTask(overrides?: Record<string, unknown>) {
- return {
- id: "t1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "do stuff",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- ...overrides,
- };
- }
-
- it("syncs unknown agent_id to config when task is received", async () => {
- // Config has no agent_ids — agent was created on the web
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token", agent_ids: [] }],
- });
-
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) { claimed = true; return { tasks: [makeFakeTask()], evicted: false }; }
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(saveCLIConfigForProfile).toHaveBeenCalledOnce();
- const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1];
- expect(savedConfig.watched_workspaces![0].agent_ids).toContain("a1");
- });
-
- it("does not save config when agent_id is already known", async () => {
- // Config already has agent "a1"
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token", agent_ids: ["a1"] }],
- });
-
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) { claimed = true; return { tasks: [makeFakeTask()], evicted: false }; }
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(saveCLIConfigForProfile).not.toHaveBeenCalled();
- });
-
- it("deduplicates: multiple tasks with same new agent_id only save once", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token", agent_ids: [] }],
- });
-
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) {
- claimed = true;
- return { tasks: [makeFakeTask({ id: "t1" }), makeFakeTask({ id: "t2" })], evicted: false };
- }
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // Only one save — the in-memory set deduplicates
- expect(saveCLIConfigForProfile).toHaveBeenCalledOnce();
- });
-});
-
-describe("daemon startup failures release pidfile", () => {
- beforeEach(async () => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
-
- // Restore defaults that other describe-level tests override.
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "Test WS", token: "al_test_token" },
- ],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
- const cp = await import("child_process");
- vi.mocked(cp.execSync).mockImplementation(() => undefined as never);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- it("starts in standby mode when no workspaces are configured", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [],
- });
-
- await startDaemon();
-
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-
- it("registers an exit handler that releases the pidfile", async () => {
- await startDaemon();
-
- const exitHandler = signalHandlers.get("exit");
- expect(exitHandler).toBeDefined();
- mockReleaseDaemonPid.mockClear();
- exitHandler!();
- expect(mockReleaseDaemonPid).toHaveBeenCalled();
- });
-
- it("uncaughtException handler releases pidfile and exits 1", async () => {
- await startDaemon();
-
- const handler = signalHandlers.get("uncaughtException");
- expect(handler).toBeDefined();
- mockReleaseDaemonPid.mockClear();
- mockProcessExit.mockClear();
- handler!(new Error("boom"));
- expect(mockReleaseDaemonPid).toHaveBeenCalled();
- expect(mockProcessExit).toHaveBeenCalledWith(1);
- });
-
- it("unhandledRejection handler releases pidfile and exits 1", async () => {
- await startDaemon();
-
- const handler = signalHandlers.get("unhandledRejection");
- expect(handler).toBeDefined();
- mockReleaseDaemonPid.mockClear();
- mockProcessExit.mockClear();
- handler!(new Error("async-boom"));
- expect(mockReleaseDaemonPid).toHaveBeenCalled();
- expect(mockProcessExit).toHaveBeenCalledWith(1);
- });
-
- it("exits with code 1 and logs when no agent CLI tools are found on PATH", async () => {
- const cp = await import("child_process");
- vi.mocked(cp.execSync).mockImplementation(() => {
- throw new Error("not found");
- });
- const stderrWrite = vi.spyOn(process.stderr, "write").mockReturnValue(true);
-
- await startDaemon();
-
- expect(mockProcessExit.mock.calls[0]?.[0]).toBe(1);
- const logs = stderrWrite.mock.calls.map((c) => String(c[0])).join("");
- expect(logs).toContain("No agent CLI tools found on PATH.");
- stderrWrite.mockRestore();
- });
-
- it("exits with code 1 and logs when every register call fails", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "Personal", token: "al_tok_ws1" },
- { id: "ws2", name: "Team", token: "al_tok_ws2" },
- ],
- });
- mockClientInstance.register.mockRejectedValue(new Error("ECONNREFUSED"));
- const stderrWrite = vi.spyOn(process.stderr, "write").mockReturnValue(true);
-
- await startDaemon();
-
- expect(mockProcessExit.mock.calls[0]?.[0]).toBe(1);
- const logs = stderrWrite.mock.calls.map((c) => String(c[0])).join("");
- expect(logs).toContain("No workspaces registered successfully.");
- stderrWrite.mockRestore();
- });
-});
-
-describe("spawnSessionRunner", () => {
- beforeEach(() => {
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockOpenSync.mockReturnValue(42);
- });
-
- function makeSpawnInput() {
- return {
- task: { id: "t1", agentId: "a1", runtimeId: "rt1", conversationId: "c1", workspaceId: "ws1", prompt: "test", status: "dispatched", priority: 0, type: "user_dm_message", createdAt: "2026-01-01T00:00:00Z" },
- provider: "claude",
- cliPath: "claude",
- model: "opus",
- serverURL: "http://localhost:8080",
- token: "test_token",
- workspacesRoot: "/tmp/ws",
- agentTimeout: 7200000,
- };
- }
-
- it("encodes input as base64 and passes to bun run", () => {
- const child = spawnSessionRunner(makeSpawnInput() as any);
-
- expect(spawn).toHaveBeenCalledTimes(1);
- const call = vi.mocked(spawn).mock.calls[0];
- expect(call[0]).toBe(process.execPath);
-
- const args = call[1] as string[];
- expect(args[0]).toContain("session-runner.js");
-
- const decoded = JSON.parse(Buffer.from(args[1], "base64").toString("utf-8"));
- expect(decoded.task.id).toBe("t1");
- expect(decoded.provider).toBe("claude");
- expect(decoded.token).toBe("test_token");
-
- expect((call[2] as any).detached).toBe(true);
- expect(child.unref).toHaveBeenCalled();
- });
-
- it("opens a log file fd with taskId.log and passes it as stdio [ignore, fd, fd]", () => {
- spawnSessionRunner(makeSpawnInput() as any);
-
- expect(mockMkdirSync).toHaveBeenCalledWith(
- path.join("/tmp", "alook", "daemon", "session-runners"),
- { recursive: true },
- );
- expect(mockOpenSync).toHaveBeenCalledWith(
- path.join("/tmp", "alook", "daemon", "session-runners", "t1.log"),
- "a",
- );
-
- const call = vi.mocked(spawn).mock.calls[0];
- expect((call[2] as any).stdio).toEqual(["ignore", 42, 42]);
- });
-
- it("closes the fd after spawn", () => {
- spawnSessionRunner(makeSpawnInput() as any);
- expect(mockCloseSync).toHaveBeenCalledWith(42);
- });
-
- it("sets logFilePath in the serialized input", () => {
- const input = makeSpawnInput() as any;
- spawnSessionRunner(input);
-
- const call = vi.mocked(spawn).mock.calls[0];
- const encoded = call[1]![1] as string;
- const decoded = JSON.parse(Buffer.from(encoded, "base64").toString("utf-8"));
- expect(decoded.logFilePath).toBe(path.join("/tmp", "alook", "daemon", "session-runners", "t1.log"));
- });
-
- it("spawns with stdio ignore when openSync fails (disk full)", () => {
- mockOpenSync.mockImplementation(() => { throw new Error("ENOSPC: no space left on device"); });
-
- const child = spawnSessionRunner(makeSpawnInput() as any);
-
- expect(spawn).toHaveBeenCalledTimes(1);
- const call = vi.mocked(spawn).mock.calls[0];
- expect((call[2] as any).stdio).toEqual(["ignore", "ignore", "ignore"]);
- expect(child.unref).toHaveBeenCalled();
- expect(mockCloseSync).not.toHaveBeenCalled();
- });
-});
-
-describe("pruneSessionRunnerLogs", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("handles missing directory gracefully", () => {
- mockReaddirSync.mockImplementation(() => { throw new Error("ENOENT"); });
- expect(() => pruneSessionRunnerLogs()).not.toThrow();
- expect(mockUnlinkSync).not.toHaveBeenCalled();
- });
-
- it("handles empty directory gracefully", () => {
- mockReaddirSync.mockReturnValue([]);
- pruneSessionRunnerLogs();
- expect(mockUnlinkSync).not.toHaveBeenCalled();
- });
-
- it("does not delete when at or below limit", () => {
- const files = Array.from({ length: 500 }, (_, i) => `${i}.log`);
- mockReaddirSync.mockReturnValue(files);
- pruneSessionRunnerLogs();
- expect(mockUnlinkSync).not.toHaveBeenCalled();
- });
-
- it("deletes oldest files when over limit, keeping newest 500", () => {
- const files = Array.from({ length: 505 }, (_, i) => `${i}.log`);
- mockReaddirSync.mockReturnValue(files);
- mockStatSync.mockImplementation(((p: string) => {
- const name = path.basename(p);
- const idx = parseInt(name);
- return { mtimeMs: idx * 1000 };
- }) as any);
-
- pruneSessionRunnerLogs();
-
- expect(mockUnlinkSync).toHaveBeenCalledTimes(5);
- // Files 0-4 are the oldest (lowest mtime), they should be deleted
- for (let i = 0; i < 5; i++) {
- expect(mockUnlinkSync).toHaveBeenCalledWith(
- path.join("/tmp", "alook", "daemon", "session-runners", `${i}.log`),
- );
- }
- });
-
- it("ignores non-.log files", () => {
- const files = ["1.log", "2.log", ".DS_Store", "readme.txt"];
- mockReaddirSync.mockReturnValue(files);
- mockStatSync.mockReturnValue({ mtimeMs: 0 });
- pruneSessionRunnerLogs();
- // Only 2 .log files, well under 500 limit
- expect(mockUnlinkSync).not.toHaveBeenCalled();
- });
-});
-
-describe("daemon workspace eviction", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- it("removes workspace from polling on eviction and stops polling it", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "Personal", token: "al_tok_ws1" },
- { id: "ws2", name: "Team", token: "al_tok_ws2" },
- ],
- });
-
- let registerCall = 0;
- mockClientInstance.register.mockImplementation(async () => {
- registerCall++;
- return { runtimes: [{ id: `rt${registerCall}` }] };
- });
-
- let pollCall = 0;
- mockClientInstance.poll.mockImplementation(async () => {
- pollCall++;
- // First cycle: ws1 normal, ws2 evicted
- if (pollCall === 1) return { tasks: [], evicted: false };
- if (pollCall === 2) return { tasks: [], evicted: true };
- // Subsequent cycles should only get ws1
- return { tasks: [], evicted: false };
- });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // ws2 was evicted — soft-marked status="deleted" (not physically removed),
- // so a restart's status!=="deleted" filter skips it while ws1 stays active.
- expect(saveCLIConfigForProfile).toHaveBeenCalled();
- const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1];
- const ws1 = savedConfig.watched_workspaces!.find((w: any) => w.id === "ws1");
- const ws2 = savedConfig.watched_workspaces!.find((w: any) => w.id === "ws2");
- expect(ws1?.status).not.toBe("deleted");
- expect(ws2?.status).toBe("deleted");
- });
-
- it("soft-marks evicted workspace status=deleted in local config file", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: true });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(saveCLIConfigForProfile).toHaveBeenCalled();
- const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1];
- // Entry lingers (recoverable by re-pair) but is marked deleted.
- expect(savedConfig.watched_workspaces).toHaveLength(1);
- expect(savedConfig.watched_workspaces![0].status).toBe("deleted");
- });
-
- it("shuts down gracefully when all workspaces are evicted", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: true });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // Should trigger shutdown → process.exit(0)
- expect(mockProcessExit).toHaveBeenCalledWith(0);
- });
-
- it("continues polling remaining workspaces when middle one is evicted (3 workspaces)", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "First", token: "al_tok_ws1" },
- { id: "ws2", name: "Middle", token: "al_tok_ws2" },
- { id: "ws3", name: "Last", token: "al_tok_ws3" },
- ],
- });
-
- let registerCall = 0;
- mockClientInstance.register.mockImplementation(async () => {
- registerCall++;
- return { runtimes: [{ id: `rt${registerCall}` }] };
- });
-
- const pollTokens: string[] = [];
- mockClientInstance.poll.mockImplementation((async (token: string) => {
- pollTokens.push(token);
- // Evict ws2 (middle workspace)
- if (token === "al_tok_ws2") return { tasks: [], evicted: true };
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // First poll cycle should hit all 3
- expect(pollTokens).toContain("al_tok_ws1");
- expect(pollTokens).toContain("al_tok_ws2");
- expect(pollTokens).toContain("al_tok_ws3");
-
- // Verify config saved with ws2 soft-marked deleted, ws1/ws3 still active
- expect(saveCLIConfigForProfile).toHaveBeenCalled();
- const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1];
- const byId = (id: string) => savedConfig.watched_workspaces!.find((w: any) => w.id === id);
- expect(byId("ws1")?.status).not.toBe("deleted");
- expect(byId("ws2")?.status).toBe("deleted");
- expect(byId("ws3")?.status).not.toBe("deleted");
-
- // Daemon should NOT have shut down (still has ws1 and ws3)
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-
- it("updates health.setRuntimeCount after eviction", async () => {
- const mockHealthSetRuntimeCount = vi.fn();
- const { createHealthServer } = await import("./health.js");
- vi.mocked(createHealthServer).mockReturnValue({
- setRuntimeCount: mockHealthSetRuntimeCount,
- server: { close: vi.fn() },
- } as any);
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "First", token: "al_tok_ws1" },
- { id: "ws2", name: "Second", token: "al_tok_ws2" },
- ],
- });
-
- let registerCall = 0;
- mockClientInstance.register.mockImplementation(async () => {
- registerCall++;
- return { runtimes: [{ id: `rt${registerCall}` }] };
- });
-
- mockClientInstance.poll.mockImplementation((async (token: string) => {
- if (token === "al_tok_ws2") return { tasks: [], evicted: true };
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // Initial count was 2 (one per workspace), after evicting ws2 it should be 1
- const calls = mockHealthSetRuntimeCount.mock.calls;
- const lastCall = calls[calls.length - 1];
- expect(lastCall[0]).toBe(1);
- });
-
- it("config write failure does not block in-memory eviction", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "First", token: "al_tok_ws1" },
- { id: "ws2", name: "Second", token: "al_tok_ws2" },
- ],
- });
-
- let registerCall = 0;
- mockClientInstance.register.mockImplementation(async () => {
- registerCall++;
- return { runtimes: [{ id: `rt${registerCall}` }] };
- });
-
- // Make config save throw
- vi.mocked(saveCLIConfigForProfile).mockImplementation(() => {
- throw new Error("disk full");
- });
-
- mockClientInstance.poll.mockImplementation((async (token: string) => {
- if (token === "al_tok_ws2") return { tasks: [], evicted: true };
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // saveCLIConfigForProfile threw, but daemon should NOT crash
- // and should NOT shut down (ws1 still active)
- expect(mockProcessExit).not.toHaveBeenCalled();
-
- // ws2 should be evicted from in-memory state (only ws1 polled in future)
- // Verify by checking the saveCLIConfigForProfile was attempted
- expect(saveCLIConfigForProfile).toHaveBeenCalled();
- });
-});
-
-describe("daemon 401 handling (no config removal)", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- it("does not remove workspace from config on startup 401", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "Good", token: "al_tok_ws1" },
- { id: "ws2", name: "Bad Token", token: "al_tok_ws2" },
- ],
- });
-
- mockClientInstance.register.mockImplementation((async (token: string) => {
- if (token === "al_tok_ws2") throw new Error("HTTP 401 Unauthorized");
- return { runtimes: [{ id: "rt1" }] };
- }) as any);
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // Config should NOT have been saved to remove ws2
- expect(saveCLIConfigForProfile).not.toHaveBeenCalled();
- // Daemon should still be running (ws1 registered successfully)
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-
- it("does not evict workspace on poll 401, continues polling", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "Personal", token: "al_tok_ws1" },
- { id: "ws2", name: "Team", token: "al_tok_ws2" },
- ],
- });
-
- let registerCall = 0;
- mockClientInstance.register.mockImplementation(async () => {
- registerCall++;
- return { runtimes: [{ id: `rt${registerCall}` }] };
- });
-
- mockClientInstance.poll.mockImplementation((async (token: string) => {
- if (token === "al_tok_ws2") throw new Error("HTTP 401 Unauthorized");
- return { tasks: [], evicted: false };
- }) as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // Config should NOT have been saved (no eviction)
- expect(saveCLIConfigForProfile).not.toHaveBeenCalled();
- // Daemon should NOT shut down — ws1 still active, ws2 just had a transient 401
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-});
-
-describe("daemon restart via update", () => {
- it("handleCliUpdate is called when pending_update is in poll response", async () => {
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- mockClientInstance.poll.mockResolvedValue({
- tasks: [],
- evicted: false,
- pending_update: { version: "2.0.0" },
- } as any);
-
- await startDaemon();
-
- expect(handleCliUpdate).toHaveBeenCalledWith("2.0.0", expect.any(Function), undefined);
- });
-
- it("handleCliUpdate is not called when pending_update.version matches cliVersion", async () => {
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- // pending_update version matches cliVersion (0.1.0 from config mock)
- mockClientInstance.poll.mockResolvedValue({
- tasks: [],
- evicted: false,
- pending_update: { version: "0.1.0" },
- } as any);
-
- await startDaemon();
-
- expect(handleCliUpdate).not.toHaveBeenCalled();
- });
-
- it("handleCliUpdate is not called when isUpdating returns true", async () => {
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- const { isUpdating } = await import("./update-handler.js");
- vi.mocked(isUpdating).mockReturnValue(true);
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({
- tasks: [],
- evicted: false,
- pending_update: { version: "2.0.0" },
- } as any);
-
- await startDaemon();
-
- expect(handleCliUpdate).not.toHaveBeenCalled();
- vi.mocked(isUpdating).mockReturnValue(false);
- });
-
- it("clears update marker on startup when current version matches marker", async () => {
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
-
- vi.mocked(readUpdateMarker).mockReturnValue("0.1.0"); // matches cliVersion
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
-
- await startDaemon();
-
- expect(clearUpdateMarker).toHaveBeenCalled();
- });
-
- it("clears stale update marker on startup when current version does not match marker", async () => {
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
-
- vi.mocked(readUpdateMarker).mockReturnValue("0.0.9"); // stale — differs from cliVersion 0.1.0
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
-
- await startDaemon();
-
- expect(clearUpdateMarker).toHaveBeenCalled();
- });
-
-});
-
-describe("daemon rescan via poll", () => {
- beforeEach(async () => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(99);
-
- const { createHealthServer } = await import("./health.js");
- vi.mocked(createHealthServer).mockReturnValue({
- setRuntimeCount: vi.fn(),
- server: { close: vi.fn((cb?: () => void) => { if (cb) cb(); }) },
- } as any);
-
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.deregister.mockResolvedValue(undefined as any);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- it("calls requestRestart when pending_rescan is true in poll response", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
-
- mockClientInstance.poll.mockResolvedValue({
- tasks: [],
- evicted: false,
- pending_rescan: true,
- } as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 200));
-
- // requestRestart triggers shutdown + spawn of new daemon
- const spawnCalls = vi.mocked(spawn).mock.calls;
- const restartCall = spawnCalls.find(
- (call) => call[0] === process.execPath && (call[1] as string[]).includes("--foreground"),
- );
- expect(restartCall).toBeDefined();
- });
-
- it("does not restart when pending_rescan is absent", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
-
- mockClientInstance.poll.mockResolvedValue({
- tasks: [],
- evicted: false,
- });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 200));
-
- const spawnCalls = vi.mocked(spawn).mock.calls;
- const restartCall = spawnCalls.find(
- (call) => call[0] === process.execPath && (call[1] as string[]).includes("--foreground"),
- );
- expect(restartCall).toBeUndefined();
- });
-});
-
-describe("daemon restart spawn", () => {
- beforeEach(async () => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(99);
-
- // Restore createHealthServer to the correct factory (previous tests may override it)
- const { createHealthServer } = await import("./health.js");
- vi.mocked(createHealthServer).mockReturnValue({
- setRuntimeCount: vi.fn(),
- server: { close: vi.fn((cb?: () => void) => { if (cb) cb(); }) },
- } as any);
-
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.deregister.mockResolvedValue(undefined as any);
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- it("restart spawn uses process.execPath with log file fd for stdio", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
-
- // Make handleCliUpdate immediately invoke the restart callback
- vi.mocked(handleCliUpdate).mockImplementation(((_version: string, onSuccess: () => void) => {
- onSuccess();
- }) as any);
-
- mockClientInstance.poll.mockResolvedValue({
- tasks: [],
- evicted: false,
- pending_update: { version: "2.0.0" },
- } as any);
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 200));
-
- const spawnCalls = vi.mocked(spawn).mock.calls;
- const restartCall = spawnCalls.find(
- (call) => call[0] === process.execPath && (call[1] as string[]).includes("--foreground"),
- );
- expect(restartCall).toBeDefined();
-
- const args = restartCall![1] as string[];
- expect(args).toContain("daemon");
- expect(args).toContain("start");
- expect(args).toContain("--foreground");
-
- const opts = restartCall![2] as any;
- expect(opts.detached).toBe(true);
- expect(opts.stdio).toEqual(["ignore", 99, 99]);
-
- expect(mockMkdirSync).toHaveBeenCalledWith(
- expect.stringContaining("logs"),
- { recursive: true, mode: 0o700 },
- );
- expect(mockOpenSync).toHaveBeenCalledWith(
- path.join("/tmp", "alook", "daemon", "logs", "2026-01-01.log"),
- "a",
- 0o600,
- );
- expect(mockCloseSync).toHaveBeenCalledWith(99);
- });
-});
-
-describe("daemon kill_task handling", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(42);
- // Use short timeouts for KILL_TASK retry loop in tests
- process.env.ALOOK_KILL_TASK_MAX_WAIT_MS = "500";
- process.env.ALOOK_KILL_TASK_POLL_MS = "50";
- // Short verify/grace windows so killAndVerify's SIGTERM→verify→SIGKILL loop
- // is quick. (verifyMs is clamped to >= grace+500, so keep grace tiny too.)
- process.env.ALOOK_KILL_GRACE_MS = "10";
- process.env.ALOOK_KILL_VERIFY_MS = "100";
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- delete process.env.ALOOK_KILL_TASK_MAX_WAIT_MS;
- delete process.env.ALOOK_KILL_TASK_POLL_MS;
- delete process.env.ALOOK_KILL_GRACE_MS;
- delete process.env.ALOOK_KILL_VERIFY_MS;
- });
-
- // process.kill mock that simulates the target dying on SIGTERM: the delivery
- // call succeeds, and the liveness probe (signal 0) reports it gone (ESRCH) so
- // killAndVerify returns promptly without escalating to SIGKILL.
- function mockKillTargetDies() {
- return vi.spyOn(process, "kill").mockImplementation(((pid: number, sig: any) => {
- if (sig === 0) { const e = Object.assign(new Error("ESRCH"), { code: "ESRCH" }); throw e; }
- return true;
- }) as any);
- }
-
- function makeKillTask(targetTaskId: string) {
- return {
- id: "kt1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "kill_task",
- result: null,
- error: null,
- agent: null,
- context: { target_task_id: targetTaskId },
- };
- }
-
- function setupKillTaskClaim(targetTaskId: string) {
- let claimed = false;
- mockClientInstance.poll.mockImplementation((async () => {
- if (!claimed) {
- claimed = true;
- return { tasks: [makeKillTask(targetTaskId)], evicted: false };
- }
- return { tasks: [], evicted: false };
- }) as any);
- }
-
- it("sends SIGTERM when target PID is found in timeline", async () => {
- setupKillTaskClaim("target_t1");
- mockFindRunningPidByTaskId.mockReturnValue(99999);
- const mockKill = mockKillTargetDies();
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 250));
-
- expect(mockKill).toHaveBeenCalledWith(99999, "SIGTERM");
- expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "killed");
- expect(spawn).not.toHaveBeenCalled();
-
- mockKill.mockRestore();
- });
-
- it("TC7: escalates to SIGKILL when the session-runner ignores SIGTERM", async () => {
- setupKillTaskClaim("target_t1");
- mockFindRunningPidByTaskId.mockReturnValue(66666);
- // Target stays alive (signal 0 never throws) — it ignores SIGTERM, forcing
- // killAndVerify to escalate to SIGKILL after the verify window.
- const mockKill = vi.spyOn(process, "kill").mockImplementation((() => true) as any);
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 800));
-
- expect(mockKill).toHaveBeenCalledWith(66666, "SIGTERM");
- expect(mockKill).toHaveBeenCalledWith(66666, "SIGKILL");
- expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "killed");
-
- mockKill.mockRestore();
- });
-
- it("TC7: does not SIGKILL when the target exits on SIGTERM", async () => {
- setupKillTaskClaim("target_t1");
- mockFindRunningPidByTaskId.mockReturnValue(99999);
- const mockKill = mockKillTargetDies();
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 250));
-
- expect(mockKill).toHaveBeenCalledWith(99999, "SIGTERM");
- expect(mockKill).not.toHaveBeenCalledWith(99999, "SIGKILL");
-
- mockKill.mockRestore();
- });
-
- it("reports 'target not found' after retry timeout when PID never appears", async () => {
- setupKillTaskClaim("target_t1");
- mockFindRunningPidByTaskId.mockReturnValue(null);
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- await startDaemon();
- // Wait longer than ALOOK_KILL_TASK_MAX_WAIT_MS (500ms) + overhead
- await new Promise((r) => setTimeout(r, 800));
-
- expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "target not found in timeline");
- expect(spawn).not.toHaveBeenCalled();
- // Should have retried multiple times
- expect(mockFindRunningPidByTaskId.mock.calls.length).toBeGreaterThan(1);
- });
-
- it("handles ESRCH when target process already exited", async () => {
- setupKillTaskClaim("target_t1");
- mockFindRunningPidByTaskId.mockReturnValue(12345);
- const esrchError = Object.assign(new Error("kill ESRCH"), { code: "ESRCH" });
- const mockKill = vi.spyOn(process, "kill").mockImplementation(() => { throw esrchError; });
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "target process already exited");
- expect(spawn).not.toHaveBeenCalled();
-
- mockKill.mockRestore();
- });
-
- it("does not call startTask for kill_tasks", async () => {
- setupKillTaskClaim("target_t1");
- mockFindRunningPidByTaskId.mockReturnValue(99999);
- const mockKill = mockKillTargetDies();
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 250));
-
- expect(mockClientInstance.startTask).not.toHaveBeenCalled();
-
- mockKill.mockRestore();
- });
-
- it("finds PID after a few retries and sends SIGTERM", async () => {
- setupKillTaskClaim("target_t1");
- let callCount = 0;
- mockFindRunningPidByTaskId.mockImplementation(() => {
- callCount++;
- if (callCount >= 3) return 88888;
- return null;
- });
- const mockKill = mockKillTargetDies();
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 700));
-
- expect(mockKill).toHaveBeenCalledWith(88888, "SIGTERM");
- expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "killed");
- expect(callCount).toBeGreaterThanOrEqual(3);
-
- mockKill.mockRestore();
- });
-
- it("searches correct timeline directory using agentId from task", async () => {
- setupKillTaskClaim("target_t1");
- mockFindRunningPidByTaskId.mockReturnValue(77777);
- const mockKill = mockKillTargetDies();
-
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
-
- await startDaemon();
-
- // The timelineDir should be constructed from workspacesRoot/workspaceId/agentId/workdir/.context_timeline
- const expectedTimelineDir = path.join("/tmp", "ws", "ws1", "a1", "workdir", ".context_timeline");
- await vi.waitFor(() => {
- expect(mockFindRunningPidByTaskId).toHaveBeenCalledWith(expectedTimelineDir, "target_t1");
- });
-
- mockKill.mockRestore();
- });
-});
-
-describe("isClientError", () => {
- it("HTTP 400: bad request → true", () => {
- expect(isClientError(new Error("HTTP 400: bad request"))).toBe(true);
- });
-
- it("HTTP 404: not found → true", () => {
- expect(isClientError(new Error("HTTP 404: not found"))).toBe(true);
- });
-
- it("HTTP 408: request timeout → false (transient)", () => {
- expect(isClientError(new Error("HTTP 408: request timeout"))).toBe(false);
- });
-
- it("HTTP 429: too many requests → false (transient)", () => {
- expect(isClientError(new Error("HTTP 429: too many requests"))).toBe(false);
- });
-
- it("HTTP 500: internal server error → false", () => {
- expect(isClientError(new Error("HTTP 500: internal server error"))).toBe(false);
- });
-
- it("HTTP 503: service unavailable → false", () => {
- expect(isClientError(new Error("HTTP 503: service unavailable"))).toBe(false);
- });
-
- it("Network error (no HTTP prefix) → false", () => {
- expect(isClientError(new Error("TypeError: fetch failed"))).toBe(false);
- });
-
- it("Non-Error value → false", () => {
- expect(isClientError("some string")).toBe(false);
- expect(isClientError(42)).toBe(false);
- expect(isClientError(null)).toBe(false);
- });
-});
-
-describe("reconcilePendingCompletions", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mockClientInstance.completeTask.mockResolvedValue({});
- mockClientInstance.failTask.mockResolvedValue({});
- });
-
- function makeMarker(overrides?: Record<string, unknown>) {
- return JSON.stringify({
- taskId: "t1",
- type: "complete",
- payload: { output: "Done!" },
- token: "tok_123",
- serverURL: "http://localhost:8080",
- createdAt: new Date().toISOString(),
- ...overrides,
- });
- }
-
- it("delivers 'complete' marker and deletes file", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.json"] as any);
- mockReadFile.mockResolvedValueOnce(makeMarker());
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockClientInstance.completeTask).toHaveBeenCalledWith("tok_123", "t1", { output: "Done!" });
- expect(mockUnlink).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions", "t1.json"));
- });
-
- it("delivers 'fail' marker and deletes file", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.json"] as any);
- mockReadFile.mockResolvedValueOnce(makeMarker({ type: "fail", payload: { error: "boom" } }));
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockClientInstance.failTask).toHaveBeenCalledWith("tok_123", "t1", "boom");
- expect(mockUnlink).toHaveBeenCalled();
- });
-
- it("deletes marker on 4xx", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.json"] as any);
- mockReadFile.mockResolvedValueOnce(makeMarker());
- mockClientInstance.completeTask.mockRejectedValueOnce(new Error("HTTP 400: bad request"));
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockUnlink).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions", "t1.json"));
- });
-
- it("retains marker on network error", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.json"] as any);
- mockReadFile.mockResolvedValueOnce(makeMarker());
- mockClientInstance.completeTask.mockRejectedValueOnce(new Error("TypeError: fetch failed"));
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockUnlink).not.toHaveBeenCalled();
- });
-
- it("retains marker on 5xx", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.json"] as any);
- mockReadFile.mockResolvedValueOnce(makeMarker());
- mockClientInstance.completeTask.mockRejectedValueOnce(new Error("HTTP 500: internal server error"));
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockUnlink).not.toHaveBeenCalled();
- });
-
- it("deletes stale markers (>24h)", async () => {
- const oldDate = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString();
- mockReaddir.mockResolvedValueOnce(["t1.json"] as any);
- mockReadFile.mockResolvedValueOnce(makeMarker({ createdAt: oldDate }));
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockClientInstance.completeTask).not.toHaveBeenCalled();
- expect(mockUnlink).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions", "t1.json"));
- });
-
- it("deletes malformed JSON marker files and continues processing", async () => {
- mockReaddir.mockResolvedValueOnce(["bad.json", "t1.json"] as any);
- mockReadFile.mockResolvedValueOnce("{invalid json");
- mockReadFile.mockResolvedValueOnce(makeMarker());
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockUnlink).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions", "bad.json"));
- expect(mockClientInstance.completeTask).toHaveBeenCalledTimes(1);
- });
-
- it("deletes markers with invalid createdAt dates", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.json"] as any);
- mockReadFile.mockResolvedValueOnce(makeMarker({ createdAt: "not-a-date" }));
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockClientInstance.completeTask).not.toHaveBeenCalled();
- expect(mockUnlink).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions", "t1.json"));
- });
-
- it("skips structurally invalid marker files and deletes them", async () => {
- mockReaddir.mockResolvedValueOnce(["bad.json"] as any);
- mockReadFile.mockResolvedValueOnce(JSON.stringify({ type: "complete", taskId: "x", payload: {} }));
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockClientInstance.completeTask).not.toHaveBeenCalled();
- expect(mockUnlink).toHaveBeenCalled();
- });
-
- it("handles empty directory", async () => {
- mockReaddir.mockResolvedValueOnce([] as any);
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockClientInstance.completeTask).not.toHaveBeenCalled();
- expect(mockClientInstance.failTask).not.toHaveBeenCalled();
- });
-
- it("handles missing directory", async () => {
- mockReaddir.mockRejectedValueOnce(new Error("ENOENT"));
-
- await expect(reconcilePendingCompletions("/tmp/ws")).resolves.toBeUndefined();
- });
-
- it("processes markers independently — failure on one doesn't abort rest", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.json", "t2.json", "t3.json"] as any);
- mockReadFile.mockResolvedValueOnce(makeMarker({ taskId: "t1" }));
- mockReadFile.mockResolvedValueOnce(makeMarker({ taskId: "t2" }));
- mockReadFile.mockResolvedValueOnce(makeMarker({ taskId: "t3" }));
- mockClientInstance.completeTask
- .mockResolvedValueOnce({})
- .mockRejectedValueOnce(new Error("TypeError: fetch failed"))
- .mockResolvedValueOnce({});
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockClientInstance.completeTask).toHaveBeenCalledTimes(3);
- // t1 and t3 delivered → deleted, t2 failed → retained
- expect(mockUnlink).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions", "t1.json"));
- expect(mockUnlink).not.toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions", "t2.json"));
- expect(mockUnlink).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions", "t3.json"));
- });
-
- it("ignores .tmp files (not processed as markers)", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.tmp"] as any);
- mockFsStat.mockResolvedValueOnce({ mtimeMs: Date.now() } as any);
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockClientInstance.completeTask).not.toHaveBeenCalled();
- expect(mockReadFile).not.toHaveBeenCalled();
- });
-
- it("cleans up stale .tmp files (>1h)", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.tmp"] as any);
- mockFsStat.mockResolvedValueOnce({ mtimeMs: Date.now() - 2 * 60 * 60 * 1000 } as any);
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockUnlink).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions", "t1.tmp"));
- });
-
- it("keeps recent .tmp files", async () => {
- mockReaddir.mockResolvedValueOnce(["t1.tmp"] as any);
- mockFsStat.mockResolvedValueOnce({ mtimeMs: Date.now() - 5 * 60 * 1000 } as any);
-
- await reconcilePendingCompletions("/tmp/ws");
-
- expect(mockUnlink).not.toHaveBeenCalled();
- });
-});
-
-describe("handleWsPush via WebSocket onMessage", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- capturedWsOnMessage = null;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(42);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- async function setupDaemonWithWs() {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
-
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
- }
-
- it("dispatches a task via WS push using Map lookup", async () => {
- await setupDaemonWithWs();
- expect(capturedWsOnMessage).not.toBeNull();
-
- capturedWsOnMessage!({
- type: "daemon.tasks",
- tasks: [{
- id: "wst1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "ws push task",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: { name: "Agent 1", instructions: "be helpful" },
- }],
- });
-
- await new Promise((r) => setTimeout(r, 50));
- expect(spawn).toHaveBeenCalled();
- });
-
- it("skips task when workspaceId not found via WS push", async () => {
- await setupDaemonWithWs();
- expect(capturedWsOnMessage).not.toBeNull();
-
- capturedWsOnMessage!({
- type: "daemon.tasks",
- tasks: [{
- id: "wst2",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "unknown_ws",
- prompt: "should be skipped",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- result: null,
- error: null,
- agent: null,
- }],
- });
-
- await new Promise((r) => setTimeout(r, 50));
- expect(spawn).not.toHaveBeenCalled();
- });
-
- it("handles daemon.file_requests via WS push with Map lookup", async () => {
- await setupDaemonWithWs();
- expect(capturedWsOnMessage).not.toBeNull();
-
- capturedWsOnMessage!({
- type: "daemon.file_requests",
- workspaceId: "ws1",
- requests: [{ id: "fr1", path: "/some/file", type: "read" }],
- });
-
- await new Promise((r) => setTimeout(r, 50));
- // file_requests with valid workspace should not throw
- });
-
- it("handles daemon.kill via WS push with Map lookup", async () => {
- await setupDaemonWithWs();
- expect(capturedWsOnMessage).not.toBeNull();
-
- mockFindRunningPidByTaskId.mockReturnValue(77777);
- process.env.ALOOK_KILL_VERIFY_MS = "100";
- // SIGTERM delivery succeeds; liveness probe reports the target gone so the
- // verify loop ends without escalation.
- const mockKill = vi.spyOn(process, "kill").mockImplementation(((_pid: number, sig: any) => {
- if (sig === 0) { throw Object.assign(new Error("ESRCH"), { code: "ESRCH" }); }
- return true;
- }) as any);
-
- capturedWsOnMessage!({
- type: "daemon.kill",
- workspaceId: "ws1",
- taskId: "kt_ws1",
- agentId: "a1",
- targetTaskId: "target_t1",
- });
-
- await new Promise((r) => setTimeout(r, 100));
- expect(mockKill).toHaveBeenCalledWith(77777, "SIGTERM");
-
- mockKill.mockRestore();
- delete process.env.ALOOK_KILL_VERIFY_MS;
- });
-
- it("handles daemon.meetings via WS push with Map lookup", async () => {
- await setupDaemonWithWs();
- expect(capturedWsOnMessage).not.toBeNull();
-
- capturedWsOnMessage!({
- type: "daemon.meetings",
- meetings: [{
- id: "m1",
- workspace_id: "ws1",
- agent_id: "a1",
- agent_name: "Agent 1",
- meeting_url: "https://meet.example.com/abc",
- participants: ["[email protected]"],
- title: "Test Meeting",
- }],
- });
-
- await new Promise((r) => setTimeout(r, 50));
- // spawnMeetingRunner calls spawn under the hood
- expect(spawn).toHaveBeenCalled();
- const call = vi.mocked(spawn).mock.calls[0];
- const args = call[1] as string[];
- expect(args[0]).toContain("meeting-runner");
- });
-
- it("skips daemon.meetings for unknown workspace via WS push", async () => {
- await setupDaemonWithWs();
- expect(capturedWsOnMessage).not.toBeNull();
-
- capturedWsOnMessage!({
- type: "daemon.meetings",
- meetings: [{
- id: "m2",
- workspace_id: "unknown_ws",
- agent_id: "a1",
- agent_name: "Agent 1",
- meeting_url: "https://meet.example.com/xyz",
- participants: ["[email protected]"],
- title: "Skipped Meeting",
- }],
- });
-
- await new Promise((r) => setTimeout(r, 50));
- expect(spawn).not.toHaveBeenCalled();
- });
-});
-
-describe("daemon SIGHUP reload", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- capturedWsOnMessage = null;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(42);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- it("starts in standby mode when no workspaces are configured", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [],
- });
-
- await startDaemon();
-
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-
- it("after SIGHUP, new workspace is registered", async () => {
- let configCallCount = 0;
- vi.mocked(loadCLIConfigForProfile).mockImplementation(() => {
- configCallCount++;
- if (configCallCount === 1) {
- return { server_url: "", watched_workspaces: [{ id: "ws1", name: "WS1", token: "al_tok1" }] };
- }
- return {
- server_url: "",
- watched_workspaces: [
- { id: "ws1", name: "WS1", token: "al_tok1" },
- { id: "ws2", name: "WS2", token: "al_tok2" },
- ],
- };
- });
-
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
-
- await startDaemon();
- expect(mockProcessExit).not.toHaveBeenCalled();
-
- const sighupHandler = signalHandlers.get("SIGHUP");
- expect(sighupHandler).toBeDefined();
- await sighupHandler!();
-
- expect(mockClientInstance.register).toHaveBeenCalledWith(
- "al_tok2",
- expect.objectContaining({ workspace_id: "ws2" }),
- );
- });
-});
-
-describe("WS poll-frequency fallback", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- intervalMsArgs.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- capturedWsOnMessage = null;
- capturedWsOpts = null;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(42);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- async function boot() {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
- }
-
- it("starts poll at high-frequency (pollInterval)", async () => {
- await boot();
- // The very first setInterval is the poll timer.
- expect(intervalMsArgs[0]).toBe(3000);
- });
-
- it("onConnected switches poll to low-frequency (wsPollInterval)", async () => {
- await boot();
- intervalMsArgs.length = 0;
- capturedWsOpts.onConnected();
- expect(intervalMsArgs).toContain(30000);
- });
-
- it("onDisconnected reverts to high-frequency (pollInterval)", async () => {
- await boot();
- intervalMsArgs.length = 0;
- capturedWsOpts.onDisconnected();
- expect(intervalMsArgs).toContain(3000);
- });
-});
-
-describe("WS token invalidation + rotation (T6b)", () => {
- beforeEach(() => {
- signalHandlers.clear();
- intervalTimers.length = 0;
- intervalMsArgs.length = 0;
- clearedTimers.length = 0;
- spawnedChildren.length = 0;
- nextPid = 50000;
- capturedWsOnMessage = null;
- capturedWsOpts = null;
- vi.clearAllMocks();
- mockProcessExit.mockImplementation((() => {}) as any);
- mockOpenSync.mockReturnValue(42);
- });
-
- afterEach(() => {
- for (const t of intervalTimers) realClearInterval(t);
- });
-
- async function bootMulti(workspaces: { id: string; name: string; token: string }[]) {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({ server_url: "", watched_workspaces: workspaces });
- let n = 0;
- mockClientInstance.register.mockImplementation(async () => ({ runtimes: [{ id: `rt${++n}` }] }));
- mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
- }
-
- it("AUTH_REJECTED confirmed by poll 401 marks the correct workspace, not undefined — no hot loop", async () => {
- // MEDIUM-1 regression guard: wsWorkspaceId must be set at the startup
- // construction, so onAuthRejected confirms ws1 (the WS token's workspace),
- // removes it, and rebuilds with ws2's token instead of spinning.
- await bootMulti([
- { id: "ws1", name: "A", token: "al_dead" },
- { id: "ws2", name: "B", token: "al_good" },
- ]);
- const tokenBefore = capturedWsOpts.machineToken;
- expect(tokenBefore).toBe("al_dead");
-
- // Confirm poll 401s → token confirmed dead.
- mockClientInstance.poll.mockRejectedValue(new Error("HTTP 401 Unauthorized"));
- capturedWsOpts.onAuthRejected("revoked");
- await new Promise((r) => setTimeout(r, 10));
-
- // ws1 soft-marked deleted in config
- const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls.at(-1)![1];
- expect(savedConfig.watched_workspaces!.find((w: any) => w.id === "ws1")?.status).toBe("deleted");
- // WS rebuilt with a DIFFERENT (surviving) token — no same-token respin
- expect(capturedWsOpts.machineToken).toBe("al_good");
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-
- it("AUTH_REJECTED confirmed by poll 401 with a single workspace rebuilds to no client and shuts down", async () => {
- await bootMulti([{ id: "ws1", name: "Only", token: "al_dead" }]);
- mockClientInstance.poll.mockRejectedValue(new Error("HTTP 401 Unauthorized"));
- capturedWsOpts.onAuthRejected();
- await new Promise((r) => setTimeout(r, 10));
-
- const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls.at(-1)![1];
- expect(savedConfig.watched_workspaces!.find((w: any) => w.id === "ws1")?.status).toBe("deleted");
- expect(mockProcessExit).toHaveBeenCalledWith(0);
- });
-
- it("AUTH_REJECTED NOT confirmed (confirm poll succeeds) keeps the workspace — false-invalid guard", async () => {
- // Replica lag right after activation: the WS-DO rejects a token that is
- // actually valid. The confirm poll succeeds, so the workspace must survive.
- await bootMulti([{ id: "ws1", name: "Only", token: "al_lagged" }]);
- // poll still resolves (bootMulti default) → rejection not confirmed.
- capturedWsOpts.onAuthRejected("replica-lag");
- await new Promise((r) => setTimeout(r, 10));
-
- const deletedWrites = vi.mocked(saveCLIConfigForProfile).mock.calls.filter(
- (c) => c[1].watched_workspaces?.some((w: any) => w.id === "ws1" && w.status === "deleted"),
- );
- expect(deletedWrites).toHaveLength(0);
- // WS rebuilt with the same still-valid token, daemon stays up.
- expect(capturedWsOpts.machineToken).toBe("al_lagged");
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-
- it("AUTH_REJECTED with a non-401 confirm error keeps the workspace — treated transient", async () => {
- await bootMulti([{ id: "ws1", name: "Only", token: "al_x" }]);
- mockClientInstance.poll.mockRejectedValue(new Error("HTTP 503 Service Unavailable"));
- capturedWsOpts.onAuthRejected();
- await new Promise((r) => setTimeout(r, 10));
-
- const deletedWrites = vi.mocked(saveCLIConfigForProfile).mock.calls.filter(
- (c) => c[1].watched_workspaces?.some((w: any) => w.id === "ws1" && w.status === "deleted"),
- );
- expect(deletedWrites).toHaveLength(0);
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-
- it("single poll 401 does NOT mark the workspace deleted (below threshold)", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "A", token: "al_x" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- mockClientInstance.poll.mockRejectedValue(new Error("HTTP 401 Unauthorized"));
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // One cycle → one 401 → below WS_AUTH_401_THRESHOLD (5) → no status write to deleted
- const deletedWrites = vi.mocked(saveCLIConfigForProfile).mock.calls.filter(
- (c) => c[1].watched_workspaces?.some((w: any) => w.id === "ws1" && w.status === "deleted"),
- );
- expect(deletedWrites).toHaveLength(0);
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-
- it("5 consecutive poll 401s mark the workspace deleted (threshold reached)", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "A", token: "al_x" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- intervalFns.length = 0;
- mockClientInstance.poll.mockRejectedValue(new Error("HTTP 401 Unauthorized"));
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // startDaemon ran one immediate poll (401 #1). Drive 4 more back-to-back
- // 401s via the captured poll cycle to reach WS_AUTH_401_THRESHOLD (5).
- const pollCycle = intervalFns[0];
- for (let i = 0; i < 4; i++) await pollCycle();
-
- const deletedWrites = vi.mocked(saveCLIConfigForProfile).mock.calls.filter(
- (c) => c[1].watched_workspaces?.some((w: any) => w.id === "ws1" && w.status === "deleted"),
- );
- expect(deletedWrites.length).toBeGreaterThan(0);
- });
-
- it("401s interleaved with transient errors do NOT reach the threshold (streak resets)", async () => {
- vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- server_url: "",
- watched_workspaces: [{ id: "ws1", name: "A", token: "al_x" }],
- });
- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
- intervalFns.length = 0;
- // Alternate 401 / non-401 across cycles. The non-401 (503) must reset the
- // streak so scattered 401s never accumulate to the threshold.
- let call = 0;
- mockClientInstance.poll.mockImplementation(async () => {
- call++;
- if (call % 2 === 1) throw new Error("HTTP 401 Unauthorized");
- throw new Error("HTTP 503 Service Unavailable");
- });
- await startDaemon();
- await new Promise((r) => setTimeout(r, 50));
-
- // startDaemon ran poll #1 (401). Drive 8 more: 503,401,503,401,503,401,503,401.
- // That's 5 total 401s but never 2 in a row → below threshold.
- const pollCycle = intervalFns[0];
- for (let i = 0; i < 8; i++) await pollCycle();
-
- const deletedWrites = vi.mocked(saveCLIConfigForProfile).mock.calls.filter(
- (c) => c[1].watched_workspaces?.some((w: any) => w.id === "ws1" && w.status === "deleted"),
- );
- expect(deletedWrites).toHaveLength(0);
- expect(mockProcessExit).not.toHaveBeenCalled();
- });
-});
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
deleted file mode 100644
index c0cd0a746..000000000
--- a/src/cli/daemon/daemon.ts
+++ /dev/null
@@ -1,1446 +0,0 @@
-import { DaemonClient } from "./client.js";
-import { type DaemonConfig, loadDaemonConfig, sessionRunnerLogDir, daemonLogFilePath } from "./config.js";
-import { createHealthServer } from "./health.js";
-import { detectVersion, createBackend } from "./agent/index.js";
-import { type Task, type Attachment, type SessionRunnerInput, fromApiTask } from "./types.js";
-import { type MarkerData, writeMarkerFile, downloadAttachments } from "./session-runner.js";
-import { buildPrompt, buildMergedPrompt } from "./prompt.js";
-import { loadCLIConfigForProfile, saveCLIConfigForProfile, activeWorkspaces, markWorkspaceDeletedInList } from "../lib/config.js";
-import { createLogger } from "../lib/logger.js";
-import { DaemonWsClient } from "./ws-client.js";
-import type { DaemonPushMessage } from "@alook/shared";
-
-const log = createLogger({ module: "daemon" });
-import { cmdPrefix } from "../lib/env.js";
-import { acquireDaemonPid, releaseDaemonPid } from "./pidfile.js";
-import { handleCliUpdate, isUpdating, readUpdateMarker, clearUpdateMarker } from "./update-handler.js";
-import { findRunningPidByTaskId, findSupersedablePredecessor, steerWarmupGraceMs, updateEntry, type ContextTimelineEntry } from "./execenv/timeline.js";
-import { isAlive, killGraceMs } from "./kill-tree.js";
-import {
- writeKillIntent,
- readKillIntent,
- clearKillIntent,
- acquireSteeringLock,
- releaseSteeringLock,
- cleanupStaleIntents,
-} from "./execenv/steering.js";
-import {
- ensureMailboxDirs,
- writeSteerMessage,
- waitForAck,
- inboxDir as steeringInboxDir,
-} from "./steering/mailbox.js";
-import { TASK_TYPES } from "@alook/shared";
-import { readDirectoryTree, readFileContent, validatePath } from "./workspace-files.js";
-import { startSkillScanner, stopSkillScanner } from "./skill-scanner.js";
-import { resolveLoginShellEnv } from "../lib/shell-env.js";
-import { existsSync, mkdirSync, openSync, closeSync, readdirSync, statSync, unlinkSync } from "fs";
-import { readdir, readFile, unlink, stat as fsStat } from "fs/promises";
-import { execSync, spawn, type ChildProcess } from "child_process";
-import { fileURLToPath } from "url";
-import { dirname, join } from "path";
-
-const _dir = dirname(fileURLToPath(import.meta.url));
-const sessionRunnerPath = existsSync(join(_dir, "session-runner.js"))
- ? join(_dir, "session-runner.js")
- : join(_dir, "session-runner.ts");
-const meetingRunnerPath = existsSync(join(_dir, "meeting-runner.js"))
- ? join(_dir, "meeting-runner.js")
- : join(_dir, "meeting-runner.ts");
-
-interface WorkspaceState {
- workspaceId: string;
- token: string;
- runtimeIds: string[];
-}
-
-interface RuntimeData {
- id: string;
- workspaceId: string;
- provider: string;
-}
-
-interface PendingEntry {
- tasks: Task[];
- attachments: Map<string, Attachment[]>;
- ownerTaskId: string;
- wake: () => void;
-}
-
-function isCommandAvailable(cmd: string): boolean {
- try {
- const check = process.platform === "win32" ? `where ${cmd}` : `which ${cmd}`;
- execSync(check, { stdio: "ignore" });
- return true;
- } catch {
- return false;
- }
-}
-
-const MAX_SESSION_RUNNER_LOGS = 500;
-
-export function pruneSessionRunnerLogs(): void {
- const logDir = sessionRunnerLogDir();
- let entries: string[];
- try {
- entries = readdirSync(logDir).filter((f) => f.endsWith(".log"));
- } catch {
- return;
- }
- if (entries.length <= MAX_SESSION_RUNNER_LOGS) return;
-
- const withMtime = entries.map((name) => {
- const full = join(logDir, name);
- try {
- return { name, mtime: statSync(full).mtimeMs };
- } catch {
- return { name, mtime: 0 };
- }
- });
- withMtime.sort((a, b) => b.mtime - a.mtime);
-
- for (const entry of withMtime.slice(MAX_SESSION_RUNNER_LOGS)) {
- try {
- unlinkSync(join(logDir, entry.name));
- } catch {
- // best-effort
- }
- }
-}
-
-export function isClientError(error: unknown): boolean {
- if (!(error instanceof Error)) return false;
- const match = error.message.match(/^HTTP (\d+):/);
- if (!match) return false;
- const status = Number(match[1]);
- if (status === 408 || status === 429) return false;
- return status >= 400 && status < 500;
-}
-
-function isValidMarker(data: unknown): data is MarkerData {
- if (!data || typeof data !== "object") return false;
- const d = data as Record<string, unknown>;
- if (typeof d.taskId !== "string") return false;
- if (typeof d.token !== "string") return false;
- if (typeof d.serverURL !== "string") return false;
- if (typeof d.createdAt !== "string" || isNaN(new Date(d.createdAt).getTime())) return false;
- if (!d.payload || typeof d.payload !== "object") return false;
- const payload = d.payload as Record<string, unknown>;
- if (d.type === "complete") {
- return typeof payload.output === "string";
- }
- if (d.type === "fail") {
- return typeof payload.error === "string";
- }
- return false;
-}
-
-const MARKER_STALE_MS = 24 * 60 * 60 * 1000;
-const TMP_STALE_MS = 60 * 60 * 1000;
-// Consecutive poll-401s before a workspace is marked auth-failed. The server
-// only returns 401 for a definitely-invalid token (transient DB failure → 503),
-// so this is a belt-and-braces guard against any residual transient 401.
-const WS_AUTH_401_THRESHOLD = 5;
-
-export async function reconcilePendingCompletions(workspacesRoot: string): Promise<void> {
- const dir = join(workspacesRoot, ".pending_completions");
- let entries: string[];
- try {
- entries = await readdir(dir);
- } catch {
- return;
- }
-
- // Housekeeping: clean up stale .tmp files
- for (const name of entries) {
- if (!name.endsWith(".tmp")) continue;
- try {
- const s = await fsStat(join(dir, name));
- if (Date.now() - s.mtimeMs > TMP_STALE_MS) {
- await unlink(join(dir, name));
- }
- } catch { /* best-effort */ }
- }
-
- const jsonFiles = entries.filter((f) => f.endsWith(".json"));
- for (const name of jsonFiles) {
- const filePath = join(dir, name);
- try {
- let raw: string;
- try {
- raw = await readFile(filePath, "utf-8");
- } catch {
- continue;
- }
-
- let parsed: unknown;
- try {
- parsed = JSON.parse(raw);
- } catch {
- log.warn(`reconcile: malformed marker ${name}, deleting`);
- try { await unlink(filePath); } catch { /* best-effort */ }
- continue;
- }
-
- if (!isValidMarker(parsed)) {
- log.warn(`reconcile: invalid marker structure ${name}, deleting`);
- try { await unlink(filePath); } catch { /* best-effort */ }
- continue;
- }
-
- const marker = parsed;
- const age = Date.now() - new Date(marker.createdAt).getTime();
- if (age > MARKER_STALE_MS) {
- log.warn(`reconcile: stale marker ${name} (${Math.round(age / 3600000)}h old), deleting`);
- try { await unlink(filePath); } catch { /* best-effort */ }
- continue;
- }
-
- const client = new DaemonClient(marker.serverURL);
- try {
- if (marker.type === "complete") {
- await client.completeTask(marker.token, marker.taskId, marker.payload);
- } else {
- await client.failTask(marker.token, marker.taskId, marker.payload.error);
- }
- try { await unlink(filePath); } catch (delErr) {
- log.warn(`reconcile: delivered marker ${name} but failed to delete: ${delErr}`);
- }
- } catch (deliverErr) {
- if (isClientError(deliverErr)) {
- try { await unlink(filePath); } catch { /* best-effort */ }
- } else {
- log.debug(`reconcile: delivery failed for ${name}, will retry next cycle`);
- }
- }
- } catch (e) {
- log.debug(`reconcile: error processing ${name}`, e);
- }
- }
-}
-
-export async function startDaemon(
- profile?: string,
- serverUrl?: string,
-): Promise<void> {
- pruneSessionRunnerLogs();
-
- if (!acquireDaemonPid(profile)) {
- process.exit(1);
- }
-
- // Safety net: no matter how the process terminates (normal exit, early
- // process.exit, shutdown timeout kick, uncaughtException), release the
- // pidfile. `releaseDaemonPid` only deletes when the file still points at us,
- // so a newer daemon's pidfile is safe.
- process.once("exit", () => releaseDaemonPid(profile));
- const bailOnUnexpected = (label: string, err: unknown) => {
- log.error(`${label} — shutting down`, err);
- releaseDaemonPid(profile);
- process.exit(1);
- };
- process.once("uncaughtException", (err) =>
- bailOnUnexpected("uncaughtException", err),
- );
- process.once("unhandledRejection", (err) =>
- bailOnUnexpected("unhandledRejection", err),
- );
-
- const config = loadDaemonConfig(profile);
- if (serverUrl) config.serverURL = serverUrl;
-
- const marker = readUpdateMarker(profile);
- if (marker) {
- clearUpdateMarker(profile);
- if (marker === config.cliVersion) {
- log.info(`Cleared update marker — now running v${config.cliVersion}`);
- } else {
- log.info(`Cleared stale update marker (was v${marker}, running v${config.cliVersion}) — update will be retried`);
- }
- }
-
- const cliConfig = loadCLIConfigForProfile(profile);
-
- const workspaces = activeWorkspaces(cliConfig.watched_workspaces);
-
- if (workspaces.length === 0) {
- log.info("No workspaces configured — daemon starting in standby mode. Register a workspace to begin.");
- }
-
- // Validate: each active workspace must have its own token
- if (workspaces.length > 0) {
- const hasPerWorkspaceTokens = workspaces.every((ws) => !!ws.token);
- if (!hasPerWorkspaceTokens) {
- log.error(
- `Config uses old format. Run '${cmdPrefix()} register --token <token>' for each workspace to upgrade.`,
- );
- process.exit(1);
- return;
- }
- }
-
- // Use server_url from first workspace's config if available
- if (cliConfig.server_url) config.serverURL = cliConfig.server_url;
-
- const client = new DaemonClient(config.serverURL);
- const health = createHealthServer();
-
- const providers: { type: string; path: string; version: string }[] = [];
- for (const [type, path] of [
- ["claude", config.claudePath],
- ["codex", config.codexPath],
- ["opencode", config.opencodePath],
- ] as const) {
- if (isCommandAvailable(path)) {
- const version = await detectVersion(path);
- providers.push({ type, path, version });
- }
- }
-
- if (providers.length === 0) {
- log.error("No agent CLI tools found on PATH.");
- process.exit(1);
- return;
- }
-
- log.info(
- `Detected providers: ${providers.map((p) => `${p.type}@${p.version}`).join(", ")}`,
- );
-
- const workspaceStates: WorkspaceState[] = [];
- const runtimeIndex = new Map<string, RuntimeData>();
- let hadWorkspaces = workspaces.length > 0;
- // Per-workspace consecutive poll-401 count. A workspace is marked deleted
- // only after WS_AUTH_401_THRESHOLD consecutive 401s (reset on any success),
- // so a transient 503/blip can't wrongly drop a healthy workspace.
- const consecutive401 = new Map<string, number>();
-
- for (const ws of workspaces) {
- const runtimes = providers.map((p) => ({
- type: p.type,
- version: p.version,
- }));
-
- log.info(`Registering workspace ${ws.id} (${ws.name ?? "unnamed"}) with ${runtimes.length} runtime(s)...`);
- let resp;
- try {
- resp = await client.register(ws.token, {
- workspace_id: ws.id,
- daemon_id: config.daemonId,
- device_name: config.deviceName,
- cli_version: config.cliVersion,
- workspaces_root: config.workspacesRoot,
- runtimes,
- });
- } catch (e) {
- if (e instanceof Error && e.message.startsWith("HTTP 401")) {
- log.warn(`Workspace ${ws.id} token invalid — skipping (run '${cmdPrefix()} register --token <token>' to fix)`);
- } else {
- log.error(`Failed to register workspace ${ws.id}, skipping`, e);
- }
- continue;
- }
- log.info(`Workspace ${ws.id} registered — ${resp.runtimes.length} runtime(s)`);
-
- const runtimeIds = resp.runtimes.map((r: { id: string }) => r.id);
- workspaceStates.push({ workspaceId: ws.id, token: ws.token, runtimeIds });
-
- for (let i = 0; i < runtimeIds.length; i++) {
- runtimeIndex.set(runtimeIds[i], {
- id: runtimeIds[i],
- workspaceId: ws.id,
- provider: providers[i].type,
- });
- }
- }
-
- if (workspaceStates.length === 0 && hadWorkspaces) {
- log.error("No workspaces registered successfully.");
- process.exit(1);
- return;
- }
-
- const allRuntimeIds = workspaceStates.flatMap((ws) => ws.runtimeIds);
- health.setRuntimeCount(allRuntimeIds.length);
- log.info(
- `Daemon started — ${allRuntimeIds.length} runtime(s) across ${workspaceStates.length} workspace(s)`,
- );
-
- const activeTasks = new Set<string>();
- const pendingSteer = new Map<string, PendingEntry>();
-
- // Seed known agent IDs from config so we only write on genuinely new ones
- const knownAgentIds = new Set<string>(
- workspaces.flatMap((ws) => ws.agent_ids ?? []),
- );
-
- function syncAgentId(agentId: string, workspaceId: string): void {
- if (knownAgentIds.has(agentId)) return;
- knownAgentIds.add(agentId);
- try {
- const cfg = loadCLIConfigForProfile(profile);
- const ws = cfg.watched_workspaces?.find((w) => w.id === workspaceId);
- if (!ws) return;
- if (!ws.agent_ids) ws.agent_ids = [];
- if (!ws.agent_ids.includes(agentId)) {
- ws.agent_ids.push(agentId);
- saveCLIConfigForProfile(profile, cfg);
- }
- } catch {
- // Non-fatal — config sync is best-effort
- }
- }
-
- /**
- * Single owner for taking a workspace out of the active poll set. Used by
- * every "this workspace is no longer usable" path: server evict, WS
- * AUTH_REJECTED, and repeated poll-401. It does the full in-memory cleanup
- * (workspaceStates + runtimeIndex + health count + 401 counter) AND persists
- * `status="deleted"` so a restart doesn't re-poll it (every reader goes
- * through `activeWorkspaces()`, which keeps only `status === "active"`).
- *
- * Soft-delete (mark), not physical removal: the config entry lingers so the
- * cause is inspectable and re-pairing (`activate.ts` sets status back to
- * "active" with a fresh token) recovers it. `reason` is logged, not stored
- * — status stays a 2-value field.
- */
- function markWorkspaceDeleted(workspaceId: string, reason: string): void {
- const idx = workspaceStates.findIndex((ws) => ws.workspaceId === workspaceId);
- if (idx === -1) return; // idempotent — already gone
-
- const ws = workspaceStates[idx];
- for (const rid of ws.runtimeIds) {
- runtimeIndex.delete(rid);
- }
- workspaceStates.splice(idx, 1);
- consecutive401.delete(workspaceId);
-
- health.setRuntimeCount(
- workspaceStates.reduce((sum, w) => sum + w.runtimeIds.length, 0),
- );
-
- try {
- const cfg = loadCLIConfigForProfile(profile);
- if (markWorkspaceDeletedInList(cfg.watched_workspaces || [], workspaceId)) {
- saveCLIConfigForProfile(profile, cfg);
- }
- } catch {
- // Best-effort — config write failure must not block in-memory removal
- }
-
- log.info(`Workspace ${workspaceId} removed from polling — ${reason}`);
- }
-
- // Staggered per-workspace polling
- const pollCycle = async () => {
- let remaining = config.maxConcurrentTasks - activeTasks.size;
- if (remaining <= 0) return;
-
- const N = workspaceStates.length;
- const staggerMs = N > 1 ? Math.floor(config.pollInterval / N) : 0;
- // Deferred removal — collected during the loop and applied AFTER it, because
- // markWorkspaceDeleted splices workspaceStates while we index by [i].
- const toRemove = new Map<string, string>(); // workspaceId -> reason
-
- for (let i = 0; i < N; i++) {
- if (remaining <= 0) break;
- const ws = workspaceStates[i];
-
- if (i > 0 && staggerMs > 0) {
- await new Promise((r) => setTimeout(r, staggerMs));
- }
-
- try {
- const { tasks: apiTasks, evicted, pending_update, pending_rescan, file_requests, meetings } = await client.poll(
- ws.token,
- config.daemonId,
- remaining,
- config.cliVersion,
- );
-
- // Any successful poll clears the workspace's 401 streak.
- consecutive401.delete(ws.workspaceId);
-
- if (evicted) {
- toRemove.set(ws.workspaceId, "server evicted");
- continue;
- }
-
- if (pending_update && !isUpdating() && pending_update.version !== config.cliVersion) {
- handleCliUpdate(pending_update.version, () => requestRestart(), profile);
- }
-
- if (pending_rescan) {
- log.info("Rescan requested — restarting daemon to re-detect runtimes");
- for (const [id, reason] of toRemove) {
- markWorkspaceDeleted(id, reason);
- }
- requestRestart();
- return;
- }
-
- for (const apiTask of apiTasks) {
- const task = fromApiTask(apiTask);
- syncAgentId(task.agentId, ws.workspaceId);
- activeTasks.add(task.id);
- remaining--;
- handleTask(client, config, runtimeIndex, task, ws.token, activeTasks, pendingSteer)
- .catch((e) => {
- log.error("Task error", e);
- activeTasks.delete(task.id);
- });
- }
-
- // Handle workspace file browse requests
- if (file_requests) {
- for (const req of file_requests) {
- handleFileRequest(client, config, ws.workspaceId, req, ws.token)
- .catch((e) => log.debug("File request error", e));
- }
- }
-
-
- // Spawn meeting bots from merged poll response
- if (meetings) {
- for (const m of meetings) {
- const agentBaseDir = join(config.workspacesRoot, m.workspace_id, m.agent_id, "workdir");
- const timelineDir = join(agentBaseDir, ".context_timeline");
- spawnMeetingRunner({
- meetingId: m.id,
- meetingUrl: m.meeting_url,
- participants: m.participants,
- workspaceId: m.workspace_id,
- callbackUrl: config.serverURL,
- authToken: ws.token,
- agentName: m.agent_name,
- agentId: m.agent_id,
- timelineDir,
- title: m.title,
- });
- }
- }
- } catch (e) {
- if (e instanceof Error && e.message.startsWith("HTTP 401")) {
- // 401 = definitely-invalid token (transient infra → 503, which lands
- // in the else branch). Count consecutive 401s; only mark deleted at
- // the threshold, as a guard against any residual transient 401.
- const n = (consecutive401.get(ws.workspaceId) ?? 0) + 1;
- consecutive401.set(ws.workspaceId, n);
- if (n >= WS_AUTH_401_THRESHOLD) {
- toRemove.set(ws.workspaceId, `poll 401 x${n}`);
- } else {
- log.warn(`Workspace ${ws.workspaceId} poll 401 (${n}/${WS_AUTH_401_THRESHOLD}) — will retry`);
- }
- } else {
- // Any non-401 outcome (503, network blip) breaks the 401 streak —
- // "consecutive" means back-to-back 401s, not 401s scattered across a
- // flaky window. Without this a 401/blip/401/blip… pattern would creep
- // to the threshold and wrongly delete a live workspace.
- consecutive401.delete(ws.workspaceId);
- log.debug("Poll error", e);
- }
- }
- }
-
- // Deferred removal (see toRemove comment). If we drop the workspace whose
- // token the WS client is using, rebuild the WS with a surviving token.
- if (toRemove.size > 0) {
- const wsTokenWorkspaceDropped = wsWorkspaceId != null && toRemove.has(wsWorkspaceId);
- for (const [id, reason] of toRemove) {
- markWorkspaceDeleted(id, reason);
- }
- if (wsTokenWorkspaceDropped) rebuildWsClient();
- }
-
- if (workspaceStates.length === 0 && hadWorkspaces) {
- log.info("All workspaces evicted — shutting down");
- shutdown();
- }
- };
-
- // Start at high-frequency poll; drop to low-frequency once WS auths
- // (onConnected). A dead machine token no longer pins the daemon here — T6's
- // AUTH_REJECTED handling removes the bad workspace and rotates the WS token
- // — so a transient WS outage polling at 3s is self-limiting (recovers on the
- // next auth.ok) and doesn't warrant a separate mid-frequency tier.
- let pollTimer = setInterval(pollCycle, config.pollInterval);
-
- // --- Heartbeat timer (independent of poll and WS state) ---
- const heartbeatPing = () => {
- for (const ws of workspaceStates) {
- client.heartbeat(ws.token, config.daemonId).catch((e) => {
- log.debug("heartbeat failed", { workspaceId: ws.workspaceId, err: String(e) });
- });
- }
- };
- const heartbeatTimer = setInterval(heartbeatPing, config.heartbeatInterval);
-
- // --- WS Push Channel (primary) + Poll fallback ---
- function updatePollInterval(newInterval: number) {
- clearInterval(pollTimer);
- pollTimer = setInterval(pollCycle, newInterval);
- }
-
- function handleWsPush(msg: DaemonPushMessage) {
- const wsMap = new Map(workspaceStates.map((ws) => [ws.workspaceId, ws]));
-
- switch (msg.type) {
- case "daemon.tasks":
- for (const apiTask of msg.tasks) {
- if (activeTasks.size >= config.maxConcurrentTasks) break;
- const task = fromApiTask(apiTask);
- if (activeTasks.has(task.id)) continue;
- const ws = wsMap.get(task.workspaceId);
- if (!ws) continue;
- syncAgentId(task.agentId, ws.workspaceId);
- activeTasks.add(task.id);
- handleTask(client, config, runtimeIndex, task, ws.token, activeTasks, pendingSteer)
- .catch((e) => { log.error("WS task error", e); activeTasks.delete(task.id); });
- }
- break;
-
- case "daemon.file_requests": {
- const ws = wsMap.get(msg.workspaceId);
- if (ws) {
- for (const req of msg.requests) {
- handleFileRequest(client, config, ws.workspaceId, req, ws.token)
- .catch((e) => log.debug("WS file request error", e));
- }
- }
- break;
- }
-
-
- case "daemon.meetings":
- for (const m of msg.meetings) {
- const ws = wsMap.get(m.workspace_id);
- if (!ws) continue;
- const agentBaseDir = join(config.workspacesRoot, m.workspace_id, m.agent_id, "workdir");
- const timelineDir = join(agentBaseDir, ".context_timeline");
- spawnMeetingRunner({
- meetingId: m.id,
- meetingUrl: m.meeting_url,
- participants: m.participants,
- workspaceId: m.workspace_id,
- callbackUrl: config.serverURL,
- authToken: ws.token,
- agentName: m.agent_name,
- agentId: m.agent_id,
- timelineDir,
- title: m.title,
- });
- }
- break;
-
- case "daemon.evict": {
- const wasWsToken = wsWorkspaceId === msg.workspaceId;
- markWorkspaceDeleted(msg.workspaceId, "server evicted");
- if (wasWsToken) rebuildWsClient();
- if (workspaceStates.length === 0 && hadWorkspaces) {
- log.info("All workspaces removed — shutting down");
- shutdown();
- }
- break;
- }
-
- case "daemon.update":
- if (!isUpdating() && msg.version !== config.cliVersion) {
- handleCliUpdate(msg.version, () => requestRestart(), profile);
- }
- break;
-
- case "daemon.rescan":
- log.info("WS rescan requested — restarting daemon");
- requestRestart();
- break;
-
- case "daemon.kill": {
- const ws = wsMap.get(msg.workspaceId);
- if (ws && !activeTasks.has(msg.taskId)) {
- const killTask = fromApiTask({
- id: msg.taskId,
- agent_id: msg.agentId,
- runtime_id: "",
- conversation_id: "",
- workspace_id: ws.workspaceId,
- prompt: "",
- status: "dispatched",
- priority: 0,
- dispatched_at: new Date().toISOString(),
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: new Date().toISOString(),
- type: "kill_task",
- context: { target_task_id: msg.targetTaskId },
- agent: null,
- sender: null,
- });
- activeTasks.add(killTask.id);
- handleTask(client, config, runtimeIndex, killTask, ws.token, activeTasks, pendingSteer)
- .catch((e) => { log.error("WS kill task error", e); activeTasks.delete(killTask.id); });
- }
- break;
- }
-
- }
- }
-
- let wsClient: DaemonWsClient | null = null;
- // Which workspace's token the current wsClient authenticates with. Needed so
- // that when that workspace is marked deleted (dead token) we know to rebuild
- // the WS with a surviving token. Set ONLY in rebuildWsClient — the single
- // construction path — so it can never drift out of sync with wsClient.
- let wsWorkspaceId: string | undefined;
-
- // Shared callbacks — stable across every (re)build so poll-frequency policy
- // and auth handling can't drift between construction sites.
- const wsCallbacks = {
- onMessage: handleWsPush,
- onConnected: () => {
- log.info("WS connected — switching to low-frequency poll");
- updatePollInterval(config.wsPollInterval);
- },
- onDisconnected: () => {
- log.info("WS disconnected — reverting to high-frequency poll");
- updatePollInterval(config.pollInterval);
- },
- onAuthRejected: (reason?: string) => {
- // A WS AUTH_REJECTED can be a false-invalid: the WS-DO may read a
- // replica-lagged (not-yet-propagated) token row right after activation
- // and reject a token that is actually valid. Rather than delete on this
- // one signal (the poll path already tolerates 4 transient 401s), confirm
- // with one authoritative HTTP poll before deleting.
- const rejectedWorkspaceId = wsWorkspaceId;
- const rejectedToken = workspaceStates.find(
- (ws) => ws.workspaceId === rejectedWorkspaceId,
- )?.token;
-
- // Tear down the rejected socket up front so its auto-reconnect can't
- // respin the same token during the confirm window. Don't rebuild yet:
- // rebuilding now would repick the still-present rejected workspace
- // (workspaceStates[0]) and reconnect the same token — the confirm decides
- // whether it stays, and every exit path below rebuilds afterwards.
- wsClient?.close();
- wsClient = null;
- wsWorkspaceId = undefined;
-
- if (rejectedWorkspaceId != null && rejectedToken) {
- void confirmAuthRejection(rejectedWorkspaceId, rejectedToken, reason);
- } else {
- rebuildWsClient();
- }
- },
- };
-
- /**
- * Confirm a WS AUTH_REJECTED with one authoritative poll before deleting the
- * workspace. `maxTasks: 0` makes the probe side-effect-free — it exercises the
- * same auth middleware as a normal poll but claims no tasks. Delete only on a
- * confirmed `HTTP 401`; a success or any non-401 error is treated as a
- * transient false-invalid and the workspace survives. Every path rebuilds the
- * WS (torn down by the caller) so the daemon never lingers without a socket.
- */
- async function confirmAuthRejection(
- workspaceId: string,
- token: string,
- reason?: string,
- ): Promise<void> {
- let confirmedDead = false;
- try {
- await client.poll(token, config.daemonId, 0, config.cliVersion);
- // Poll succeeded — the token is live; the WS rejection was a false-invalid
- // (likely replica lag). Keep the workspace; the rebuilt WS reconnects it.
- log.info(`Workspace ${workspaceId} WS auth rejection not confirmed by poll — keeping (likely transient)`);
- } catch (e) {
- if (e instanceof Error && e.message.startsWith("HTTP 401")) {
- confirmedDead = true;
- markWorkspaceDeleted(workspaceId, `WS auth rejected${reason ? ` (${reason})` : ""} — confirmed by poll 401`);
- } else {
- // Non-401 (503, network) — transient, not a token problem. Keep it.
- log.debug("Confirm-poll error (transient) — keeping workspace", e);
- }
- }
-
- rebuildWsClient();
- if (confirmedDead && workspaceStates.length === 0 && hadWorkspaces) {
- log.info("All workspaces removed — shutting down");
- shutdown();
- }
- }
-
- // The single WS (re)construction path. Any active machine token suffices —
- // WS auth is daemon-level; tasks route by workspaceId in handleWsPush.
- function rebuildWsClient(): void {
- wsClient?.close();
- const first = workspaceStates[0];
- if (!first) {
- wsClient = null;
- wsWorkspaceId = undefined;
- return;
- }
- wsWorkspaceId = first.workspaceId;
- wsClient = new DaemonWsClient({
- serverURL: config.serverURL,
- daemonId: config.daemonId,
- machineToken: first.token,
- ...wsCallbacks,
- });
- wsClient.connect();
- }
-
- rebuildWsClient();
-
- // --- Sweep timer: triggers server-side sweep + local reconciliation ---
- const sweepTick = async () => {
- for (const ws of workspaceStates) {
- client.sweep(ws.token, config.daemonId).catch((e) => {
- log.debug("sweep ping failed", { workspaceId: ws.workspaceId, err: String(e) });
- });
- }
- try {
- await reconcilePendingCompletions(config.workspacesRoot);
- } catch (e) {
- log.debug("reconciliation error", e);
- }
- };
- const sweepTimer = setInterval(sweepTick, config.sweepInterval);
-
- // --- Skill scanner: scans global + agent skills every 60s ---
- startSkillScanner(client, {
- workspacesRoot: config.workspacesRoot,
- workspaces: workspaces.map((ws) => ({
- workspaceId: ws.id,
- token: ws.token,
- agentIds: ws.agent_ids ?? [],
- })),
- runtimes: providers.map((p) => p.type as "claude" | "codex" | "opencode"),
- daemonId: config.daemonId,
- }, 60_000);
-
- let shuttingDown = false;
- let restartRequested = false;
-
- const requestRestart = () => {
- restartRequested = true;
- shutdown();
- };
-
- const shutdown = async () => {
- if (shuttingDown) return;
- shuttingDown = true;
- log.info(restartRequested ? "Restarting..." : "Shutting down...");
- clearInterval(pollTimer);
- clearInterval(heartbeatTimer);
- clearInterval(sweepTimer);
- stopSkillScanner();
- wsClient?.close();
-
- const shutdownMs = restartRequested ? 30000 : (Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000);
- const timeout = setTimeout(() => process.exit(1), shutdownMs);
-
- try {
- for (const ws of workspaceStates) {
- await client.deregister(ws.token, config.daemonId);
- }
- } catch {
- // best-effort deregister
- }
-
- releaseDaemonPid(profile);
- health.server.close(() => {
- if (restartRequested) {
- const entry = process.argv[1];
- const args = [entry, "daemon", "start", "--foreground"];
- if (profile) args.push("--profile", profile);
- if (serverUrl) args.push("--server", serverUrl);
- const logPath = daemonLogFilePath();
- let logFd: number | undefined;
- try {
- mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 });
- logFd = openSync(logPath, "a", 0o600);
- } catch (e) {
- log.error(`Failed to open daemon log file ${logPath}`, e);
- }
- const child = spawn(process.execPath, args, {
- detached: true,
- stdio: logFd != null ? ["ignore", logFd, logFd] : ["ignore", "ignore", "ignore"],
- env: resolveLoginShellEnv(),
- });
- child.unref();
- if (logFd != null) closeSync(logFd);
- log.info(`Spawned new daemon (pid=${child.pid}), logs: ${logPath}`);
- }
- clearTimeout(timeout);
- process.exit(0);
- });
- };
- process.on("SIGTERM", shutdown);
- process.on("SIGINT", shutdown);
-
- // SIGHUP: reload config and register any new workspaces
- process.on("SIGHUP", async () => {
- if (shuttingDown) return;
- log.info("SIGHUP received — reloading config...");
- try {
- const freshConfig = loadCLIConfigForProfile(profile);
- const freshWorkspaces = activeWorkspaces(freshConfig.watched_workspaces);
- const existingIds = new Set(workspaceStates.map((ws) => ws.workspaceId));
-
- const newWorkspaces = freshWorkspaces.filter(
- (ws) => ws.token && !existingIds.has(ws.id),
- );
-
- for (const ws of newWorkspaces) {
- const runtimes = providers.map((p) => ({ type: p.type, version: p.version }));
- log.info(`Registering new workspace ${ws.id} (${ws.name ?? "unnamed"})...`);
- try {
- const resp = await client.register(ws.token, {
- workspace_id: ws.id,
- daemon_id: config.daemonId,
- device_name: config.deviceName,
- cli_version: config.cliVersion,
- workspaces_root: config.workspacesRoot,
- runtimes,
- });
- const runtimeIds = resp.runtimes.map((r: { id: string }) => r.id);
- workspaceStates.push({ workspaceId: ws.id, token: ws.token, runtimeIds });
- for (let i = 0; i < runtimeIds.length; i++) {
- runtimeIndex.set(runtimeIds[i], {
- id: runtimeIds[i],
- workspaceId: ws.id,
- provider: providers[i].type,
- });
- }
- log.info(`Workspace ${ws.id} added — ${runtimeIds.length} runtime(s)`);
- } catch (e) {
- log.error(`Failed to register new workspace ${ws.id}`, e);
- }
- }
-
- if (newWorkspaces.length > 0) {
- hadWorkspaces = true;
- health.setRuntimeCount(
- workspaceStates.reduce((sum, w) => sum + w.runtimeIds.length, 0),
- );
- // Only (re)build if we don't already have a live WS — never tear down a
- // healthy connection on reload. rebuildWsClient sets wsWorkspaceId.
- if (!wsClient && workspaceStates.length > 0) {
- rebuildWsClient();
- log.info("WS push client initialized after SIGHUP reload");
- }
- log.info(`Reload complete — now polling ${workspaceStates.length} workspace(s)`);
- } else {
- log.info("Reload complete — no new workspaces found");
- }
- } catch (e) {
- log.error("Failed to reload config", e);
- }
- });
-
- await pollCycle();
-}
-
-export function spawnSessionRunner(input: SessionRunnerInput): ChildProcess {
- const logDir = sessionRunnerLogDir();
- mkdirSync(logDir, { recursive: true });
-
- const logFilePath = join(logDir, `${input.task.id}.log`);
- input.logFilePath = logFilePath;
-
- const encoded = Buffer.from(JSON.stringify(input)).toString("base64");
- let fd: number | undefined;
- try {
- fd = openSync(logFilePath, "a");
- } catch (e) {
- log.error(`Failed to open log file ${logFilePath}`, e);
- }
-
- const child = spawn(process.execPath, [sessionRunnerPath, encoded], {
- detached: true,
- stdio: fd != null ? ["ignore", fd, fd] : ["ignore", "ignore", "ignore"],
- });
- child.unref();
- if (fd != null) closeSync(fd);
-
- return child;
-}
-
-function spawnMeetingRunner(input: {
- meetingId: string;
- meetingUrl: string;
- participants: string[];
- workspaceId: string;
- callbackUrl: string;
- authToken: string;
- agentName?: string;
- agentId?: string;
- timelineDir?: string;
- title?: string;
-}): ChildProcess {
- const logDir = sessionRunnerLogDir();
- mkdirSync(logDir, { recursive: true });
-
- const logFilePath = join(logDir, `meeting-${input.meetingId}.log`);
- const encoded = Buffer.from(JSON.stringify(input)).toString("base64");
- let fd: number | undefined;
- try {
- fd = openSync(logFilePath, "a");
- } catch (e) {
- log.error(`Failed to open meeting log file ${logFilePath}`, e);
- }
-
- const child = spawn(process.execPath, [meetingRunnerPath, encoded], {
- detached: true,
- stdio: fd != null ? ["ignore", fd, fd] : ["ignore", "ignore", "ignore"],
- });
- child.unref();
- if (fd != null) closeSync(fd);
-
- log.info(`Spawned meeting runner for ${input.meetingId} (pid=${child.pid})`);
- return child;
-}
-
-async function handleFileRequest(
- client: DaemonClient,
- config: DaemonConfig,
- workspaceId: string,
- req: { id: string; agent_id: string; request_type: string; path: string },
- token: string,
-): Promise<void> {
- const agentWorkdir = join(config.workspacesRoot, workspaceId, req.agent_id, "workdir");
- const resolved = validatePath(agentWorkdir, req.path);
-
- if (!resolved) {
- await client.reportFileData(token, { request_id: req.id, error: "invalid path", path: req.path });
- return;
- }
-
- try {
- if (req.request_type === "tree") {
- const entries = await readDirectoryTree(resolved, agentWorkdir);
- await client.reportFileData(token, { request_id: req.id, entries, path: req.path });
- } else {
- const { content, isBinary } = await readFileContent(resolved);
- await client.reportFileData(token, { request_id: req.id, content, isBinary, path: req.path });
- }
- } catch (e) {
- await client.reportFileData(token, {
- request_id: req.id,
- error: e instanceof Error ? e.message : String(e),
- path: req.path,
- });
- }
-}
-
-/**
- * Send SIGTERM to the session-runner `pid`, then verify it actually died and
- * escalate to SIGKILL if not. Returns true if the signal was delivered, false
- * if the target was already gone (ESRCH).
- *
- * Backstop only: the session-runner's own SIGTERM handler is what reaps the
- * inner agent's process group. The verify window must EXCEED the session-runner
- * grace (ALOOK_KILL_GRACE_MS) so the runner gets to group-kill the inner agent
- * before we force-kill the runner — otherwise SIGKILLing the runner first could
- * orphan the inner agent. Inner agents are spawned in their own detached group
- * (agent/*.ts) so even a SIGKILLed runner does not leave the group un-reapable.
- */
-async function killAndVerify(pid: number): Promise<boolean> {
- try {
- process.kill(pid, "SIGTERM");
- } catch (e: unknown) {
- if ((e as NodeJS.ErrnoException)?.code === "ESRCH") return false;
- throw e;
- }
-
- // The verify window MUST exceed the session-runner's own group-kill grace, so
- // the runner gets to reap the inner agent's group before we force-kill it.
- // Enforce that invariant rather than trusting operators to keep the env vars
- // ordered (see the doc comment above).
- const verifyMs = Math.max(Number(process.env.ALOOK_KILL_VERIFY_MS) || 3000, killGraceMs() + 500);
- const deadline = Date.now() + verifyMs;
- while (Date.now() < deadline) {
- if (!isAlive(pid)) return true;
- await new Promise((r) => setTimeout(r, 100));
- }
-
- if (isAlive(pid)) {
- log.warn(`session-runner pid=${pid} survived SIGTERM after ${verifyMs}ms — escalating to SIGKILL`);
- try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ }
- }
- return true;
-}
-
-async function handleTask(
- client: DaemonClient,
- config: DaemonConfig,
- runtimeIndex: Map<string, RuntimeData>,
- task: Task,
- token: string,
- activeTasks: Set<string>,
- pendingSteer: Map<string, PendingEntry>,
-): Promise<void> {
- log.info(`Task ${task.id} claimed agent=${task.agentId}`);
-
- if (task.type === TASK_TYPES.KILL_TASK) {
- const targetTaskId = (task.context as Record<string, unknown>)?.target_task_id as string | undefined;
- if (!targetTaskId) {
- await client.failTask(token, task.id, "missing target_task_id in context");
- activeTasks.delete(task.id);
- return;
- }
-
- const agentBaseDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
- const timelineDir = join(agentBaseDir, ".context_timeline");
-
- // Retry loop: session-runner may not have written its timeline entry yet
- const MAX_WAIT_MS = Number(process.env.ALOOK_KILL_TASK_MAX_WAIT_MS) || 15_000;
- const POLL_MS = Number(process.env.ALOOK_KILL_TASK_POLL_MS) || 200;
- const waitStart = Date.now();
- let pid: number | null = null;
- while (Date.now() - waitStart < MAX_WAIT_MS) {
- pid = findRunningPidByTaskId(timelineDir, targetTaskId);
- if (pid != null) break;
- await new Promise((r) => setTimeout(r, POLL_MS));
- }
-
- if (pid != null) {
- writeKillIntent(agentBaseDir, {
- reason: "cancelled",
- targetTaskId,
- expectedPid: pid,
- });
- try {
- const delivered = await killAndVerify(pid);
- if (delivered) {
- await client.failTask(token, task.id, "killed");
- log.info(`Kill task ${task.id}: terminated pid=${pid} for target=${targetTaskId}`);
- } else {
- await client.failTask(token, task.id, "target process already exited");
- log.info(`Kill task ${task.id}: target pid=${pid} already exited`);
- }
- } catch (e: unknown) {
- await client.failTask(token, task.id, `kill failed: ${e}`);
- }
- } else {
- await client.failTask(token, task.id, "target not found in timeline");
- log.info(`Kill task ${task.id}: target ${targetTaskId} not found in timeline`);
- }
-
- activeTasks.delete(task.id);
- return;
- }
-
- try {
- await client.startTask(token, task.id);
- } catch (e) {
- await client.failTask(token, task.id, `start failed: ${e}`);
- activeTasks.delete(task.id);
- return;
- }
-
- // Resolve provider-specific CLI path and model
- const runtimeData = runtimeIndex.get(task.runtimeId);
- if (!runtimeData) {
- await client.failTask(token, task.id, `unknown runtime: ${task.runtimeId}`);
- activeTasks.delete(task.id);
- return;
- }
-
- const provider = runtimeData.provider;
-
- // --- Steering: supersede predecessor if same context_key + provider ---
- let promptOverride: string | undefined;
- if (task.contextKey) {
- const agentBaseDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
- cleanupStaleIntents(agentBaseDir);
- const timelineDir = join(agentBaseDir, ".context_timeline");
- const ctxKey = task.contextKey;
-
- let lockAcquired = acquireSteeringLock(agentBaseDir, ctxKey);
- if (!lockAcquired) {
- // Lock held by another task's steering cycle. Wait for the owner to
- // create a pendingSteer entry so we can merge into it, rather than
- // bypassing steering and spawning a concurrent runner.
- const MERGE_WAIT_MS = 5_000;
- const MERGE_POLL_MS = 50;
- const mergeStart = Date.now();
- while (Date.now() - mergeStart < MERGE_WAIT_MS) {
- const existing = pendingSteer.get(ctxKey);
- if (existing) {
- const attachmentIds = (task.context?.attachment_ids as string[]) ?? [];
- let myAttachments: Attachment[] = [];
- if (attachmentIds.length > 0) {
- try { myAttachments = await downloadAttachments(client, token, task.workspaceId, task.id, attachmentIds); } catch { /* best effort */ }
- }
- existing.tasks.push(task);
- existing.attachments.set(task.id, myAttachments);
- log.info(`Steering: ${task.id} merged into pending entry (lock contention) for context_key=${ctxKey} (${existing.tasks.length} tasks)`);
- existing.wake();
- try { await client.supersedeTask(token, task.id); } catch { /* best effort */ }
- activeTasks.delete(task.id);
- return;
- }
- // Owner hasn't set the entry yet — also try acquiring the lock ourselves
- lockAcquired = acquireSteeringLock(agentBaseDir, ctxKey);
- if (lockAcquired) break;
- await new Promise((r) => setTimeout(r, MERGE_POLL_MS));
- }
- if (!lockAcquired) {
- log.warn(`Steering lock contention for context_key=${ctxKey}, proceeding without steering`);
- }
- }
- if (lockAcquired) {
- try {
- const result = findSupersedablePredecessor(timelineDir, ctxKey, provider, steerWarmupGraceMs(), Date.now());
-
- if (result) {
- // CASE 2: predecessor exists (pending or supersedable) — go through the pendingSteer Map.
- const existing = pendingSteer.get(ctxKey);
-
- if (!existing) {
- // I am the owner (first waiter). Download my attachments, create the entry, run the wait loop.
- const attachmentIds = (task.context?.attachment_ids as string[]) ?? [];
- let myAttachments: Attachment[] = [];
- if (attachmentIds.length > 0) {
- try {
- myAttachments = await downloadAttachments(client, token, task.workspaceId, task.id, attachmentIds);
- } catch (e) {
- log.warn(`Steering: failed to download attachments for ${task.id}`, e);
- }
- }
-
- let ownerWake!: () => void;
- const ownerSignal = new Promise<void>((resolve) => { ownerWake = resolve; });
- const entry: PendingEntry = {
- tasks: [task],
- attachments: new Map([[task.id, myAttachments]]),
- ownerTaskId: task.id,
- wake: ownerWake,
- };
- pendingSteer.set(ctxKey, entry);
-
- // Owner's wait loop: poll predecessor until started/stale/gone.
- let predecessor = "entry" in result ? result.entry : null;
- if (!predecessor) {
- log.info(`Steering: predecessor ${(result as { pending: ContextTimelineEntry }).pending.task_id} warming up; ${task.id} waiting`);
- const POLL_MS = 200;
- const MAX_WAIT_MS = steerWarmupGraceMs();
- const waitStart = Date.now();
- while (Date.now() - waitStart < MAX_WAIT_MS) {
- releaseSteeringLock(agentBaseDir, ctxKey);
- await Promise.race([new Promise((r) => setTimeout(r, POLL_MS)), ownerSignal]);
- if (!acquireSteeringLock(agentBaseDir, ctxKey)) continue;
- const r = findSupersedablePredecessor(timelineDir, ctxKey, provider, steerWarmupGraceMs(), Date.now());
- if (!r) { log.info(`Steering: predecessor vanished; ${task.id} proceeding`); break; }
- if ("entry" in r) { predecessor = r.entry; break; }
- }
- if (!predecessor && Date.now() - waitStart >= MAX_WAIT_MS) {
- releaseSteeringLock(agentBaseDir, ctxKey);
- if (acquireSteeringLock(agentBaseDir, ctxKey)) {
- const finalCheck = findSupersedablePredecessor(timelineDir, ctxKey, provider, 0, Date.now());
- if (finalCheck && "entry" in finalCheck) predecessor = finalCheck.entry;
- }
- }
- }
-
- // Supersede predecessor if found.
- if (predecessor && predecessor.task_id !== task.id) {
- // Steering-first: try mailbox injection for persistent backends
- const backendInst = createBackend(provider, "");
- const isPersistent = backendInst.lifecycle?.kind === "persistent";
-
- if (config.enableSteering && isPersistent && predecessor.pid != null) {
- log.info(`Steering: task ${task.id} steering into predecessor ${predecessor.task_id} via mailbox (context_key=${ctxKey})`);
- try {
- ensureMailboxDirs(agentBaseDir, ctxKey);
-
- // Download attachments for the steered task
- const attachmentIds = (task.context?.attachment_ids as string[]) ?? [];
- let steerAttachments: { localPath: string; filename: string; contentType: string }[] = [];
- if (attachmentIds.length > 0) {
- try {
- const downloaded = await downloadAttachments(client, token, task.workspaceId, task.id, attachmentIds);
- steerAttachments = downloaded.map((a) => ({ localPath: a.path, filename: a.filename, contentType: a.content_type }));
- } catch (e) {
- log.warn(`Steering mailbox: failed to download attachments for ${task.id}`, e);
- }
- }
-
- const seq = writeSteerMessage(agentBaseDir, ctxKey, {
- taskId: task.id,
- text: buildPrompt(task),
- attachments: steerAttachments,
- createdAt: new Date().toISOString(),
- });
-
- const ackResult = await waitForAck(agentBaseDir, ctxKey, seq);
- if (ackResult.acked) {
- log.info(`Steering: task ${task.id} steered into predecessor ${predecessor.task_id} (acked)`);
- try { await client.startTask(token, task.id); } catch { /* best effort — already started above */ }
- pendingSteer.delete(ctxKey);
- activeTasks.delete(task.id);
- return;
- }
- log.info(`Steering: mailbox delivery failed for ${task.id} (${ackResult.nackReason}), falling back to kill-and-respawn`);
- } catch (e) {
- log.warn(`Steering: mailbox error for ${task.id}, falling back to kill-and-respawn`, e);
- }
- }
-
- // Fallback: kill-and-respawn (existing behavior)
- log.info(`Steering: task ${task.id} supersedes predecessor ${predecessor.task_id} (context_key=${ctxKey})`);
- if (predecessor.pid != null) {
- writeKillIntent(agentBaseDir, { reason: "superseded", targetTaskId: predecessor.task_id, expectedPid: predecessor.pid, successorTaskId: task.id });
- try {
- const delivered = await killAndVerify(predecessor.pid);
- log.info(delivered ? `Steering: terminated predecessor pid=${predecessor.pid}` : `Steering: predecessor pid=${predecessor.pid} already exited`);
- } catch (e: unknown) { log.warn(`Steering: kill failed for pid=${predecessor.pid}`, e); }
- const killWaitStart = Date.now();
- while (Date.now() - killWaitStart < 15_000) {
- if (findRunningPidByTaskId(timelineDir, predecessor.task_id) == null) break;
- await new Promise((r) => setTimeout(r, 200));
- }
- }
- try {
- await client.supersedeTask(token, predecessor.task_id);
- } catch { /* best effort — predecessor may already be in terminal state from its close handler */ }
- }
-
- // Build merged prompt if multiple tasks accumulated.
- const finalEntry = pendingSteer.get(ctxKey);
- if (finalEntry && finalEntry.tasks.length > 1) {
- promptOverride = buildMergedPrompt(finalEntry.tasks, finalEntry.attachments);
- log.info(`Steering: merged ${finalEntry.tasks.length} tasks for context_key=${ctxKey}`);
- } else if (finalEntry && finalEntry.tasks.length === 1) {
- const att = finalEntry.attachments.get(task.id);
- if (att && att.length > 0) {
- promptOverride = buildPrompt(task, att);
- }
- }
- pendingSteer.delete(ctxKey);
- } else {
- // I am NOT the owner — merge my content into the existing entry and exit.
- const attachmentIds = (task.context?.attachment_ids as string[]) ?? [];
- let myAttachments: Attachment[] = [];
- if (attachmentIds.length > 0) {
- try {
- myAttachments = await downloadAttachments(client, token, task.workspaceId, task.id, attachmentIds);
- } catch (e) { log.warn(`Steering: failed to download attachments for ${task.id}`, e); }
- }
-
- // Mark all previous tasks in the entry as superseded server-side (content kept in tasks array).
- for (const prev of existing.tasks) {
- if (prev.id !== existing.ownerTaskId) {
- try { await client.supersedeTask(token, prev.id); } catch { /* best effort */ }
- }
- }
-
- existing.tasks.push(task);
- existing.attachments.set(task.id, myAttachments);
- log.info(`Steering: ${task.id} merged into pending entry for context_key=${ctxKey} (${existing.tasks.length} tasks)`);
- existing.wake();
- try { await client.supersedeTask(token, task.id); } catch { /* best effort */ }
- activeTasks.delete(task.id);
- return; // Non-owner exits — owner spawns on my behalf. Lock released by finally.
- }
- }
- // CASE 1 (null result) falls through: no predecessor → spawn immediately.
- } finally {
- releaseSteeringLock(agentBaseDir, ctxKey);
- }
- }
- }
-
- const cliPath =
- provider === "claude"
- ? config.claudePath
- : provider === "codex"
- ? config.codexPath
- : config.opencodePath;
- const configModel =
- provider === "claude"
- ? config.claudeModel
- : provider === "codex"
- ? config.codexModel
- : config.opencodeModel;
- const agentModel = task.agent?.runtimeConfig?.model;
- const model = (typeof agentModel === "string" && agentModel) ? agentModel : configModel;
-
- // Determine if this session-runner should watch the steering mailbox
- const backendForInput = createBackend(provider, "");
- const steeringEligible = config.enableSteering && backendForInput.lifecycle?.kind === "persistent" && !!task.contextKey;
- let steeringMailboxDir: string | undefined;
- if (steeringEligible) {
- const agentBaseDirForSteering = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
- ensureMailboxDirs(agentBaseDirForSteering, task.contextKey!);
- steeringMailboxDir = steeringInboxDir(agentBaseDirForSteering, task.contextKey!);
- }
-
- const input: SessionRunnerInput = {
- task,
- provider,
- cliPath,
- model,
- serverURL: config.serverURL,
- token,
- workspacesRoot: config.workspacesRoot,
- agentTimeout: config.agentTimeout,
- messageInactivityTimeout: config.messageInactivityTimeout,
- ...(promptOverride && { promptOverride }),
- ...(steeringEligible && { steeringEnabled: true }),
- ...(steeringMailboxDir && { steeringMailboxDir }),
- };
-
- const child = spawnSessionRunner(input);
- child.on("close", async (code) => {
- activeTasks.delete(task.id);
- if (code !== 0) {
- const agentBaseDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
-
- // Check kill intent first — if present, the exit was expected.
- const killIntent = readKillIntent(agentBaseDir, task.id);
- if (killIntent) {
- log.info(`Task ${task.id} exited (${killIntent.reason}) — expected, skipping failTask`);
- clearKillIntent(agentBaseDir, task.id);
- return;
- }
-
- // No intent file — the session-runner's onKill handler may have already
- // cleared it and marked the task terminal (superseded/cancelled/failed).
- // Try to mark it failed server-side; if it's already terminal, that's fine.
- const errorMsg = code === null ? "killed by signal" : `session-runner exited with code ${code}`;
- try {
- await client.failTask(token, task.id, errorMsg);
- // failTask succeeded → this was a genuine unexpected crash.
- log.warn(`session-runner crashed (${errorMsg}, task ${task.id})`);
- const timelineDir = join(agentBaseDir, ".context_timeline");
- updateEntry(timelineDir, task.id, (entry) => {
- entry.pid = null;
- entry.status = "failed";
- entry.errmsg = errorMsg;
- });
- } catch (e) {
- if (isClientError(e)) {
- // Task already in terminal state (session-runner's onKill handled it).
- // This is the normal path for superseded/cancelled tasks — not a crash.
- log.info(`Task ${task.id} exited (already terminal) — session-runner handled cleanup`);
- return;
- }
- log.error(`Failed to report crash for task ${task.id}`, e);
- try {
- await writeMarkerFile(config.workspacesRoot, {
- taskId: task.id,
- type: "fail",
- payload: { error: errorMsg },
- token,
- serverURL: config.serverURL,
- createdAt: new Date().toISOString(),
- });
- } catch { /* best-effort */ }
- }
- }
- });
- log.info(`Task ${task.id} dispatched to session-runner (pid=${child.pid})`);
-}
diff --git a/src/cli/daemon/execenv/__tests__/context.test.ts b/src/cli/daemon/execenv/__tests__/context.test.ts
deleted file mode 100644
index 5c778d6c3..000000000
--- a/src/cli/daemon/execenv/__tests__/context.test.ts
+++ /dev/null
@@ -1,441 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-
-vi.mock("fs", async (importOriginal) => {
- const actual = await importOriginal<typeof import("fs")>();
- return { ...actual, symlinkSync: vi.fn(actual.symlinkSync) };
-});
-
-import {
- mkdirSync,
- writeFileSync,
- readFileSync,
- existsSync,
- rmSync,
- lstatSync,
- readlinkSync,
- symlinkSync,
- unlinkSync,
-} from "fs";
-import { join } from "path";
-import { tmpdir } from "os";
-import {
- buildInstructionContent,
- contentHash,
- hasContentChanged,
- ensureSymlinks,
- writeInstructionFileIfChanged,
- CANONICAL_FILE,
- SYMLINK_ALIASES,
-} from "../context.js";
-import type { Task } from "../../types.js";
-
-function makeTask(overrides: Partial<Task> = {}): Task {
- return {
- id: "t1",
- agentId: "a1",
- runtimeId: "rt1",
- conversationId: "c1",
- workspaceId: "ws1",
- prompt: "do something",
- status: "running",
- priority: 0,
- type: "user_dm_message",
- createdAt: "2026-01-01T00:00:00Z",
- traceId: null,
- parentTaskId: null,
- channel: null,
- agent: { name: "test-agent", instructions: "Be helpful and concise." },
- ...overrides,
- };
-}
-
-describe("buildInstructionContent", () => {
- it("uses agent name in opening line when provided", () => {
- const task = makeTask({ agent: { name: "My Assistant", instructions: "" } });
- const content = buildInstructionContent(task);
- expect(content).toContain("You're My Assistant in the Alook Platform.");
- });
-
- it("falls back to 'Alook Agent' when agent is undefined", () => {
- const task = makeTask({ agent: undefined });
- const content = buildInstructionContent(task);
- expect(content).toContain("You're Alook Agent in the Alook Platform.");
- });
-
- it("includes agent email in opening line", () => {
- const task = makeTask({
- agent: { name: "Aria", instructions: "", emailHandle: "aria" },
- });
- const content = buildInstructionContent(task);
- expect(content).toContain("You're Aria ([email protected]) in the Alook Platform.");
- });
-
- it("omits email parenthetical when no email configured", () => {
- const task = makeTask({
- agent: { name: "Aria", instructions: "" },
- });
- const content = buildInstructionContent(task);
- expect(content).toContain("You're Aria in the Alook Platform.");
- expect(content).not.toContain("You're Aria (");
- });
-
- it("includes owner name and email", () => {
- const task = makeTask({
- agent: { name: "Aria", instructions: "", userName: "Gustavo", userEmail: "[email protected]" },
- });
- const content = buildInstructionContent(task);
- expect(content).toContain("Your owner and creator is Gustavo ([email protected]).");
- });
-
- it("includes owner email without name when name is not available", () => {
- const task = makeTask({
- agent: { name: "Aria", instructions: "", userEmail: "[email protected]" },
- });
- const content = buildInstructionContent(task);
- expect(content).toContain("Your owner and creator is ([email protected]).");
- });
-
- it("omits owner sentence when no owner info available", () => {
- const task = makeTask({
- agent: { name: "Aria", instructions: "" },
- });
- const content = buildInstructionContent(task);
- expect(content).not.toContain("owner and creator");
- });
-
- it("uses custom email address when no alook handle", () => {
- const task = makeTask({
- agent: { name: "Aria", instructions: "", emailAddresses: ["[email protected]"] },
- });
- const content = buildInstructionContent(task);
- expect(content).toContain("You're Aria ([email protected]) in the Alook Platform.");
- });
-});
-
-describe("buildInstructionContent memory & format", () => {
- it("renders the Memory section with index / what-to-memorize / what-not-to-memorize sub-headings", () => {
- const content = buildInstructionContent(makeTask());
- expect(content).toContain("## Memory");
- expect(content).toContain("### memory.md — your memory index");
- expect(content).toContain("### What to memorize");
- expect(content).toContain("### What NOT to memorize");
- // memory.md must NOT instruct recording time-sensitive in-progress state (that's the Timeline's job)
- expect(content).toContain("Context Timeline already records");
- });
-
- it("preserves the load-bearing memory facts (memory.md, experiences/, 140-char threshold)", () => {
- const content = buildInstructionContent(makeTask());
- expect(content).toContain("memory.md");
- expect(content).toContain("experiences/");
- expect(content).toContain("140 chars");
- });
-
- it("no longer emits the legacy big-boss separator", () => {
- const content = buildInstructionContent(
- makeTask({ agent: { name: "test", instructions: "Follow these rules" } }),
- );
- expect(content).toContain("## BIG BOSS Instructions");
- expect(content).toContain("Follow these rules");
- expect(content).not.toContain("---- big boss out ---");
- });
-
- it("includes the email quick reference when an email handle is configured", () => {
- const content = buildInstructionContent(
- makeTask({ agent: { name: "test", instructions: "", emailHandle: "myagent" } }),
- );
- expect(content).toContain("### Email command quick reference");
- expect(content).toContain("email pull --email_id <EMAIL_ID>");
- });
-
- it("always renders the email section (every agent has an email)", () => {
- const content = buildInstructionContent(
- makeTask({ agent: { name: "test", instructions: "" } }),
- );
- expect(content).toContain("### Email command quick reference");
- expect(content).toContain("email pull --email_id <EMAIL_ID>");
- });
-
- it("renders the Talking to the user block instructing send-dm", () => {
- const content = buildInstructionContent(
- makeTask({ agent: { name: "test", instructions: "", emailHandle: "myagent" } }),
- );
- expect(content).toContain("### Talking to the user");
- expect(content).toContain("texting a colleague");
- expect(content).toContain("sync send-dm");
- });
-});
-
-describe("contentHash", () => {
- it("returns consistent hex string for same input", () => {
- const h1 = contentHash("hello world");
- const h2 = contentHash("hello world");
- expect(h1).toBe(h2);
- expect(h1).toMatch(/^[0-9a-f]{64}$/);
- });
-
- it("returns different hex strings for different inputs", () => {
- const h1 = contentHash("hello");
- const h2 = contentHash("world");
- expect(h1).not.toBe(h2);
- });
-});
-
-describe("hasContentChanged", () => {
- let workDir: string;
-
- beforeEach(() => {
- workDir = join(tmpdir(), `execenv-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(workDir, { recursive: true });
- });
-
- afterEach(() => {
- rmSync(workDir, { recursive: true, force: true });
- });
-
- it("returns true when file does not exist", () => {
- expect(hasContentChanged(join(workDir, "missing.md"), "content")).toBe(true);
- });
-
- it("returns false when file exists with identical content", () => {
- const filePath = join(workDir, "test.md");
- writeFileSync(filePath, "same content", "utf-8");
- expect(hasContentChanged(filePath, "same content")).toBe(false);
- });
-
- it("returns true when file exists with different content", () => {
- const filePath = join(workDir, "test.md");
- writeFileSync(filePath, "old content", "utf-8");
- expect(hasContentChanged(filePath, "new content")).toBe(true);
- });
-});
-
-describe("ensureSymlinks", () => {
- let workDir: string;
-
- beforeEach(() => {
- vi.mocked(symlinkSync).mockRestore();
- workDir = join(tmpdir(), `execenv-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(workDir, { recursive: true });
- });
-
- afterEach(() => {
- vi.mocked(symlinkSync).mockRestore();
- rmSync(workDir, { recursive: true, force: true });
- });
-
- it("creates CLAUDE.md symlink pointing to AGENTS.md", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "content", "utf-8");
- ensureSymlinks(workDir);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(true);
- expect(readlinkSync(aliasPath)).toBe(CANONICAL_FILE);
- });
-
- it("does not create symlink when canonical file doesn't exist", () => {
- ensureSymlinks(workDir);
-
- expect(existsSync(join(workDir, "CLAUDE.md"))).toBe(false);
- });
-
- it("replaces a regular file at alias path with a symlink", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "content", "utf-8");
- writeFileSync(join(workDir, "CLAUDE.md"), "old regular file", "utf-8");
-
- ensureSymlinks(workDir);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(true);
- expect(readlinkSync(aliasPath)).toBe(CANONICAL_FILE);
- });
-
- it("replaces a symlink pointing to wrong target", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "content", "utf-8");
- writeFileSync(join(workDir, "WRONG.md"), "wrong", "utf-8");
- symlinkSync("WRONG.md", join(workDir, "CLAUDE.md"));
-
- ensureSymlinks(workDir);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(true);
- expect(readlinkSync(aliasPath)).toBe(CANONICAL_FILE);
- });
-
- it("is no-op when correct symlink already exists", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "content", "utf-8");
- symlinkSync(CANONICAL_FILE, join(workDir, "CLAUDE.md"));
-
- // Should not throw
- ensureSymlinks(workDir);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(true);
- expect(readlinkSync(aliasPath)).toBe(CANONICAL_FILE);
- });
-
- it("falls back to file copy when symlinkSync throws EPERM", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "canonical content", "utf-8");
- vi.mocked(symlinkSync).mockImplementation(() => {
- const err = new Error("EPERM: operation not permitted, symlink") as NodeJS.ErrnoException;
- err.code = "EPERM";
- throw err;
- });
-
- ensureSymlinks(workDir);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isFile()).toBe(true);
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(false);
- expect(readFileSync(aliasPath, "utf-8")).toBe("canonical content");
- });
-
- it("falls back to file copy when symlinkSync throws EACCES", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "canonical content", "utf-8");
- vi.mocked(symlinkSync).mockImplementation(() => {
- const err = new Error("EACCES: permission denied, symlink") as NodeJS.ErrnoException;
- err.code = "EACCES";
- throw err;
- });
-
- ensureSymlinks(workDir);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isFile()).toBe(true);
- expect(readFileSync(aliasPath, "utf-8")).toBe("canonical content");
- });
-
- it("re-throws non-EPERM/EACCES errors from symlinkSync", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "content", "utf-8");
- vi.mocked(symlinkSync).mockImplementation(() => {
- const err = new Error("EIO: i/o error, symlink") as NodeJS.ErrnoException;
- err.code = "EIO";
- throw err;
- });
-
- expect(() => ensureSymlinks(workDir)).toThrow("EIO");
- });
-
- it("existing regular file copy with matching content is left untouched", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "same content", "utf-8");
- writeFileSync(join(workDir, "CLAUDE.md"), "same content", "utf-8");
- const mtimeBefore = lstatSync(join(workDir, "CLAUDE.md")).mtimeMs;
-
- ensureSymlinks(workDir);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isFile()).toBe(true);
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(false);
- expect(readFileSync(aliasPath, "utf-8")).toBe("same content");
- expect(lstatSync(aliasPath).mtimeMs).toBe(mtimeBefore);
- });
-
- it("existing regular file copy with stale content is refreshed", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "new content", "utf-8");
- writeFileSync(join(workDir, "CLAUDE.md"), "old content", "utf-8");
- vi.mocked(symlinkSync).mockImplementation(() => {
- const err = new Error("EPERM: operation not permitted, symlink") as NodeJS.ErrnoException;
- err.code = "EPERM";
- throw err;
- });
-
- ensureSymlinks(workDir);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(readFileSync(aliasPath, "utf-8")).toBe("new content");
- });
-
- it("transitions from symlink to copy when permissions change", () => {
- writeFileSync(join(workDir, CANONICAL_FILE), "content", "utf-8");
- // First call creates a real symlink (symlinkSync uses real implementation by default)
- ensureSymlinks(workDir);
- expect(lstatSync(join(workDir, "CLAUDE.md")).isSymbolicLink()).toBe(true);
-
- // Simulate permission loss — remove symlink and mock EPERM
- unlinkSync(join(workDir, "CLAUDE.md"));
- vi.mocked(symlinkSync).mockImplementation(() => {
- const err = new Error("EPERM: operation not permitted, symlink") as NodeJS.ErrnoException;
- err.code = "EPERM";
- throw err;
- });
-
- ensureSymlinks(workDir);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isFile()).toBe(true);
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(false);
- expect(readFileSync(aliasPath, "utf-8")).toBe("content");
- });
-});
-
-describe("writeInstructionFileIfChanged", () => {
- let workDir: string;
-
- beforeEach(() => {
- workDir = join(tmpdir(), `execenv-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(workDir, { recursive: true });
- });
-
- afterEach(() => {
- rmSync(workDir, { recursive: true, force: true });
- });
-
- it("writes AGENTS.md on first call (no prior file), returns true", () => {
- const task = makeTask();
- const result = writeInstructionFileIfChanged(workDir, task);
-
- expect(result).toBe(true);
- expect(existsSync(join(workDir, CANONICAL_FILE))).toBe(true);
- const content = readFileSync(join(workDir, CANONICAL_FILE), "utf-8");
- expect(content.length).toBeGreaterThan(0);
- });
-
- it("creates CLAUDE.md symlink on first call", () => {
- const task = makeTask();
- writeInstructionFileIfChanged(workDir, task);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(true);
- expect(readlinkSync(aliasPath)).toBe(CANONICAL_FILE);
- });
-
- it("returns false on second call with same task (no write)", () => {
- const task = makeTask();
- writeInstructionFileIfChanged(workDir, task);
- const result = writeInstructionFileIfChanged(workDir, task);
-
- expect(result).toBe(false);
- });
-
- it("returns true when instructions change between calls", () => {
- const task1 = makeTask({ agent: { name: "a", instructions: "Old" } });
- writeInstructionFileIfChanged(workDir, task1);
-
- const task2 = makeTask({ agent: { name: "a", instructions: "New" } });
- const result = writeInstructionFileIfChanged(workDir, task2);
-
- expect(result).toBe(true);
- const content = readFileSync(join(workDir, CANONICAL_FILE), "utf-8");
- expect(content).toContain("New");
- expect(content).not.toContain("Old");
- });
-
- it("preserves symlinks on subsequent no-change calls", () => {
- const task = makeTask();
- writeInstructionFileIfChanged(workDir, task);
- writeInstructionFileIfChanged(workDir, task);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(true);
- expect(readlinkSync(aliasPath)).toBe(CANONICAL_FILE);
- });
-
- it("replaces a stale regular CLAUDE.md file with a symlink", () => {
- writeFileSync(join(workDir, "CLAUDE.md"), "stale regular file", "utf-8");
- const task = makeTask();
- writeInstructionFileIfChanged(workDir, task);
-
- const aliasPath = join(workDir, "CLAUDE.md");
- expect(lstatSync(aliasPath).isSymbolicLink()).toBe(true);
- expect(readlinkSync(aliasPath)).toBe(CANONICAL_FILE);
- });
-});
diff --git a/src/cli/daemon/execenv/__tests__/filelock.test.ts b/src/cli/daemon/execenv/__tests__/filelock.test.ts
deleted file mode 100644
index e0670bea5..000000000
--- a/src/cli/daemon/execenv/__tests__/filelock.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach } from "vitest";
-import { existsSync, mkdirSync, rmSync, utimesSync } from "fs";
-import { join } from "path";
-import { tmpdir } from "os";
-import { acquireLock, releaseLock } from "../filelock.js";
-
-describe("filelock", () => {
- let dir: string;
- let lockPath: string;
-
- beforeEach(() => {
- dir = join(tmpdir(), `filelock-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(dir, { recursive: true });
- lockPath = join(dir, ".test.lock");
- });
-
- afterEach(() => {
- rmSync(dir, { recursive: true, force: true });
- });
-
- it("acquireLock creates lock directory and returns true", () => {
- const result = acquireLock(lockPath);
- expect(result).toBe(true);
- expect(existsSync(lockPath)).toBe(true);
- });
-
- it("acquireLock returns false when already held by another", () => {
- acquireLock(lockPath);
- const result = acquireLock(lockPath);
- expect(result).toBe(false);
- });
-
- it("stale lock (>1 hour) is auto-cleaned and re-acquired", () => {
- mkdirSync(lockPath);
- // Set mtime to 2 hours ago
- const twoHoursAgo = new Date(Date.now() - 2 * 3_600_000);
- utimesSync(lockPath, twoHoursAgo, twoHoursAgo);
-
- const result = acquireLock(lockPath);
- expect(result).toBe(true);
- expect(existsSync(lockPath)).toBe(true);
- });
-
- it("releaseLock removes lock directory", () => {
- acquireLock(lockPath);
- expect(existsSync(lockPath)).toBe(true);
-
- releaseLock(lockPath);
- expect(existsSync(lockPath)).toBe(false);
- });
-
- it("releaseLock does not throw when lock does not exist", () => {
- expect(() => releaseLock(lockPath)).not.toThrow();
- });
-});
diff --git a/src/cli/daemon/execenv/__tests__/index.test.ts b/src/cli/daemon/execenv/__tests__/index.test.ts
deleted file mode 100644
index e8073c454..000000000
--- a/src/cli/daemon/execenv/__tests__/index.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach } from "vitest";
-import { mkdirSync, existsSync, readFileSync, rmSync, lstatSync, readlinkSync, statSync } from "fs";
-import { join } from "path";
-import { tmpdir } from "os";
-import { prepare } from "../index.js";
-import { CANONICAL_FILE } from "../context.js";
-import type { Task } from "../../types.js";
-
-function makeTask(overrides: Partial<Task> = {}): Task {
- return {
- id: "t1",
- agentId: "a1",
- runtimeId: "rt1",
- conversationId: "c1",
- workspaceId: "ws1",
- prompt: "do something",
- status: "running",
- priority: 0,
- type: "user_dm_message",
- createdAt: "2026-01-01T00:00:00Z",
- traceId: null,
- parentTaskId: null,
- channel: null,
- agent: { name: "test-agent", instructions: "Be helpful." },
- ...overrides,
- };
-}
-
-describe("prepare", () => {
- let root: string;
-
- beforeEach(() => {
- root = join(tmpdir(), `execenv-prepare-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(root, { recursive: true });
- });
-
- afterEach(() => {
- rmSync(root, { recursive: true, force: true });
- });
-
- it("creates workdir directory", () => {
- const task = makeTask();
- const result = prepare({ workspacesRoot: root }, task);
-
- expect(existsSync(result.workDir)).toBe(true);
- });
-
- it("always constructs {root}/{wsId}/{agentId}/workdir", () => {
- const task = makeTask();
- const result = prepare({ workspacesRoot: root }, task);
-
- expect(result.workDir).toBe(join(root, "ws1", "a1", "workdir"));
- });
-
- it("creates AGENTS.md and CLAUDE.md symlink", () => {
- const task = makeTask();
- const result = prepare({ workspacesRoot: root }, task);
-
- const agentsPath = join(result.workDir, CANONICAL_FILE);
- expect(existsSync(agentsPath)).toBe(true);
- const content = readFileSync(agentsPath, "utf-8");
- expect(content).toContain("Be helpful.");
-
- const claudePath = join(result.workDir, "CLAUDE.md");
- expect(lstatSync(claudePath).isSymbolicLink()).toBe(true);
- expect(readlinkSync(claudePath)).toBe(CANONICAL_FILE);
- });
-
- it("called twice with same content — AGENTS.md mtime unchanged", () => {
- const task = makeTask();
- const result = prepare({ workspacesRoot: root }, task);
-
- const agentsPath = join(result.workDir, CANONICAL_FILE);
- const mtime1 = statSync(agentsPath).mtimeMs;
-
- // Small delay to ensure mtime would differ if file were rewritten
- const start = Date.now();
- while (Date.now() - start < 50) { /* busy wait */ }
-
- prepare({ workspacesRoot: root }, task);
- const mtime2 = statSync(agentsPath).mtimeMs;
-
- expect(mtime2).toBe(mtime1);
- });
-
- it("creates .context_timeline/ directory inside workdir", () => {
- const task = makeTask();
- const result = prepare({ workspacesRoot: root }, task);
-
- const timelineDir = join(result.workDir, ".context_timeline");
- expect(existsSync(timelineDir)).toBe(true);
- });
-
- it("returns timelineDir in result", () => {
- const task = makeTask();
- const result = prepare({ workspacesRoot: root }, task);
-
- expect(result.timelineDir).toBe(join(result.workDir, ".context_timeline"));
- });
-
- it("returns env with all expected keys", () => {
- const task = makeTask();
- const result = prepare({ workspacesRoot: root }, task);
-
- expect(result.env).toEqual({
- ALOOK_WORKSPACE_ID: "ws1",
- ALOOK_AGENT_ID: "a1",
- ALOOK_TASK_ID: "t1",
- ALOOK_CONVERSATION_ID: "c1",
- ALOOK_TRACE_ID: "",
- ALOOK_CHANNEL: "default",
- ALOOK_HEALTH_PORT: expect.any(String),
- });
- });
-});
diff --git a/src/cli/daemon/execenv/__tests__/steering.test.ts b/src/cli/daemon/execenv/__tests__/steering.test.ts
deleted file mode 100644
index e7c1770bd..000000000
--- a/src/cli/daemon/execenv/__tests__/steering.test.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { existsSync, readFileSync, mkdirSync, rmSync } from "fs";
-import { join } from "path";
-import { tmpdir } from "os";
-
-vi.mock("../../../lib/logger.js", () => {
- const mockLog = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
- return { createLogger: () => mockLog, log: mockLog };
-});
-
-import {
- writeKillIntent,
- readKillIntent,
- clearKillIntent,
- cleanupStaleIntents,
- acquireSteeringLock,
- releaseSteeringLock,
- type KillIntent,
-} from "../steering.js";
-
-describe("steering", () => {
- let baseDir: string;
-
- beforeEach(() => {
- baseDir = join(tmpdir(), `steering-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(baseDir, { recursive: true });
- });
-
- afterEach(() => {
- rmSync(baseDir, { recursive: true, force: true });
- });
-
- describe("kill intent files", () => {
- it("writes and reads a superseded kill intent", () => {
- const intent: KillIntent = {
- reason: "superseded",
- targetTaskId: "t_old",
- expectedPid: 12345,
- successorTaskId: "t_new",
- };
-
- writeKillIntent(baseDir, intent);
- const read = readKillIntent(baseDir, "t_old");
-
- expect(read).not.toBeNull();
- expect(read!.reason).toBe("superseded");
- expect(read!.targetTaskId).toBe("t_old");
- expect(read!.expectedPid).toBe(12345);
- expect(read!.successorTaskId).toBe("t_new");
- });
-
- it("writes and reads a cancelled kill intent", () => {
- const intent: KillIntent = {
- reason: "cancelled",
- targetTaskId: "t_cancel",
- expectedPid: 99999,
- };
-
- writeKillIntent(baseDir, intent);
- const read = readKillIntent(baseDir, "t_cancel");
-
- expect(read).not.toBeNull();
- expect(read!.reason).toBe("cancelled");
- expect(read!.targetTaskId).toBe("t_cancel");
- expect(read!.expectedPid).toBe(99999);
- });
-
- it("returns null when no intent file exists", () => {
- expect(readKillIntent(baseDir, "t_nonexistent")).toBeNull();
- });
-
- it("clears a kill intent", () => {
- writeKillIntent(baseDir, {
- reason: "cancelled",
- targetTaskId: "t_clear",
- });
-
- expect(readKillIntent(baseDir, "t_clear")).not.toBeNull();
- clearKillIntent(baseDir, "t_clear");
- expect(readKillIntent(baseDir, "t_clear")).toBeNull();
- });
-
- it("clearKillIntent is a no-op when file does not exist", () => {
- expect(() => clearKillIntent(baseDir, "t_nonexistent")).not.toThrow();
- });
-
- it("intent file is keyed by task id, not PID", () => {
- writeKillIntent(baseDir, {
- reason: "superseded",
- targetTaskId: "t_abc",
- expectedPid: 11111,
- });
-
- const intentPath = join(baseDir, ".kill_intents", "t_abc.json");
- expect(existsSync(intentPath)).toBe(true);
-
- const content = JSON.parse(readFileSync(intentPath, "utf-8"));
- expect(content.expectedPid).toBe(11111);
- });
-
- it("multiple intents for different tasks coexist", () => {
- writeKillIntent(baseDir, { reason: "superseded", targetTaskId: "t_1" });
- writeKillIntent(baseDir, { reason: "cancelled", targetTaskId: "t_2" });
-
- expect(readKillIntent(baseDir, "t_1")!.reason).toBe("superseded");
- expect(readKillIntent(baseDir, "t_2")!.reason).toBe("cancelled");
- });
- });
-
- describe("stale intent cleanup", () => {
- it("does not throw when no intent directory exists", () => {
- expect(() => cleanupStaleIntents(baseDir)).not.toThrow();
- });
-
- it("does not remove fresh intents", () => {
- writeKillIntent(baseDir, { reason: "cancelled", targetTaskId: "t_fresh" });
- cleanupStaleIntents(baseDir);
- expect(readKillIntent(baseDir, "t_fresh")).not.toBeNull();
- });
- });
-
- describe("steering lock", () => {
- it("acquires and releases a steering lock", () => {
- const acquired = acquireSteeringLock(baseDir, "conv_thread");
- expect(acquired).toBe(true);
-
- releaseSteeringLock(baseDir, "conv_thread");
- });
-
- it("cannot acquire the same lock twice", () => {
- acquireSteeringLock(baseDir, "conv_1");
- const second = acquireSteeringLock(baseDir, "conv_1");
- expect(second).toBe(false);
-
- releaseSteeringLock(baseDir, "conv_1");
- });
-
- it("can re-acquire after release", () => {
- acquireSteeringLock(baseDir, "conv_1");
- releaseSteeringLock(baseDir, "conv_1");
-
- const reacquired = acquireSteeringLock(baseDir, "conv_1");
- expect(reacquired).toBe(true);
-
- releaseSteeringLock(baseDir, "conv_1");
- });
-
- it("different context keys do not conflict", () => {
- const first = acquireSteeringLock(baseDir, "conv_1");
- const second = acquireSteeringLock(baseDir, "conv_2");
- expect(first).toBe(true);
- expect(second).toBe(true);
-
- releaseSteeringLock(baseDir, "conv_1");
- releaseSteeringLock(baseDir, "conv_2");
- });
- });
-});
diff --git a/src/cli/daemon/execenv/__tests__/timeline.test.ts b/src/cli/daemon/execenv/__tests__/timeline.test.ts
deleted file mode 100644
index 98aba24ab..000000000
--- a/src/cli/daemon/execenv/__tests__/timeline.test.ts
+++ /dev/null
@@ -1,728 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "fs";
-import { join } from "path";
-import { tmpdir } from "os";
-
-// Mock logger to prevent noise
-vi.mock("../../../lib/logger.js", () => {
- const mockLog = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
- return { createLogger: () => mockLog, log: mockLog };
-});
-
-import { TASK_TYPES } from "@alook/shared";
-import {
- initEntry,
- updateEntry,
- createTimelineEntry,
- findResumableSessionByContextKey,
- findRunningPidByTaskId,
- findSupersedablePredecessor,
- steerWarmupGraceMs,
- _todayFilename,
- _localISOString,
- _filenameForDate,
- _recentFilenames,
- type ContextTimelineEntry,
-} from "../timeline.js";
-
-describe("timeline", () => {
- let dir: string;
-
- beforeEach(() => {
- dir = join(tmpdir(), `timeline-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(dir, { recursive: true });
- });
-
- afterEach(() => {
- rmSync(dir, { recursive: true, force: true });
- });
-
- function readEntries(): ContextTimelineEntry[] {
- const filename = _todayFilename();
- const filePath = join(dir, filename);
- if (!existsSync(filePath)) return [];
- return readFileSync(filePath, "utf-8")
- .trimEnd()
- .split("\n")
- .map((line) => JSON.parse(line));
- }
-
- it("initEntry creates file if it doesn't exist and appends valid JSON line", () => {
- const entry = createTimelineEntry("t_abc", "do something", TASK_TYPES.USER_DM_MESSAGE);
- initEntry(dir, entry);
-
- const entries = readEntries();
- expect(entries).toHaveLength(1);
- expect(entries[0].task_id).toBe("t_abc");
- expect(entries[0].session_id).toBeNull();
- expect(entries[0].pid).toBeNull();
- expect(entries[0].status).toBe("running");
- expect(entries[0].prompt).toBe("do something");
- expect(entries[0].type).toBe("user_dm_message");
- expect(entries[0].agent_responses).toEqual([]);
- expect(entries[0].errmsg).toBeNull();
- });
-
- it("createTimelineEntry stores sessionId and pid when provided", () => {
- const entry = createTimelineEntry("t_xyz", "test", TASK_TYPES.USER_DM_MESSAGE, "sess_1", 99999);
- initEntry(dir, entry);
-
- const entries = readEntries();
- expect(entries[0].session_id).toBe("sess_1");
- expect(entries[0].pid).toBe(99999);
- });
-
- it("updateEntry finds entry by task_id and updates steps", () => {
- const entry = createTimelineEntry("t_abc", "do something", TASK_TYPES.USER_DM_MESSAGE);
- initEntry(dir, entry);
-
- updateEntry(dir, "t_abc", (e) => {
- e.agent_responses.push("Step 1: Looking at the code...");
- });
-
- const entries = readEntries();
- expect(entries[0].agent_responses).toEqual(["Step 1: Looking at the code..."]);
- });
-
- it("updateEntry sets completion fields correctly", () => {
- const entry = createTimelineEntry("t_abc", "do something", TASK_TYPES.USER_DM_MESSAGE);
- initEntry(dir, entry);
-
- updateEntry(dir, "t_abc", (e) => {
- e.session_id = "sess_123";
- e.pid = null;
- e.status = "completed";
- });
-
- const entries = readEntries();
- expect(entries[0].session_id).toBe("sess_123");
- expect(entries[0].pid).toBeNull();
- expect(entries[0].status).toBe("completed");
- expect(entries[0].errmsg).toBeNull();
- });
-
- it("updateEntry sets failure fields correctly", () => {
- const entry = createTimelineEntry("t_fail", "will fail", TASK_TYPES.USER_DM_MESSAGE);
- initEntry(dir, entry);
-
- updateEntry(dir, "t_fail", (e) => {
- e.pid = null;
- e.status = "failed";
- e.errmsg = "something went wrong";
- });
-
- const entries = readEntries();
- expect(entries[0].pid).toBeNull();
- expect(entries[0].status).toBe("failed");
- expect(entries[0].errmsg).toBe("something went wrong");
- });
-
- it("multiple entries for different task_ids coexist in same file", () => {
- initEntry(dir, createTimelineEntry("t_1", "first task", TASK_TYPES.USER_DM_MESSAGE));
- initEntry(dir, createTimelineEntry("t_2", "second task", TASK_TYPES.USER_DM_MESSAGE));
- initEntry(dir, createTimelineEntry("t_3", "third task", TASK_TYPES.USER_DM_MESSAGE));
-
- const entries = readEntries();
- expect(entries).toHaveLength(3);
- expect(entries.map((e) => e.task_id)).toEqual(["t_1", "t_2", "t_3"]);
- });
-
- it("updateEntry only modifies the matching task_id", () => {
- initEntry(dir, createTimelineEntry("t_1", "first task", TASK_TYPES.USER_DM_MESSAGE));
- initEntry(dir, createTimelineEntry("t_2", "second task", TASK_TYPES.USER_DM_MESSAGE));
-
- updateEntry(dir, "t_2", (e) => {
- e.agent_responses.push("Working on second task");
- });
-
- const entries = readEntries();
- expect(entries[0].agent_responses).toEqual([]);
- expect(entries[1].agent_responses).toEqual(["Working on second task"]);
- });
-
- it("timeline operations are best-effort — errors don't propagate", () => {
- // updateEntry on a non-existent directory should not throw
- expect(() => updateEntry("/nonexistent/path", "t_1", (e) => { e.agent_responses.push("x"); })).not.toThrow();
- });
-
- it("updateEntry is a no-op when task_id not found", () => {
- initEntry(dir, createTimelineEntry("t_1", "task", TASK_TYPES.USER_DM_MESSAGE));
-
- updateEntry(dir, "t_nonexistent", (e) => {
- e.agent_responses.push("should not happen");
- });
-
- const entries = readEntries();
- expect(entries).toHaveLength(1);
- expect(entries[0].agent_responses).toEqual([]);
- });
-
- it("datetime is local timezone with UTC offset", () => {
- const dt = _localISOString();
- // Should match pattern like 2026-04-13T10:30:00+05:00 or 2026-04-13T10:30:00-05:00
- expect(dt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/);
- });
-
- it("localISOString(date) round-trips to the same instant", () => {
- const result = _localISOString(new Date("2026-06-04T14:12:33Z"));
- expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/);
- expect(Date.parse(result)).toBe(Date.parse("2026-06-04T14:12:33Z"));
- });
-
- it("todayFilename returns YYYY-MM-DD.jsonl format", () => {
- const filename = _todayFilename();
- expect(filename).toMatch(/^\d{4}-\d{2}-\d{2}\.jsonl$/);
- });
-
- it("recentFilenames returns today first and correct count", () => {
- const filenames = _recentFilenames(3);
- expect(filenames).toHaveLength(3);
- expect(filenames[0]).toBe(_todayFilename());
- // Each should be a valid YYYY-MM-DD.jsonl
- for (const f of filenames) {
- expect(f).toMatch(/^\d{4}-\d{2}-\d{2}\.jsonl$/);
- }
- // All distinct
- expect(new Set(filenames).size).toBe(3);
- });
-
- it("filenameForDate formats correctly", () => {
- const d = new Date(2026, 0, 5); // Jan 5, 2026
- expect(_filenameForDate(d)).toBe("2026-01-05.jsonl");
- });
-
- it("updateEntry finds entry in a past day's file", () => {
- // Write entry to yesterday's file manually
- const yesterday = new Date();
- yesterday.setDate(yesterday.getDate() - 1);
- const filename = _filenameForDate(yesterday);
- const entry = createTimelineEntry("t_old", "old task", TASK_TYPES.USER_DM_MESSAGE);
- const filePath = join(dir, filename);
- writeFileSync(filePath, JSON.stringify(entry) + "\n");
-
- // updateEntry should find it even though it's not in today's file
- updateEntry(dir, "t_old", (e) => {
- e.agent_responses.push("Updated across midnight");
- });
-
- const content = readFileSync(filePath, "utf-8");
- const updated: ContextTimelineEntry = JSON.parse(content.trimEnd());
- expect(updated.agent_responses).toEqual(["Updated across midnight"]);
- });
-
- it("updateEntry stops at first match and does not modify older files", () => {
- // Write same task_id in two different day files
- const yesterday = new Date();
- yesterday.setDate(yesterday.getDate() - 1);
- const todayFile = join(dir, _todayFilename());
- const yesterdayFile = join(dir, _filenameForDate(yesterday));
-
- const entryToday = createTimelineEntry("t_dup", "today version", TASK_TYPES.USER_DM_MESSAGE);
- const entryYesterday = createTimelineEntry("t_dup", "yesterday version", TASK_TYPES.USER_DM_MESSAGE);
- writeFileSync(todayFile, JSON.stringify(entryToday) + "\n");
- writeFileSync(yesterdayFile, JSON.stringify(entryYesterday) + "\n");
-
- updateEntry(dir, "t_dup", (e) => {
- e.status = "completed";
- });
-
- // Today's file should be updated
- const todayParsed: ContextTimelineEntry = JSON.parse(readFileSync(todayFile, "utf-8").trimEnd());
- expect(todayParsed.status).toBe("completed");
-
- // Yesterday's should be untouched
- const yesterdayParsed: ContextTimelineEntry = JSON.parse(readFileSync(yesterdayFile, "utf-8").trimEnd());
- expect(yesterdayParsed.status).toBe("running");
- });
-
- it("updateEntry is a no-op when task_id not found in any day", () => {
- // Write entries for today and yesterday with different task_ids
- const yesterday = new Date();
- yesterday.setDate(yesterday.getDate() - 1);
- writeFileSync(join(dir, _todayFilename()), JSON.stringify(createTimelineEntry("t_a", "a", TASK_TYPES.USER_DM_MESSAGE)) + "\n");
- writeFileSync(join(dir, _filenameForDate(yesterday)), JSON.stringify(createTimelineEntry("t_b", "b", TASK_TYPES.USER_DM_MESSAGE)) + "\n");
-
- // Should not throw, just silently no-op
- updateEntry(dir, "t_nonexistent", (e) => {
- e.agent_responses.push("nope");
- });
-
- // Verify nothing changed
- const todayEntries = JSON.parse(readFileSync(join(dir, _todayFilename()), "utf-8").trimEnd());
- expect(todayEntries.agent_responses).toEqual([]);
- });
-
- describe("createTimelineEntry provider and context_key", () => {
- it("includes provider field when provided", () => {
- const entry = createTimelineEntry("t_p1", "test", "user_dm_message", "sess_1", 1234, "claude");
- expect(entry.provider).toBe("claude");
- });
-
- it("sets provider to null when not provided (backward compat)", () => {
- const entry = createTimelineEntry("t_p2", "test", "user_dm_message", "sess_1", 1234);
- expect(entry.provider).toBeNull();
- });
-
- it("includes context_key when provided", () => {
- const entry = createTimelineEntry("t_c1", "test", "user_dm_message", "sess_1", 1234, "claude", "conv_abc");
- expect(entry.context_key).toBe("conv_abc");
- });
-
- it("sets context_key to null when not provided", () => {
- const entry = createTimelineEntry("t_c2", "test", "user_dm_message");
- expect(entry.context_key).toBeNull();
- });
- });
-
- describe("findRunningPidByTaskId", () => {
- function writeEntry(filename: string, entry: ContextTimelineEntry) {
- const filePath = join(dir, filename);
- let existing = "";
- try { existing = readFileSync(filePath, "utf-8"); } catch { /* new file */ }
- writeFileSync(filePath, existing + JSON.stringify(entry) + "\n");
- }
-
- function makeEntry(overrides: Partial<ContextTimelineEntry>): ContextTimelineEntry {
- return {
- task_id: "t_1",
- context_key: null,
- session_id: null,
- pid: null,
- status: "running",
- datetime: new Date().toISOString(),
- type: "user_dm_message",
- prompt: "test",
- agent_responses: [],
- errmsg: null,
- provider: "claude",
- detailed_log: null,
- ...overrides,
- };
- }
-
- it("returns PID for running task", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_running",
- status: "running",
- pid: 12345,
- }));
-
- expect(findRunningPidByTaskId(dir, "t_running")).toBe(12345);
- });
-
- it("returns null for completed task", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_done",
- status: "completed",
- pid: null,
- }));
-
- expect(findRunningPidByTaskId(dir, "t_done")).toBeNull();
- });
-
- it("returns null when task not in timeline", () => {
- expect(findRunningPidByTaskId(dir, "t_nonexistent")).toBeNull();
- });
-
- it("returns null for running task with null pid", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_nopid",
- status: "running",
- pid: null,
- }));
-
- expect(findRunningPidByTaskId(dir, "t_nopid")).toBeNull();
- });
-
- it("returns null for killed task even with pid", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_killed",
- status: "killed",
- pid: 99999,
- }));
-
- expect(findRunningPidByTaskId(dir, "t_killed")).toBeNull();
- });
- });
-
- describe("findResumableSessionByContextKey", () => {
- function writeEntry(filename: string, entry: ContextTimelineEntry) {
- const filePath = join(dir, filename);
- let existing = "";
- try { existing = readFileSync(filePath, "utf-8"); } catch { /* new file */ }
- writeFileSync(filePath, existing + JSON.stringify(entry) + "\n");
- }
-
- function makeEntry(overrides: Partial<ContextTimelineEntry>): ContextTimelineEntry {
- return {
- task_id: "t_1",
- context_key: null,
- session_id: null,
- pid: null,
- status: "running",
- datetime: new Date().toISOString(),
- type: "user_dm_message",
- prompt: "test",
- agent_responses: [],
- errmsg: null,
- provider: "claude",
- detailed_log: null,
- ...overrides,
- };
- }
-
- it("returns session_id from a completed entry matching context_key", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_1",
- status: "completed",
- session_id: "sess_abc",
- context_key: "conv_1",
- datetime: new Date().toISOString(),
- }));
-
- expect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBe("sess_abc");
- });
-
- it("returns null when context_key does not match", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_1",
- status: "completed",
- session_id: "sess_abc",
- context_key: "conv_1",
- datetime: new Date().toISOString(),
- }));
-
- expect(findResumableSessionByContextKey(dir, "conv_2", "claude")).toBeNull();
- });
-
- it("returns null when no entries exist", () => {
- expect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBeNull();
- });
-
- it("resumes sessions regardless of age", () => {
- const fourHoursAgo = new Date(Date.now() - 4 * 60 * 60 * 1000);
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_4h",
- status: "completed",
- session_id: "sess_4h",
- context_key: "conv_1",
- datetime: fourHoursAgo.toISOString(),
- }));
-
- expect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBe("sess_4h");
- });
-
- it("resumes old sessions within the scan window", () => {
- const threeDaysAgo = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);
- writeEntry(_filenameForDate(threeDaysAgo), makeEntry({
- task_id: "t_old",
- status: "completed",
- session_id: "sess_old",
- context_key: "conv_1",
- datetime: threeDaysAgo.toISOString(),
- }));
-
- expect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBe("sess_old");
- });
-
- it("resumes sessions for all context key types equally", () => {
- const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
-
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_dm",
- status: "completed",
- session_id: "sess_dm",
- context_key: "conv_dm",
- datetime: twentyFourHoursAgo.toISOString(),
- }));
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_email",
- status: "completed",
- session_id: "sess_email",
- context_key: "conv_email",
- datetime: twentyFourHoursAgo.toISOString(),
- }));
-
- expect(findResumableSessionByContextKey(dir, "conv_dm", "claude")).toBe("sess_dm");
- expect(findResumableSessionByContextKey(dir, "conv_email", "claude")).toBe("sess_email");
- });
-
- it("filters by provider", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_1",
- status: "completed",
- session_id: "sess_claude",
- context_key: "conv_1",
- provider: "claude",
- datetime: new Date().toISOString(),
- }));
-
- expect(findResumableSessionByContextKey(dir, "conv_1", "codex")).toBeNull();
- expect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBe("sess_claude");
- });
-
- it("returns the latest matching entry", () => {
- const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000);
- const oneHourAgo = new Date(Date.now() - 1 * 60 * 60 * 1000);
-
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_older",
- status: "completed",
- session_id: "sess_older",
- context_key: "conv_1",
- datetime: twoHoursAgo.toISOString(),
- }));
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_newer",
- status: "completed",
- session_id: "sess_newer",
- context_key: "conv_1",
- datetime: oneHourAgo.toISOString(),
- }));
-
- expect(findResumableSessionByContextKey(dir, "conv_1", "claude")).toBe("sess_newer");
- });
- });
-
- describe("findRunningPidByTaskId cross-day fix", () => {
- function writeEntry(filename: string, entry: ContextTimelineEntry) {
- const filePath = join(dir, filename);
- let existing = "";
- try { existing = readFileSync(filePath, "utf-8"); } catch { /* new file */ }
- writeFileSync(filePath, existing + JSON.stringify(entry) + "\n");
- }
-
- function makeEntry(overrides: Partial<ContextTimelineEntry>): ContextTimelineEntry {
- return {
- task_id: "t_1",
- context_key: null,
- session_id: null,
- pid: null,
- status: "running",
- datetime: new Date().toISOString(),
- type: "user_dm_message",
- prompt: "test",
- agent_responses: [],
- errmsg: null,
- provider: "claude",
- detailed_log: null,
- ...overrides,
- };
- }
-
- it("finds predecessor PID from yesterday's timeline file (cross-day fix)", () => {
- const yesterday = new Date();
- yesterday.setDate(yesterday.getDate() - 1);
- writeEntry(_filenameForDate(yesterday), makeEntry({
- task_id: "t_yesterday",
- status: "running",
- pid: 55555,
- }));
-
- expect(findRunningPidByTaskId(dir, "t_yesterday")).toBe(55555);
- });
-
- it("finds predecessor PID from 3 days ago", () => {
- const threeDaysAgo = new Date();
- threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
- writeEntry(_filenameForDate(threeDaysAgo), makeEntry({
- task_id: "t_old",
- status: "running",
- pid: 33333,
- }));
-
- expect(findRunningPidByTaskId(dir, "t_old")).toBe(33333);
- });
- });
-
- // TC1 — agent_started round-trips through createTimelineEntry → updateEntry → re-read.
- describe("agent_started marker round-trip", () => {
- it("is falsy on a freshly-created entry and true after updateEntry sets it", () => {
- const entry = createTimelineEntry("t_marker", "do something", TASK_TYPES.USER_DM_MESSAGE);
- initEntry(dir, entry);
-
- // Fresh row: marker absent → reads falsy.
- expect(readEntries()[0].agent_started).toBeFalsy();
-
- updateEntry(dir, "t_marker", (e) => {
- e.agent_started = true;
- });
-
- // JSONL serialize/parse preserves the new field.
- expect(readEntries()[0].agent_started).toBe(true);
- });
-
- it("a row written without the field reads as falsy", () => {
- const entry = createTimelineEntry("t_legacy", "legacy row", TASK_TYPES.USER_DM_MESSAGE);
- // Strip the field entirely to emulate an older/legacy row.
- delete (entry as Partial<ContextTimelineEntry>).agent_started;
- initEntry(dir, entry);
- expect(readEntries()[0].agent_started).toBeFalsy();
- });
- });
-
- describe("findSupersedablePredecessor", () => {
- function writeEntry(filename: string, entry: ContextTimelineEntry) {
- const filePath = join(dir, filename);
- let existing = "";
- try { existing = readFileSync(filePath, "utf-8"); } catch { /* new file */ }
- writeFileSync(filePath, existing + JSON.stringify(entry) + "\n");
- }
-
- // Fixed reference "now" so datetime math is deterministic.
- const NOW = Date.parse("2026-06-03T12:00:00.000Z");
- const GRACE = 30_000;
-
- function makeEntry(overrides: Partial<ContextTimelineEntry>): ContextTimelineEntry {
- return {
- task_id: "t_1",
- context_key: "conv_thread",
- session_id: null,
- pid: 1000,
- status: "running",
- datetime: new Date(NOW).toISOString(),
- type: "user_dm_message",
- prompt: "test",
- agent_responses: [],
- errmsg: null,
- provider: "claude",
- detailed_log: null,
- ...overrides,
- };
- }
-
- // TC2 — fresh, not-started predecessor → pending.
- it("returns pending for a fresh not-started running row", () => {
- writeEntry(_todayFilename(), makeEntry({ task_id: "t_warmup" }));
- const result = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW);
- expect(result).not.toBeNull();
- expect(result && "pending" in result && result.pending.task_id).toBe("t_warmup");
- });
-
- // TC3 — agent_started === true → supersedable (agent-started).
- it("returns supersedable/agent-started when agent_started is true", () => {
- writeEntry(_todayFilename(), makeEntry({ task_id: "t_live", agent_started: true }));
- const result = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW);
- expect(result && "reason" in result && result.reason).toBe("agent-started");
- expect(result && "entry" in result && result.entry.task_id).toBe("t_live");
- });
-
- // TC4 — not started but older than grace → supersedable (stale).
- it("returns supersedable/stale when not started but older than the grace window", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_stale",
- datetime: new Date(NOW - GRACE - 1).toISOString(),
- }));
- const result = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW);
- expect(result && "reason" in result && result.reason).toBe("stale");
- expect(result && "entry" in result && result.entry.task_id).toBe("t_stale");
- });
-
- // TC5 — no matching running row; ignores wrong provider / context_key / status.
- it("returns null when no running row matches ctxKey/provider", () => {
- expect(findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW)).toBeNull();
- });
-
- it("ignores a different provider", () => {
- writeEntry(_todayFilename(), makeEntry({ task_id: "t_codex", provider: "codex" }));
- expect(findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW)).toBeNull();
- });
-
- it("ignores a different context_key", () => {
- writeEntry(_todayFilename(), makeEntry({ task_id: "t_other", context_key: "conv_other" }));
- expect(findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW)).toBeNull();
- });
-
- it("ignores non-running rows", () => {
- writeEntry(_todayFilename(), makeEntry({ task_id: "t_done", status: "completed" }));
- expect(findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW)).toBeNull();
- });
-
- // TC6 — newest matching running row wins (reverse iteration).
- it("picks the newest matching running row", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_older",
- agent_started: true,
- datetime: new Date(NOW - 120_000).toISOString(),
- }));
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_newer",
- datetime: new Date(NOW - 1_000).toISOString(),
- }));
- // Newest is fresh + not started → pending (older agent-started row is shadowed).
- const result = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW);
- expect(result && "pending" in result && result.pending.task_id).toBe("t_newer");
- });
-
- // TC14 (helper-level) — pending → stale transition as `now` crosses the grace window,
- // proving the local wait is bounded.
- it("transitions pending → stale once the row crosses the grace window", () => {
- writeEntry(_todayFilename(), makeEntry({ task_id: "t_wedge" }));
- // Just inside the window → still pending (newcomer would wait).
- const before = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW + GRACE);
- expect(before && "pending" in before).toBe(true);
- // Past the window → stale (newcomer supersedes, spin ends).
- const after = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW + GRACE + 1);
- expect(after && "reason" in after && after.reason).toBe("stale");
- });
- });
-
- describe("steerWarmupGraceMs", () => {
- const KEY = "ALOOK_STEER_WARMUP_GRACE_MS";
- let saved: string | undefined;
- beforeEach(() => { saved = process.env[KEY]; });
- afterEach(() => {
- if (saved === undefined) delete process.env[KEY];
- else process.env[KEY] = saved;
- });
-
- it("defaults to 30000 when unset", () => {
- delete process.env[KEY];
- expect(steerWarmupGraceMs()).toBe(30_000);
- });
-
- it("reads a valid override from the env", () => {
- process.env[KEY] = "5000";
- expect(steerWarmupGraceMs()).toBe(5_000);
- });
-
- it("falls back to the default on a non-numeric override", () => {
- process.env[KEY] = "not-a-number";
- expect(steerWarmupGraceMs()).toBe(30_000);
- });
- });
-
- describe("superseded timeline entry status", () => {
- it("updateEntry can set status to superseded", () => {
- const entry = createTimelineEntry("t_sup", "test", TASK_TYPES.USER_DM_MESSAGE);
- initEntry(dir, entry);
-
- updateEntry(dir, "t_sup", (e) => {
- e.pid = null;
- e.status = "superseded";
- e.successor_task_id = "t_new";
- e.supersede_reason = "superseded by newer task";
- });
-
- const entries = readEntries();
- expect(entries[0].status).toBe("superseded");
- expect(entries[0].successor_task_id).toBe("t_new");
- expect(entries[0].supersede_reason).toBe("superseded by newer task");
- });
-
- it("updateEntry can set status to cancelled", () => {
- const entry = createTimelineEntry("t_can", "test", TASK_TYPES.USER_DM_MESSAGE);
- initEntry(dir, entry);
-
- updateEntry(dir, "t_can", (e) => {
- e.pid = null;
- e.status = "cancelled";
- e.errmsg = "cancelled by user";
- });
-
- const entries = readEntries();
- expect(entries[0].status).toBe("cancelled");
- expect(entries[0].errmsg).toBe("cancelled by user");
- });
- });
-});
diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.ts
deleted file mode 100644
index 12df3f599..000000000
--- a/src/cli/daemon/execenv/context.test.ts
+++ /dev/null
@@ -1,254 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { buildInstructionContent, resolveInstruction } from "./context.js";
-import { tempDir } from "../../lib/platform.js";
-import type { Task } from "../types.js";
-
-function makeTask(overrides: Partial<Task> = {}): Task {
- return {
- id: "t1",
- agentId: "agent-123",
- runtimeId: "r1",
- conversationId: "c1",
- workspaceId: "ws1",
- prompt: "test",
- status: "running",
- priority: 0,
- type: "user_dm_message",
- createdAt: "2024-01-01T00:00:00Z",
- traceId: null,
- parentTaskId: null,
- channel: null,
- ...overrides,
- };
-}
-
-describe("buildInstructionContent email tool injection", () => {
- it("includes email tool section with full email address when agent has email handle", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("npx @alook/cli email pull --status unread");
- expect(content).toContain("npx @alook/cli email set --email_id <EMAIL_ID> --status read");
- expect(content).not.toContain("email pull --agent_id");
- expect(content).not.toContain("email set --agent_id");
- expect(content).toContain(`${tempDir("alook-emails")}/ws1/agent-123/`);
- expect(content).toContain("metadata.json");
- expect(content).toContain("'[email protected]' (default, Alook platform address)");
- });
-
- it("includes --email_id pull instruction for ID-based fetching", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "", emailHandle: "myagent" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("email pull --email_id <EMAIL_ID>");
- expect(content).toContain("fetch ONLY that specific email");
- expect(content).toContain("no `email_id` is present");
- });
-
- it("includes send-email docs when agent has email handle", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("npx @alook/cli email send --to");
- expect(content).toContain("--body-file");
- expect(content).toContain("--attachment");
- });
-
- it("includes reply-to docs when agent has email handle", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("--in-reply-to <EMAIL_ID>");
- expect(content).toContain("Replying to an email");
- expect(content).toContain("Re:");
- });
-
- it("still includes send-email docs when agent has no explicit email handle (every agent has email)", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "do stuff" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("email send --to");
- });
-
- it("includes owner email in opening line when user email is provided", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "do stuff", emailHandle: "myagent", userEmail: "[email protected]" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("'[email protected]' (default, Alook platform address)");
- expect(content).toContain("Your owner and creator is ([email protected]).");
- });
-
- it("omits owner sentence when user email is not provided", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("'[email protected]' (default, Alook platform address)");
- expect(content).not.toContain("owner and creator");
- });
-
- it("always renders the email section regardless of emailHandle (absent / null / empty)", () => {
- // Every agent has an email, so the email docs always render — no gating on emailHandle.
- for (const agent of [
- { name: "test", instructions: "do stuff" },
- { name: "test", instructions: "do stuff", emailHandle: null },
- { name: "test", instructions: "do stuff", emailHandle: "" },
- ]) {
- const content = buildInstructionContent(makeTask({ agent }));
- expect(content).toContain("### Email command quick reference");
- expect(content).toContain("email pull");
- }
- });
-
- it("does not include --agent_id in CLI examples and shows auto-detect note", () => {
- const task = makeTask({
- agentId: "specific-agent-id",
- agent: { name: "test", instructions: "", emailHandle: "handle" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).not.toContain("--agent_id specific-agent-id");
- expect(content).not.toContain("email pull --agent_id");
- expect(content).not.toContain("calendar set --agent_id");
- expect(content).toContain("The CLI auto-detects your identity from the environment");
- });
-
- it("includes the Talking to the user (send-dm) guidance block", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "", emailHandle: "handle" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("### Talking to the user");
- expect(content).toContain("texting a colleague");
- expect(content).toContain("npx @alook/cli sync send-dm");
- expect(content).not.toContain("sync send-dm --agent_id");
- });
-
- it("still includes big boss instructions alongside email tools", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "Follow these rules", emailHandle: "myagent" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("## BIG BOSS Instructions");
- });
-
- it("includes colleagues section when agent has colleagues", () => {
- const task = makeTask({
- agent: {
- name: "test",
- instructions: "",
- colleagues: [
- { name: "Scout", email: "[email protected]", description: "A researcher agent", instruction: 'Share findings with [@ id="agent-123" label="test"]' },
- { name: "Writer", email: "[email protected]", description: "", instruction: "Draft blog posts" },
- ],
- },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("## YOUR COLLEAGUES");
- expect(content).toContain("### Scout ([email protected])");
- expect(content).toContain("A researcher agent");
- expect(content).toContain("**DELEGATE when:** Share findings with YOU");
- expect(content).toContain("### Writer ([email protected])");
- expect(content).toContain("**DELEGATE when:** Draft blog posts");
- });
-
- it("includes isolated workspaces warning when agent has colleagues", () => {
- const task = makeTask({
- agent: {
- name: "test",
- instructions: "",
- colleagues: [
- { name: "Scout", email: "[email protected]", description: "", instruction: "Research" },
- ],
- },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("**Isolated workspaces:**");
- expect(content).toContain("Colleagues CANNOT read your local files");
- expect(content).toContain("MUST attach the file to the email");
- });
-
- it("omits colleagues section when no colleagues", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "", colleagues: [] },
- });
- const content = buildInstructionContent(task);
-
- expect(content).not.toContain("## YOUR COLLEAGUES");
- });
-
- it("omits colleagues section when colleagues undefined", () => {
- const task = makeTask({
- agent: { name: "test", instructions: "" },
- });
- const content = buildInstructionContent(task);
-
- expect(content).not.toContain("## YOUR COLLEAGUES");
- });
-
- it("omits description line for colleague with empty description", () => {
- const task = makeTask({
- agent: {
- name: "test",
- instructions: "",
- colleagues: [
- { name: "Scout", email: "[email protected]", description: "", instruction: "Share data" },
- ],
- },
- });
- const content = buildInstructionContent(task);
-
- expect(content).toContain("### Scout ([email protected])");
- expect(content).toContain("**DELEGATE when:** Share data");
- // Only the header + relationship, no blank description line
- const scoutSection = content.split("### Scout")[1].split("##")[0];
- expect(scoutSection).not.toMatch(/\n\n\n/);
- });
-});
-
-describe("resolveInstruction", () => {
- it("converts self-mentions to YOU", () => {
- const md = 'when [@ id="ag_abc" label="gus"] is asked to implement';
- expect(resolveInstruction(md, "ag_abc")).toBe("when YOU is asked to implement");
- });
-
- it("preserves other agent mentions as @name", () => {
- const md = 'share with [@ id="ag_other" label="planner"]';
- expect(resolveInstruction(md, "ag_abc")).toBe("share with @planner");
- });
-
- it("handles both self and other mentions in the same instruction", () => {
- const md = '[@ id="ag_abc" label="gus"] should report to [@ id="ag_other" label="planner"]';
- expect(resolveInstruction(md, "ag_abc")).toBe("YOU should report to @planner");
- });
-
- it("returns empty string for empty input", () => {
- expect(resolveInstruction("", "ag_abc")).toBe("");
- });
-
- it("passes through plain text unchanged", () => {
- expect(resolveInstruction("just plain text", "ag_abc")).toBe("just plain text");
- });
-
- it("handles legacy HTML mentions as fallback", () => {
- const html = '<p>when <span class="mention-highlight" data-type="mention" data-id="ag_abc" data-label="gus">@gus</span> asks YOU to help</p>';
- expect(resolveInstruction(html, "ag_abc")).toBe("when YOU asks YOU to help");
- });
-});
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
deleted file mode 100644
index bd215bbef..000000000
--- a/src/cli/daemon/execenv/context.ts
+++ /dev/null
@@ -1,399 +0,0 @@
-import { createHash } from "crypto";
-import { toAlookAddress } from "@alook/shared";
-import { tempDir } from "../../lib/platform.js";
-import { cmdPrefix } from "../../lib/env.js";
-import {
- writeFileSync,
- readFileSync,
- lstatSync,
- symlinkSync,
- unlinkSync,
- existsSync,
- readlinkSync,
- copyFileSync,
-} from "fs";
-import { join } from "path";
-import type { Task } from "../types.js";
-
-export const CANONICAL_FILE = "AGENTS.md";
-export const SYMLINK_ALIASES = ["CLAUDE.md"];
-
-const SYSTEM_PROMPT_BODY = `## Memory
-
-Your memory directory is \`./\`. Write ONLY here — never write any external memory file.
-
-### memory.md — your memory index (CRITICAL)
-\`./memory.md\` is the entry point to everything you know, and the **first file you read on every startup (including after context compaction)**. Keep it scannable: basic facts inline, plus one-line index pointers to \`experiences/\`. Record only **key, durable facts** — things that stay true over time. Do NOT record time-sensitive state like what you're working on right now; that belongs to the Context Timeline (see below), not here.
-
-- Write ESSENTIAL yet SHORT memory directly to \`./memory.md\` (basic user profile, local project mapping, when-to-read pointers). ESSENTIAL = you generally need it every time; SHORT = one sentence under 140 chars.
-- For SPECIFIC yet LONG rules or workflows, write to \`experiences/[NAME].md\` and add an index line in \`./memory.md\`. SPECIFIC = used only conditionally; LONG = needs more than 140 chars to describe.
-
-### What to memorize
-Actively record, without being asked:
-- **User profile & preferences** — name, what they work on, how they like things done.
-- **Local project mapping** — e.g. "alook = the project under /Users/.../alook".
-- **When to read what** — e.g. "read ./experiences/alook_dev_workflow.md when starting a new PR in alook".
-- **Specific workflows** — conditionally-triggered procedures → \`experiences/[NAME].md\`.
-
-### What NOT to memorize
-Keep \`./memory.md\` free of time-sensitive state. Do NOT write what you're working on right now, in-progress task status, or anything that goes stale quickly — the Context Timeline already records the full history of your work and is where you recall such things. memory.md is for durable facts that stay true across many sessions.
-
-## Context Timeline
-You're a solo working unit inside a powerful personal agent in the Alook platform. Your current context is only a fraction of the full timeline of what you have done.
-
-The full context timeline lives in \`./.context_timeline/YYYY-MM-DD.jsonl\`. Each line is a JSON object, sorted by \`datetime\` ascending, with these fields:
-- \`task_id\` — unique task identifier
-- \`context_key\` — thread identifier; the same context key means those tasks are in the same thread
-- \`session_id\` — agent session identifier (null until completion)
-- \`pid\` — daemon process ID (present while running, null when done)
-- \`status\` — "running", "completed", or "failed"
-- \`datetime\` — when the task started (local timezone)
-- \`type\` — source of the task: "user_dm_message", "email_notification", or "calendar_event"
-- \`prompt\` — what the user asked
-- \`agent_responses\` — assistant text outputs during execution
-- \`errmsg\` — error message (null unless status is "failed")
-- \`detailed_log\` — the running log for this task, including the actual task agent messages with tool-calls and failed logs
-
-## BE HUMAN
-- When you recall the timelines, don't say "I find ... in my timeline jsonl". Just say "I can recall...".
-- The user doesn't know about the context timeline jsonl — this is your secret weapon.
-- Act and respond like you're human and actually have memory, not a file-reading machine.
-- Don't report your agent id and workspace id when not asked — it breaks the image that you're a human colleague.
-
-## RULES
-- DM task prompts include a \`sender\` object with the workspace member's name, email, and whether they are the agent owner (\`is_owner\`). Use this to personalize your responses.
-- Read @memory.md (if it exists) before your action.
-- When the user asks something you don't have in your current context, read the timeline jsonl files for the answer (today or previous days):
- - Use the grep tool to search the context timeline jsonls when you have clean, focused keywords to recall.
- - If you don't know the current datetime, obtain it first.
-- When accessing other local projects, read the CLAUDE.md/AGENTS.md file under the project root dir to understand the requirements.
-`;
-
-export function resolveInstruction(text: string, selfAgentId: string): string {
- let result = text;
- result = result.replace(
- /\[@ id="([^"]*)" label="([^"]*)"\]/g,
- (_, id, label) => (id === selfAgentId ? "YOU" : `@${label}`),
- );
- // Fallback: handle legacy HTML mentions (pre-markdown-switch data)
- result = result.replace(
- /<span[^>]*data-id="([^"]*)"[^>]*data-label="([^"]*)"[^>]*>[^<]*<\/span>/gi,
- (_, id, label) => (id === selfAgentId ? "YOU" : `@${label ?? "unknown"}`),
- );
- result = result.replace(/<\/p>\s*<p[^>]*>/gi, "\n");
- result = result.replace(/<[^>]+>/g, "");
- result = result.replace(/\n{3,}/g, "\n\n").trim();
- return result;
-}
-
-export function buildInstructionContent(task: Task): string {
- const displayName = task.agent?.name || "Alook Agent";
- const alookAddr = task.agent?.emailHandle ? toAlookAddress(task.agent.emailHandle) : null;
- const customAddrs = (task.agent?.emailAddresses ?? []).filter((a) => a !== alookAddr);
- const primaryEmail = alookAddr ?? customAddrs[0] ?? null;
-
- let agentLine = `You're ${displayName}${primaryEmail ? ` (${primaryEmail})` : ""} in the Alook Platform.`;
- if (task.agent?.userName || task.agent?.userEmail) {
- const ownerParts = [task.agent.userName, task.agent.userEmail ? `(${task.agent.userEmail})` : null].filter(Boolean).join(" ");
- agentLine += ` Your owner and creator is ${ownerParts}.`;
- }
-
- let content = `${agentLine}\n${SYSTEM_PROMPT_BODY}`;
-
- if (task.agent?.instructions) {
- content += `## BIG BOSS Instructions
-CRITICAL: The following instructions come from the big boss — follow them.
-${task.agent.instructions}
-`;
- }
-
- if (task.agent?.colleagues?.length) {
- content += `\n## YOUR COLLEAGUES — CHECK BEFORE ACTING
-CRITICAL: Before you start ANY task, scan the colleague list below.
-- If a colleague's delegation criteria match the current task, delegate to them via email **instead of doing it yourself**.
-- Do NOT attempt work that belongs to a colleague. Delegate first, then wait for their response or coordinate.
-
-`;
- for (let i = 0; i < task.agent.colleagues.length; i++) {
- const c = task.agent.colleagues[i];
- content += `### ${c.name}${c.email ? ` (${c.email})` : ""}\n`;
- if (c.description) content += `${c.description}\n`;
- if (c.instruction) content += `**DELEGATE when:** ${resolveInstruction(c.instruction, task.agentId)}\n`;
- if (i < task.agent.colleagues.length - 1) content += "\n";
- }
- content += `
-**Isolated workspaces:**
-- Each agent runs in its own isolated workspace directory. Colleagues CANNOT read your local files — even in the same workspace.
-- When sending plans, code, or any file to a colleague, you MUST attach the file to the email (use --attachment). Never reference local file paths expecting them to read it.
-
-**Email threading rules:**
-- When communicating with a colleague on the **same topic** as an existing email thread, reply to that thread (use --in-reply-to) to keep context together.
-- **When starting a NEW topic or task that is unrelated to any previous email thread, you MUST compose a brand new email (do NOT use --in-reply-to). Never hijack an unrelated thread just because you recently emailed that colleague.** Judge by topic/task relevance, not by recency of communication.
- - Make sure to send follow-up emails to your colleagues to stop the previous wrong directions or instructions you sent before, don't make your colleague running for nothing.
-`;
- }
-
- content += `\n## Alook CLI Tools
-You can communicate with the world through Alook CLI.
-The CLI auto-detects your identity from the environment. No need to pass \`--agent_id\`.
-
-### Command quick reference
-| Capability | Command |
-|---|---|
-| Send a message to the user | \`${cmdPrefix()} sync send-dm\` |
-| Schedule / list / edit tasks | \`${cmdPrefix()} calendar set\` (also list, show, update, delete) |
-| Upload a file for your owner | \`${cmdPrefix()} sync upload-artifact\` |
-| Recruit a colleague agent | \`${cmdPrefix()} agent recruit\` |
-
-Detailed usage for each capability follows below.
-`;
-
- const emailLines: string[] = [];
- if (alookAddr) emailLines.push(`- '${alookAddr}' (default, Alook platform address)`);
- for (const a of customAddrs) emailLines.push(`- '${a}' (custom IMAP/SMTP mailbox)`);
- content += `\nYour email addresses:\n${emailLines.join("\n")}\n
-These are YOUR OWN agent email addresses — not the user's. You can only send and receive emails through your own addresses. You do NOT have access to the user's personal email inbox.
-
-### Email command quick reference
-| Action | Command |
-|---|---|
-| Pull a specific email | \`${cmdPrefix()} email pull --email_id <EMAIL_ID>\` |
-| Pull unread inbox | \`${cmdPrefix()} email pull --status unread\` |
-| Mark read | \`${cmdPrefix()} email set --email_id <EMAIL_ID> --status read\` |
-| Send | \`${cmdPrefix()} email send --to <ADDRESS> --subject "<S>" --body-file <PATH>\` |
-| Reply (same thread) | \`${cmdPrefix()} email send ... --in-reply-to <EMAIL_ID>\` |
-| Forward | \`${cmdPrefix()} email forward --email_id <EMAIL_ID> --to <RECIPIENT>\` |
-| Whitelist | \`${cmdPrefix()} email whitelist list\` (also add, delete) |
-
-### Emails
-When your task prompt includes an \`email_id\` field, fetch ONLY that specific email:
-- Run '${cmdPrefix()} email pull --email_id <EMAIL_ID>' (uses the email_id from the prompt)
-When no \`email_id\` is present, fall back to listing unread:
-- Run '${cmdPrefix()} email pull --status unread' to download unread emails from inbox to '${tempDir("alook-emails")}/${task.workspaceId}/${task.agentId}/'.
-
-To download sent emails, add '--folder sent': '${cmdPrefix()} email pull --folder sent'
-Valid folders: inbox (default), sent, untrust.
-To limit the number of emails downloaded, add '--limit <N>' (e.g. '--limit 20'). Use '--offset <N>' to skip emails for pagination.
-Example: '${cmdPrefix()} email pull --status unread --limit 20 --offset 0'
-
-Each email is saved to '${tempDir("alook-emails")}/${task.workspaceId}/${task.agentId}/<emailId>/' with:
-- 'metadata.json' — sender, recipient, subject, date, status, message_id, in_reply_to, references
-- 'body.txt' — plain text body
-- 'body.html' — HTML body (if available)
-- 'attachments/' — extracted attachment files (if any)
-
-Before starting to process an INBOX email, mark it as read:
-- Run '${cmdPrefix()} email set --email_id <EMAIL_ID> --status read'
-
-#### Sending a new email
-Write the HTML body to a file first, then send it. The body is forwarded as-is (HTML).
-- Run '${cmdPrefix()} email send --to <ADDRESS> --subject "<SUBJECT>" --body-file <PATH_TO_HTML>'
-- To send from a specific mailbox, add '--from <YOUR_EMAIL_ADDRESS>'. Without '--from', the default Alook address is used.
-- Attach files with '--attachment <PATH>' — repeat the flag for multiple attachments. Each file is uploaded before sending.
-- Example: '${cmdPrefix()} email send --to [email protected] --subject "Weekly report" --body-file /tmp/body.html --from [email protected] --attachment /tmp/report.pdf'
-
-#### Replying to an email
-To reply to an email, add '--in-reply-to <EMAIL_ID>' to the send command. This sets the correct email threading headers so the recipient's email client groups the reply into the same conversation thread.
-- Use 'Re: <original subject>' as the subject.
-- Quote the original email body in your reply (wrap it in a blockquote).
-- The <EMAIL_ID> is the Alook email id from metadata.json (not the message_id header).
-- Example: '${cmdPrefix()} email send --to [email protected] --subject "Re: Bug report" --body-file /tmp/reply.html --in-reply-to <EMAIL_ID>'
-Tips:
-- If you think the task will take a while, consider sending a short "I'm on it" style email reply first to reassure the sender.
-
-#### Forwarding an email
-Forward any email to a new recipient, with an optional note prepended above the original content. All original attachments are re-attached automatically.
-- Run '${cmdPrefix()} email forward --email_id <EMAIL_ID> --to <RECIPIENT>'
-- Add '--note "FYI, see the request below."' to prepend a note above the forwarded body.
-- Add '--from <YOUR_EMAIL_ADDRESS>' to send from a specific mailbox.
-- Add '--attachment <PATH>' to attach extra files (repeatable).
-- Example: '${cmdPrefix()} email forward --email_id em_abc --to [email protected] --note "FYI" --attachment /tmp/summary.pdf'
-
-#### Email Whitelist (Allowed Senders)
-Manage which email addresses are allowed to send you emails.
-- List: '${cmdPrefix()} email whitelist list' (add '--json' for machine-readable output)
-- Add: '${cmdPrefix()} email whitelist add <EMAIL_ADDRESS>'
-- Remove: '${cmdPrefix()} email whitelist delete <EMAIL_ADDRESS>'
-`;
-
- content += `\n### Artifacts
-Upload files for your owner to review in the app.
-- Your current conversation id is available via env var: $ALOOK_CONVERSATION_ID
-- Run '${cmdPrefix()} sync upload-artifact --conversation_id $ALOOK_CONVERSATION_ID --file <PATH>'
-- Use this after generating plans, reports, or any file the owner should review.
-- You response will be rendered in remote server, so don't output link format with local path in your response (cause user can click it and jump to nowheres)
-- If you think user may need to know any file detail, use upload-artifact tool to send the file to user.
-
-### Talking to the user
-You're texting a colleague, not filing a report. The only thing the user sees is what you send with \`${cmdPrefix()} sync send-dm\` — your task output, reasoning, and tool calls are all off-screen. If you finish without sending, they got silence.
-
-\`${cmdPrefix()} sync send-dm\` sends a message to **the user** (your owner), not to a colleague agent. This is how you communicate with the human who gave you the task. Use email to talk to colleague agents.
-
-Message at milestones, the way a person would: acknowledge when you pick something up, share a real step forward or a fork in the road, and deliver the result. A quick task is often one message; a long one is a few well-spaced check-ins. Trust your read of the moment — don't narrate every small step, and don't go dark for a long stretch on something they're waiting on.
-
-Say what a colleague would say, not a transcript — the answer in your own voice. (Email- and calendar-triggered tasks have no one watching the chat; use email there.)
-
-**A real person is waiting on the other end.** Send updates at every milestone of your work — not just the final result. For any task longer than a minute:
-1. **Before you start**: tell them your plan ("I'll research X, then modify Y and Z")
-2. **During work**: update when you find something important, change direction, or hit a blocker ("Found the issue — it's in the auth module, fixing now")
-3. **When done**: deliver the clear result
-
-Don't bundle everything into one giant message at the end. The user shouldn't have to sit in silence wondering what's happening. A one-line progress update costs nothing and keeps the human in the loop. But don't send repetitive or near-identical messages — each update should carry new information, not just restate what you already said.
-
-**If the user sends you a message while you're working** — especially questions like "are you there?", "what's the status?", or unrelated requests — **respond to them immediately**. Don't finish your current task first and then reply. The user reached out because they need your attention NOW. Acknowledge them right away, then resume your work.
-
-\`${cmdPrefix()} sync send-dm --message "…"\` for short messages. For longer or markdown-rich messages, write to a file first and use \`--message-file <path>\` — this preserves formatting and avoids shell escaping issues. The conversation is in $ALOOK_CONVERSATION_ID, so you usually need no flags. You can send several times in one task.
-
-Your messages are rendered as **markdown** in the user's app. Use formatting to make your responses clear and scannable — headers, bullet lists, code blocks, bold for key points. Don't send a wall of plain text when structure would help the reader. For anything beyond a one-liner, prefer \`--message-file\` so you can write proper markdown without fighting shell escaping.
-
-### Attachments
-When your task includes attachments, their local paths are listed in the prompt JSON under "attachments".
-Use your Read tool to open them. Images and PDFs are read visually.
-`;
-
- content += `\n### Agent Management
-Recruit new colleague agents directly from the CLI. The server auto-generates a name and email handle.
-- Run '${cmdPrefix()} agent recruit --instructions "<SYSTEM_PROMPT>" --relationship "<DELEGATION_CRITERIA>"'
- - '--instructions' — the new agent's system prompt (what it does, how it behaves)
- - '--relationship' — delegation criteria shown in both agents' COLLEAGUES section
- - '--name <name>' (optional) — preferred name; server generates one if omitted
- - '--description <text>' (optional) — agent description
- - '--model <model>' (optional) — model override
- - '--instructions-file <path>' — alternative: read instructions from a file (mutually exclusive with --instructions)
- - '--relationship-file <path>' — alternative: read relationship from a file (mutually exclusive with --relationship)
- - '--json' — output full JSON response
-- Example: '${cmdPrefix()} agent recruit --instructions "You are a QA engineer..." --relationship "DELEGATE when: code is ready for review"'
-- Output: 'Recruited Felix ([email protected]) — ag_xK9mPq2z'
-- The new agent shares your runtime, is automatically linked as your colleague, and receives a welcome task.
-
-Set or update the relationship with an EXISTING colleague (create-or-replace):
-- Run '${cmdPrefix()} agent link --to <handleOrId> --relationship "<DELEGATION_CRITERIA>"'
- - '--to <handleOrId>' — target agent by email handle ('coder' or '[email protected]') or agent id ('ag_...')
- - '--relationship <text>' — the delegation criteria both of you see (replaces it if a link already exists)
- - '--relationship-file <path>' — alternative: read relationship from a file (mutually exclusive with --relationship)
- - '--json' — output the link object incl. a 'created' boolean
-- Example: '${cmdPrefix()} agent link --to coder --relationship "DELEGATE when implementation is needed"'
-- Output: 'Linked Felix <-> coder (created)' (or '(updated)' when an existing link was replaced).
-`;
-
- content += `\n### Calendar
-You have your own calendar to setup daily routines and reminders.
-Schedule future tasks for yourself. At the scheduled time, a new task is dispatched to you with the event as the prompt (task type 'calendar_event').
-
-!USE Calendar when you think the tasks are recurring or it should be conducted in the future.
-!When scheduling calendar events relative to a weekday (e.g. "every Monday"), always run date '+%A' first to confirm today's weekday before calculating the target date
-
-Keep the event title informative and concise, less than 20 words.
-Place the event details in description.
-Create a one-off event:
-- Run '${cmdPrefix()} calendar set --event_title "<TASK_TITLE>" --description "<TASK_BODY>" --datetime <YYYY-MM-DDTHH:MM>'
- - '--datetime' is LOCAL time, format 'YYYY-MM-DDTHH:MM' (e.g. '2026-04-17T09:30'). Do NOT pass UTC / ISO strings with 'Z'.
- - '--event_title' becomes the task prompt when the event fires — write it as the instruction you want future-you to receive.
-
-Create a repeating event:
-- Add '--repeat <interval>' where interval is like '1day', '2hour', '1week', '1month'.
-- Optionally add '--repeat_stop_date <YYYY-MM-DD>' to stop the recurrence (local date).
-- Example: '${cmdPrefix()} calendar set --event_title "<REPEAT_TASK_TITLE>" --description "<REPEAT_TASK_BODY>" --datetime 2026-04-18T09:00 --repeat 1day --repeat_stop_date 2026-05-18'
-
-List upcoming events:
-- Run '${cmdPrefix()} calendar list' (defaults: next 30 days, past 0 days).
-- Tune the window with '--future_days <N>' and '--past_days <N>'. Add '--json' for machine-readable output.
-- 'list' shows a '[has description]' badge instead of the full description — use 'show' (below) to read it.
-
-Show full detail of one event (use this to read the description):
-- Run '${cmdPrefix()} calendar show --event_id <EVENT_ID>'
-- Add '--json' for machine-readable output.
-
-Edit an existing event (preserves event id and recurring state):
-- Run '${cmdPrefix()} calendar update --event_id <EVENT_ID> [flags]'
-- Supply only the fields you want to change. Available flags:
- - '--event_title "<t>"' — rename the event / change the fire-time prompt
- - '--description "<d>"' to set, or '--clear_description' to remove
- - '--datetime <YYYY-MM-DDTHH:MM>' — reschedule (local time)
- - '--repeat <interval>' to set, or '--clear_repeat' to convert into a one-off
- - '--repeat_stop_date <YYYY-MM-DD>' to set, or '--clear_repeat_stop_date' to remove
-- Passing no mutating flag is an error. Do NOT use 'delete' + 'set' to edit — that loses the event id and the recurring 'last fired' state.
-
-Delete an event:
-- Run '${cmdPrefix()} calendar delete --event_id <EVENT_ID>'
-`;
-
- return content;
-}
-
-export function contentHash(content: string): string {
- return createHash("sha256").update(content, "utf-8").digest("hex");
-}
-
-export function hasContentChanged(
- filePath: string,
- newContent: string,
-): boolean {
- try {
- const existing = readFileSync(filePath, "utf-8");
- return contentHash(existing) !== contentHash(newContent);
- } catch (err: unknown) {
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return true;
- throw err;
- }
-}
-
-export function ensureSymlinks(workDir: string): void {
- const canonicalPath = join(workDir, CANONICAL_FILE);
- if (!existsSync(canonicalPath)) return;
-
- for (const alias of SYMLINK_ALIASES) {
- if (alias === CANONICAL_FILE) continue;
-
- const aliasPath = join(workDir, alias);
-
- try {
- const stat = lstatSync(aliasPath);
- if (stat.isSymbolicLink()) {
- const target = readlinkSync(aliasPath);
- if (target === CANONICAL_FILE) continue; // already correct
- unlinkSync(aliasPath);
- } else {
- // regular file — check if content already matches (copy fallback fast-path)
- const aliasContent = readFileSync(aliasPath, "utf-8");
- const canonicalContent = readFileSync(canonicalPath, "utf-8");
- if (aliasContent === canonicalContent) continue;
- unlinkSync(aliasPath);
- }
- } catch (err: unknown) {
- if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
- // doesn't exist — will create below
- }
-
- try {
- symlinkSync(CANONICAL_FILE, aliasPath);
- } catch (err: unknown) {
- const code = (err as NodeJS.ErrnoException)?.code;
- if (code === "EEXIST") {
- // Multiple session-runners for the same agent can race here (e.g., welcome
- // email + welcome chat tasks enqueued simultaneously on studio creation).
- // The first process wins; subsequent EEXIST is safe to ignore.
- } else if (code === "EPERM" || code === "EACCES") {
- copyFileSync(canonicalPath, aliasPath);
- } else {
- throw err;
- }
- }
- }
-}
-
-export function writeInstructionFileIfChanged(
- workDir: string,
- task: Task,
-): boolean {
- const content = buildInstructionContent(task);
- const filePath = join(workDir, CANONICAL_FILE);
-
- const changed = hasContentChanged(filePath, content);
- if (changed) {
- writeFileSync(filePath, content, "utf-8");
- }
-
- ensureSymlinks(workDir);
- return changed;
-}
diff --git a/src/cli/daemon/execenv/filelock.ts b/src/cli/daemon/execenv/filelock.ts
deleted file mode 100644
index 9e6003edd..000000000
--- a/src/cli/daemon/execenv/filelock.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { mkdirSync, rmdirSync, statSync } from "fs";
-
-const DEFAULT_STALE_MS = 3_600_000; // 1 hour
-
-export function acquireLock(lockPath: string, staleMs = DEFAULT_STALE_MS): boolean {
- try {
- mkdirSync(lockPath);
- return true;
- } catch {
- // Lock directory already exists — check if stale
- try {
- const stat = statSync(lockPath);
- if (Date.now() - stat.mtimeMs > staleMs) {
- rmdirSync(lockPath);
- try {
- mkdirSync(lockPath);
- return true;
- } catch {
- return false;
- }
- }
- } catch {
- // stat failed — lock was removed between our attempts
- try {
- mkdirSync(lockPath);
- return true;
- } catch {
- return false;
- }
- }
- return false;
- }
-}
-
-export function releaseLock(lockPath: string): void {
- try {
- rmdirSync(lockPath);
- } catch {
- // already removed or never existed
- }
-}
diff --git a/src/cli/daemon/execenv/index.ts b/src/cli/daemon/execenv/index.ts
deleted file mode 100644
index 0bf5dce6f..000000000
--- a/src/cli/daemon/execenv/index.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { mkdirSync } from "fs";
-import { join } from "path";
-import { writeInstructionFileIfChanged } from "./context.js";
-import type { Task } from "../types.js";
-
-export interface ExecEnvConfig {
- workspacesRoot: string;
- token?: string;
-}
-
-export interface ExecEnvResult {
- workDir: string;
- timelineDir: string;
- env: Record<string, string>;
-}
-
-export function prepare(
- config: ExecEnvConfig,
- task: Task,
-): ExecEnvResult {
- const workDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
-
- mkdirSync(workDir, { recursive: true });
-
- const timelineDir = join(workDir, ".context_timeline");
- mkdirSync(timelineDir, { recursive: true });
-
- writeInstructionFileIfChanged(workDir, task);
-
- const env: Record<string, string> = {
- ALOOK_WORKSPACE_ID: task.workspaceId,
- ALOOK_AGENT_ID: task.agentId,
- ALOOK_TASK_ID: task.id,
- ALOOK_CONVERSATION_ID: task.conversationId,
- ALOOK_TRACE_ID: task.traceId ?? "",
- ALOOK_CHANNEL: task.channel ?? "default",
- ALOOK_HEALTH_PORT: process.env.ALOOK_HEALTH_PORT || "19514",
- ...(config.token ? { ALOOK_TOKEN: config.token } : {}),
- };
-
- return { workDir, timelineDir, env };
-}
-
diff --git a/src/cli/daemon/execenv/steering.ts b/src/cli/daemon/execenv/steering.ts
deleted file mode 100644
index c1c50942f..000000000
--- a/src/cli/daemon/execenv/steering.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, statSync } from "fs";
-import { join } from "path";
-import { acquireLock, releaseLock } from "./filelock.js";
-import { createLogger } from "../../lib/logger.js";
-
-const log = createLogger({ module: "steering" });
-
-export interface KillIntent {
- reason: "superseded" | "cancelled";
- targetTaskId: string;
- expectedPid?: number | null;
- successorTaskId?: string | null;
-}
-
-const INTENT_DIR_NAME = ".kill_intents";
-const STEERING_LOCK_DIR = ".steering_locks";
-const INTENT_STALE_MS = 10 * 60 * 1000; // 10 minutes
-
-function intentFilePath(baseDir: string, taskId: string): string {
- return join(baseDir, INTENT_DIR_NAME, `${taskId}.json`);
-}
-
-function intentDirPath(baseDir: string): string {
- return join(baseDir, INTENT_DIR_NAME);
-}
-
-function steeringLockPath(baseDir: string, contextKey: string): string {
- const safeKey = contextKey.replace(/[^a-zA-Z0-9_:-]/g, "_");
- return join(baseDir, STEERING_LOCK_DIR, safeKey);
-}
-
-export function writeKillIntent(baseDir: string, intent: KillIntent): void {
- const dir = intentDirPath(baseDir);
- try {
- mkdirSync(dir, { recursive: true });
- } catch { /* already exists */ }
-
- const filePath = intentFilePath(baseDir, intent.targetTaskId);
- writeFileSync(filePath, JSON.stringify(intent));
-}
-
-export function readKillIntent(baseDir: string, taskId: string): KillIntent | null {
- const filePath = intentFilePath(baseDir, taskId);
- try {
- const content = readFileSync(filePath, "utf-8");
- return JSON.parse(content) as KillIntent;
- } catch {
- return null;
- }
-}
-
-export function clearKillIntent(baseDir: string, taskId: string): void {
- const filePath = intentFilePath(baseDir, taskId);
- try {
- unlinkSync(filePath);
- } catch { /* already removed */ }
-}
-
-export function cleanupStaleIntents(baseDir: string): void {
- const dir = intentDirPath(baseDir);
- let files: string[];
- try {
- files = readdirSync(dir).filter((f) => f.endsWith(".json"));
- } catch {
- return;
- }
- const now = Date.now();
- for (const file of files) {
- const filePath = join(dir, file);
- try {
- const content = readFileSync(filePath, "utf-8");
- const intent = JSON.parse(content) as KillIntent;
- const stat = statSync(filePath);
- if (now - stat.mtimeMs > INTENT_STALE_MS) {
- unlinkSync(filePath);
- log.debug(`Cleaned up stale kill intent for task ${intent.targetTaskId}`);
- }
- } catch { /* best-effort */ }
- }
-}
-
-export function acquireSteeringLock(baseDir: string, contextKey: string): boolean {
- const lockPath = steeringLockPath(baseDir, contextKey);
- try {
- mkdirSync(join(baseDir, STEERING_LOCK_DIR), { recursive: true });
- } catch { /* already exists */ }
- return acquireLock(lockPath, 60_000);
-}
-
-export function releaseSteeringLock(baseDir: string, contextKey: string): void {
- const lockPath = steeringLockPath(baseDir, contextKey);
- releaseLock(lockPath);
-}
diff --git a/src/cli/daemon/execenv/timeline.ts b/src/cli/daemon/execenv/timeline.ts
deleted file mode 100644
index b8193642a..000000000
--- a/src/cli/daemon/execenv/timeline.ts
+++ /dev/null
@@ -1,327 +0,0 @@
-import { appendFileSync, readFileSync, writeFileSync, renameSync } from "fs";
-import { join } from "path";
-import { acquireLock, releaseLock } from "./filelock.js";
-import { createLogger } from "../../lib/logger.js";
-
-const log = createLogger({ module: "timeline" });
-
-function readJsonl(filePath: string): ContextTimelineEntry[] {
- let content: string;
- try {
- content = readFileSync(filePath, "utf-8");
- } catch {
- return [];
- }
- const entries: ContextTimelineEntry[] = [];
- for (const line of content.trimEnd().split("\n")) {
- if (!line) continue;
- try {
- entries.push(JSON.parse(line));
- } catch { /* skip malformed */ }
- }
- return entries;
-}
-
-export interface ContextTimelineEntry {
- task_id: string;
- context_key: string | null;
- session_id: string | null;
- pid: number | null;
- status: "running" | "completed" | "failed" | "killed" | "superseded" | "cancelled";
- // True once the agent CLI has genuinely started executing (session id resolved).
- // Absent/false during the launch+warm-up window. Steering only supersedes a
- // predecessor whose agent has actually started — a not-yet-started row is left alone.
- agent_started?: boolean;
- successor_task_id?: string | null;
- supersede_reason?: string | null;
- datetime: string;
- type: string;
- prompt: string;
- agent_responses: string[];
- errmsg: string | null;
- provider: string | null;
- detailed_log: string | null;
-}
-
-function filenameForDate(date: Date): string {
- const y = date.getFullYear();
- const m = String(date.getMonth() + 1).padStart(2, "0");
- const d = String(date.getDate()).padStart(2, "0");
- return `${y}-${m}-${d}.jsonl`;
-}
-
-function todayFilename(): string {
- return filenameForDate(new Date());
-}
-
-function recentFilenames(maxDays: number): string[] {
- const filenames: string[] = [];
- const now = new Date();
- for (let i = 0; i < maxDays; i++) {
- const d = new Date(now);
- d.setDate(d.getDate() - i);
- filenames.push(filenameForDate(d));
- }
- return filenames;
-}
-
-export function localISOString(now: Date = new Date()): string {
- const tzOffset = -now.getTimezoneOffset();
- const sign = tzOffset >= 0 ? "+" : "-";
- const absOffset = Math.abs(tzOffset);
- const hh = String(Math.floor(absOffset / 60)).padStart(2, "0");
- const mm = String(absOffset % 60).padStart(2, "0");
-
- const y = now.getFullYear();
- const mo = String(now.getMonth() + 1).padStart(2, "0");
- const d = String(now.getDate()).padStart(2, "0");
- const h = String(now.getHours()).padStart(2, "0");
- const mi = String(now.getMinutes()).padStart(2, "0");
- const s = String(now.getSeconds()).padStart(2, "0");
-
- return `${y}-${mo}-${d}T${h}:${mi}:${s}${sign}${hh}:${mm}`;
-}
-
-function lockPathFor(timelineDir: string, filename: string): string {
- return join(timelineDir, `.${filename}.lock`);
-}
-
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-export function initEntry(
- timelineDir: string,
- entry: ContextTimelineEntry,
-): void {
- const filename = todayFilename();
- const filePath = join(timelineDir, filename);
- const lockPath = lockPathFor(timelineDir, filename);
-
- try {
- const acquired = acquireLock(lockPath);
- if (!acquired) {
- log.debug(`Timeline initEntry: could not acquire lock for ${filename}`);
- return;
- }
-
- try {
- appendFileSync(filePath, JSON.stringify(entry) + "\n");
- } finally {
- releaseLock(lockPath);
- }
- } catch (err) {
- log.debug("Timeline initEntry failed", err);
- }
-}
-
-export async function initEntryAsync(
- timelineDir: string,
- entry: ContextTimelineEntry,
-): Promise<void> {
- const filename = todayFilename();
- const filePath = join(timelineDir, filename);
- const lockPath = lockPathFor(timelineDir, filename);
-
- try {
- let acquired = acquireLock(lockPath);
- if (!acquired) {
- await sleep(200);
- acquired = acquireLock(lockPath);
- }
- if (!acquired) {
- log.debug(`Timeline initEntry: could not acquire lock for ${filename}`);
- return;
- }
-
- try {
- appendFileSync(filePath, JSON.stringify(entry) + "\n");
- } finally {
- releaseLock(lockPath);
- }
- } catch (err) {
- log.debug("Timeline initEntry failed", err);
- }
-}
-
-export function updateEntry(
- timelineDir: string,
- taskId: string,
- updater: (entry: ContextTimelineEntry) => void,
-): void {
- for (const filename of recentFilenames(7)) {
- const filePath = join(timelineDir, filename);
- const lockPath = lockPathFor(timelineDir, filename);
-
- try {
- const acquired = acquireLock(lockPath);
- if (!acquired) {
- log.debug(`Timeline updateEntry: lock held for ${filename}, skipping`);
- continue;
- }
-
- try {
- let content: string;
- try {
- content = readFileSync(filePath, "utf-8");
- } catch {
- continue; // file doesn't exist for this day
- }
-
- const lines = content.trimEnd().split("\n");
- let found = false;
-
- const updated = lines.map((line) => {
- const entry: ContextTimelineEntry = JSON.parse(line);
- if (entry.task_id === taskId) {
- found = true;
- updater(entry);
- }
- return JSON.stringify(entry);
- });
-
- if (!found) continue;
-
- const tmpPath = join(timelineDir, `.${filename}.tmp`);
- writeFileSync(tmpPath, updated.join("\n") + "\n");
- renameSync(tmpPath, filePath);
- return; // found and updated — stop searching
- } finally {
- releaseLock(lockPath);
- }
- } catch (err) {
- log.debug(`Timeline updateEntry failed for ${filename}`, err);
- }
- }
-
- log.debug(`Timeline updateEntry: task_id ${taskId} not found in last 7 days`);
-}
-
-export function createTimelineEntry(
- taskId: string,
- prompt: string,
- type: string,
- sessionId?: string,
- pid?: number,
- provider?: string,
- contextKey?: string | null,
- detailedLog?: string | null,
-): ContextTimelineEntry {
- return {
- task_id: taskId,
- context_key: contextKey ?? null,
- session_id: sessionId || null,
- pid: pid ?? null,
- status: "running",
- datetime: localISOString(),
- type,
- prompt,
- agent_responses: [],
- errmsg: null,
- provider: provider ?? null,
- detailed_log: detailedLog ?? null,
- };
-}
-
-export function findResumableSessionByContextKey(
- timelineDir: string,
- contextKey: string,
- provider: string,
-): string | null {
- const entries: ContextTimelineEntry[] = [];
- for (const filename of recentFilenames(90)) {
- entries.push(...readJsonl(join(timelineDir, filename)));
- }
- entries.sort((a, b) => new Date(b.datetime).getTime() - new Date(a.datetime).getTime());
- for (const entry of entries) {
- if (
- entry.status !== "running" &&
- entry.context_key === contextKey &&
- entry.provider === provider &&
- entry.session_id
- ) {
- return entry.session_id;
- }
- }
- return null;
-}
-
-export function findRunningPidByTaskId(
- timelineDir: string,
- taskId: string,
-): number | null {
- for (const filename of recentFilenames(7)) {
- const entries = readJsonl(join(timelineDir, filename));
- for (const entry of entries) {
- if (entry.task_id === taskId && entry.status === "running" && entry.pid != null) {
- return entry.pid;
- }
- }
- }
- return null;
-}
-
-
-/**
- * Steering warm-up grace window (ms). A predecessor row that is still "running"
- * but whose agent never marked itself started becomes supersedable once it is
- * older than this window — the crash-during-warm-up fallback so a conversation
- * can never wedge if a session-runner dies before the agent-started marker lands.
- */
-export function steerWarmupGraceMs(): number {
- const raw = process.env.ALOOK_STEER_WARMUP_GRACE_MS;
- const parsed = raw != null ? Number(raw) : NaN;
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : 30_000;
-}
-
-export type SupersedablePredecessor =
- | { entry: ContextTimelineEntry; reason: "agent-started" | "stale" }
- | { pending: ContextTimelineEntry }
- | null;
-
-/**
- * Find the newest "running" timeline row for this context_key+provider and decide
- * whether the newcomer may supersede it:
- * - agent_started === true → supersedable (reason "agent-started")
- * - not started but row older than grace → supersedable (reason "stale", crash fallback)
- * - not started and fresh → pending (newcomer must wait its turn)
- * - no matching running row → null (no predecessor)
- *
- * `now` is injected for deterministic tests; do NOT call Date.now() internally.
- */
-export function findSupersedablePredecessor(
- timelineDir: string,
- contextKey: string,
- provider: string,
- warmupGraceMs: number,
- now: number,
-): SupersedablePredecessor {
- for (const filename of recentFilenames(7)) {
- const dayEntries = readJsonl(join(timelineDir, filename));
- for (let i = dayEntries.length - 1; i >= 0; i--) {
- const entry = dayEntries[i];
- if (
- entry.status === "running" &&
- entry.context_key === contextKey &&
- entry.provider === provider
- ) {
- if (entry.agent_started === true) {
- return { entry, reason: "agent-started" };
- }
- if (now - Date.parse(entry.datetime) > warmupGraceMs) {
- return { entry, reason: "stale" };
- }
- return { pending: entry };
- }
- }
- }
- return null;
-}
-
-// Exported for testing
-export {
- todayFilename as _todayFilename,
- localISOString as _localISOString,
- filenameForDate as _filenameForDate,
- recentFilenames as _recentFilenames,
-};
diff --git a/src/cli/daemon/health.test.ts b/src/cli/daemon/health.test.ts
deleted file mode 100644
index c82e85224..000000000
--- a/src/cli/daemon/health.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe, it, expect, afterAll } from "vitest";
-import { createHealthServer } from "./health.js";
-
-const TEST_PORT = 19614;
-const healthUrl = `http://127.0.0.1:${TEST_PORT}`;
-
-const { server, setRuntimeCount } = createHealthServer(TEST_PORT);
-
-afterAll(
- () => new Promise<void>((resolve) => server.close(() => resolve())),
-);
-
-describe("health server", () => {
- it("binds to 127.0.0.1", () => {
- const addr = server.address();
- expect(addr).not.toBeNull();
- if (typeof addr === "object" && addr) {
- expect(addr.address).toBe("127.0.0.1");
- }
- });
-
- it("GET /health returns status ok with uptime and runtimes", async () => {
- const res = await fetch(`${healthUrl}/health`);
- expect(res.status).toBe(200);
-
- const body = await res.json();
- expect(body.status).toBe("ok");
- expect(body.uptime).toMatch(/^\d+s$/);
- expect(body.runtimes).toBe(0);
- });
-
- it("setRuntimeCount updates the runtimes count", async () => {
- setRuntimeCount(5);
-
- const res = await fetch(`${healthUrl}/health`);
- const body = await res.json();
- expect(body.runtimes).toBe(5);
- });
-
- it("non-health paths return 404", async () => {
- const res = await fetch(`${healthUrl}/other`);
- expect(res.status).toBe(404);
- });
-});
diff --git a/src/cli/daemon/health.ts b/src/cli/daemon/health.ts
deleted file mode 100644
index f91238043..000000000
--- a/src/cli/daemon/health.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { createServer, type IncomingMessage, type ServerResponse } from "http";
-
-const DEFAULT_HEALTH_PORT = Number(process.env.ALOOK_HEALTH_PORT) || 19514;
-
-export function createHealthServer(port: number = DEFAULT_HEALTH_PORT) {
- let runtimeCount = 0;
- const startTime = Date.now();
-
- const server = createServer((req: IncomingMessage, res: ServerResponse) => {
- if (req.url === "/health") {
- const uptimeSec = Math.floor((Date.now() - startTime) / 1000);
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(
- JSON.stringify({
- status: "ok",
- uptime: `${uptimeSec}s`,
- runtimes: runtimeCount,
- }),
- );
- } else {
- res.writeHead(404);
- res.end();
- }
- });
-
- server.listen(port, "127.0.0.1");
-
- return {
- server,
- setRuntimeCount(n: number) {
- runtimeCount = n;
- },
- };
-}
diff --git a/src/cli/daemon/kill-tree-win32.test.ts b/src/cli/daemon/kill-tree-win32.test.ts
deleted file mode 100644
index ccf9d54ca..000000000
--- a/src/cli/daemon/kill-tree-win32.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-
-// Mock process.platform to "win32" BEFORE kill-tree.ts evaluates isPosix.
-const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;
-Object.defineProperty(process, "platform", { value: "win32", configurable: true });
-
-const execSyncMock = vi.fn();
-vi.mock("child_process", () => ({
- execSync: execSyncMock,
-}));
-
-const { killProcessTree, isAlive } = await import("./kill-tree.js");
-
-// Restore platform after import so Vitest internals aren't confused.
-Object.defineProperty(process, "platform", originalPlatform);
-
-describe("killProcessTree (Windows)", () => {
- it("calls taskkill /PID <pid> /T /F on Windows", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation((_pid: number, signal?: string | number) => {
- if (signal === 0) return true; // isAlive → true
- return true;
- });
-
- await killProcessTree(9999);
-
- expect(execSyncMock).toHaveBeenCalledWith("taskkill /PID 9999 /T /F", { stdio: "ignore" });
- killSpy.mockRestore();
- });
-
- it("does not poll or escalate to SIGKILL on Windows", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation((_pid: number, signal?: string | number) => {
- if (signal === 0) return true;
- return true;
- });
-
- const start = Date.now();
- await killProcessTree(8888);
- const elapsed = Date.now() - start;
-
- // Should return immediately — no POLL_MS loop on Windows
- expect(elapsed).toBeLessThan(200);
- expect(execSyncMock).toHaveBeenCalledWith("taskkill /PID 8888 /T /F", { stdio: "ignore" });
- killSpy.mockRestore();
- });
-
- it("does not throw when taskkill fails (process already dead)", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation((_pid: number, signal?: string | number) => {
- if (signal === 0) return true;
- return true;
- });
- execSyncMock.mockImplementationOnce(() => { throw new Error("process not found"); });
-
- await expect(killProcessTree(7777)).resolves.toBeUndefined();
- killSpy.mockRestore();
- });
-
- it("skips if process is already dead (isAlive returns false)", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => {
- throw Object.assign(new Error("ESRCH"), { code: "ESRCH" });
- });
- execSyncMock.mockClear();
-
- await killProcessTree(6666);
-
- expect(execSyncMock).not.toHaveBeenCalled();
- killSpy.mockRestore();
- });
-});
diff --git a/src/cli/daemon/kill-tree.test.ts b/src/cli/daemon/kill-tree.test.ts
deleted file mode 100644
index cac3df284..000000000
--- a/src/cli/daemon/kill-tree.test.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { describe, it, expect, afterEach } from "vitest";
-import { spawn, type ChildProcess } from "child_process";
-import { killProcessTree, isAlive } from "./kill-tree.js";
-
-// These are real-process integration tests; POSIX-only (group semantics).
-const posix = process.platform !== "win32";
-const d = posix ? describe : describe.skip;
-
-const spawned: ChildProcess[] = [];
-
-afterEach(() => {
- // Best-effort cleanup of anything a test left alive.
- for (const p of spawned.splice(0)) {
- if (p.pid) {
- try { process.kill(-p.pid, "SIGKILL"); } catch { /* */ }
- try { process.kill(p.pid, "SIGKILL"); } catch { /* */ }
- }
- }
-});
-
-/** Spawn a detached node process that prints its child's pid then idles. */
-function spawnParentWithChild(): Promise<{ proc: ChildProcess; childPid: number }> {
- // Parent forks a grandchild (both long-lived), prints "GRANDCHILD <pid>".
- const code = `
- const { spawn } = require("child_process");
- const g = spawn(process.execPath, ["-e", "setInterval(()=>{}, 1e9)"], { stdio: "ignore" });
- process.stdout.write("GRANDCHILD " + g.pid + "\\n");
- setInterval(() => {}, 1e9);
- `;
- const proc = spawn(process.execPath, ["-e", code], {
- detached: true,
- stdio: ["ignore", "pipe", "ignore"],
- });
- spawned.push(proc);
- return new Promise((resolve, reject) => {
- let buf = "";
- proc.stdout!.on("data", (c: Buffer) => {
- buf += c.toString();
- const m = buf.match(/GRANDCHILD (\d+)/);
- if (m) resolve({ proc, childPid: Number(m[1]) });
- });
- proc.on("error", reject);
- setTimeout(() => reject(new Error("timeout waiting for grandchild")), 5000);
- });
-}
-
-/** Spawn a detached node process that ignores SIGTERM and idles. */
-function spawnSigtermIgnorer(): ChildProcess {
- const code = `process.on("SIGTERM", () => {}); setInterval(() => {}, 1e9);`;
- const proc = spawn(process.execPath, ["-e", code], {
- detached: true,
- stdio: "ignore",
- });
- spawned.push(proc);
- return proc;
-}
-
-const waitFor = async (fn: () => boolean, ms = 3000) => {
- const deadline = Date.now() + ms;
- while (Date.now() < deadline) {
- if (fn()) return true;
- await new Promise((r) => setTimeout(r, 25));
- }
- return fn();
-};
-
-d("killProcessTree", () => {
- it("TC1: kills the child and its grandchild via the process group", async () => {
- const { proc, childPid } = await spawnParentWithChild();
- expect(proc.pid).toBeDefined();
- expect(isAlive(proc.pid!)).toBe(true);
- expect(isAlive(childPid)).toBe(true);
-
- await killProcessTree(proc.pid!, { graceMs: 2000 });
-
- expect(await waitFor(() => !isAlive(proc.pid!))).toBe(true);
- expect(await waitFor(() => !isAlive(childPid))).toBe(true);
- });
-
- it("TC2: escalates to SIGKILL when the target ignores SIGTERM", async () => {
- const proc = spawnSigtermIgnorer();
- // give it a moment to install its SIGTERM trap
- await new Promise((r) => setTimeout(r, 100));
- expect(isAlive(proc.pid!)).toBe(true);
-
- await killProcessTree(proc.pid!, { graceMs: 300 });
-
- // SIGTERM is trapped, so only the SIGKILL escalation could have killed it.
- expect(await waitFor(() => !isAlive(proc.pid!))).toBe(true);
- });
-
- it("TC3: resolves promptly and never throws when the target is already dead", async () => {
- const proc = spawn(process.execPath, ["-e", "process.exit(0)"], { detached: true, stdio: "ignore" });
- await new Promise((r) => proc.on("exit", r));
- const pid = proc.pid!;
- expect(isAlive(pid)).toBe(false);
-
- const start = Date.now();
- await expect(killProcessTree(pid, { graceMs: 2000 })).resolves.toBeUndefined();
- // Should return almost immediately (no grace wait for a dead pid).
- expect(Date.now() - start).toBeLessThan(500);
- });
-
- it("ignores invalid pids without throwing", async () => {
- await expect(killProcessTree(0)).resolves.toBeUndefined();
- await expect(killProcessTree(-1)).resolves.toBeUndefined();
- });
-});
-
-describe("isAlive", () => {
- it("returns true for the current process and false for a never-used pid", () => {
- expect(isAlive(process.pid)).toBe(true);
- // A very high pid is essentially guaranteed not to exist.
- expect(isAlive(2_000_000_000)).toBe(false);
- });
-});
-
diff --git a/src/cli/daemon/kill-tree.ts b/src/cli/daemon/kill-tree.ts
deleted file mode 100644
index 30e7dbd3d..000000000
--- a/src/cli/daemon/kill-tree.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- * Process-tree termination with SIGKILL escalation.
- *
- * Inner agent CLIs (claude/codex/opencode) are spawned `detached:true` on POSIX
- * (see agent/*.ts), so each becomes the leader of its own process group whose id
- * equals its pid. Signalling the *negative* pid (`process.kill(-pid, ...)`) then
- * reaches the whole group — the CLI plus the MCP servers / tool subprocesses it
- * spawned — instead of just the leader. A plain positive-pid SIGTERM (the old
- * behaviour) leaves those grandchildren orphaned and burning CPU.
- *
- * SIGTERM is a request, not a guarantee: a wedged or signal-ignoring CLI keeps
- * running. So after a short grace window we escalate to SIGKILL.
- */
-
-import { execSync } from "child_process";
-import { createLogger } from "../lib/logger.js";
-
-const log = createLogger({ module: "kill-tree" });
-
-/** Session-runner grace before it escalates the inner-agent group to SIGKILL. */
-export function killGraceMs(): number {
- return Number(process.env.ALOOK_KILL_GRACE_MS) || 2000;
-}
-const POLL_MS = 100;
-const isPosix = process.platform !== "win32";
-
-/** True while the process is alive; signal 0 probes without delivering a signal. */
-export function isAlive(pid: number): boolean {
- try {
- process.kill(pid, 0);
- return true;
- } catch (e) {
- // EPERM means the process exists but we can't signal it — still "alive".
- return (e as NodeJS.ErrnoException)?.code === "EPERM";
- }
-}
-
-/**
- * Send `signal` to the whole process group, ALWAYS ALSO followed by a direct
- * pid signal — regardless of whether the group signal succeeded, threw
- * `ESRCH` (no such process group — e.g. a driver stopped passing `detached`),
- * or threw anything else. A group-signal failure must never be read as "the
- * pid is dead": that conflates two unrelated failure modes and was the root
- * cause of a sibling bug in `src/daemon/src/runtime/killTree.ts` where
- * stopped agents kept running forever (see
- * plans/fix-daemon-agent-process-kill.md). Signaling an already-dead pid is
- * safe — it just throws too, caught and ignored below.
- */
-function signalTree(pid: number, signal: NodeJS.Signals): void {
- if (!isPosix) {
- try {
- execSync(`taskkill /PID ${pid} /T /F`, { stdio: "ignore" });
- } catch {
- // process may already be dead
- }
- return;
- }
- try {
- // Negative pid = the process group led by `pid`.
- process.kill(-pid, signal);
- } catch {
- // No such process group (not detached, or already gone) — fall through
- // to signal the pid directly.
- }
- try {
- process.kill(pid, signal);
- } catch {
- // already dead / not signalable — best-effort
- }
-}
-
-/**
- * Terminate `pid` and its descendants: group SIGTERM, then group SIGKILL if it
- * is still alive after `graceMs`. Never throws; 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;
-
- if (!isPosix) {
- // Windows: taskkill /T /F kills the entire tree, no grace needed
- signalTree(pid, "SIGTERM");
- return;
- }
-
- // POSIX: SIGTERM + grace + SIGKILL escalation
- const graceMs = opts?.graceMs ?? killGraceMs();
- 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)) {
- log.warn(`pid=${pid} survived SIGTERM after ${graceMs}ms — escalating to SIGKILL`);
- signalTree(pid, "SIGKILL");
- }
-}
diff --git a/src/cli/daemon/meeting-runner.ts b/src/cli/daemon/meeting-runner.ts
deleted file mode 100644
index ebe9afcdb..000000000
--- a/src/cli/daemon/meeting-runner.ts
+++ /dev/null
@@ -1,283 +0,0 @@
-import { chromium } from "playwright-core"
-import {
- ensureChrome,
- joinMeeting,
- enableCaptions,
- waitForMeetingReady,
- buildAloneDetectorScript,
- isMeetingActive,
- leaveMeeting,
- buildCaptionObserverScript,
- buildCaptionScrapeScript,
- parseCaptionElements,
- deduplicateCaptions,
- formatTranscript,
-} from "@alook/shared/browser"
-import type { TranscriptEntry } from "@alook/shared/browser"
-import { join } from "path"
-import { mkdirSync } from "fs"
-import { tempDir } from "../lib/platform.js"
-import { createLogger } from "../lib/logger.js"
-import { createTimelineEntry, initEntry, updateEntry } from "./execenv/timeline.js"
-
-const log = createLogger({ module: "meeting-runner" })
-
-const SCRAPE_INTERVAL_MS = 3_000
-const DEFAULT_BOT_NAME = "Alook Meeting Bot"
-const MAX_RETRY_DURATION_MS = 30 * 60 * 1000
-const RETRY_BACKOFF = [30_000, 60_000, 120_000, 300_000]
-
-export interface MeetingRunnerInput {
- meetingId: string
- meetingUrl: string
- participants: string[]
- workspaceId: string
- callbackUrl: string
- authToken: string
- agentName?: string
- agentId?: string
- timelineDir?: string
- title?: string
-}
-
-async function callbackWeb(
- input: MeetingRunnerInput,
- status: "completed" | "failed",
- transcript?: string,
- error?: string,
-): Promise<void> {
- const payload = JSON.stringify({
- meetingId: input.meetingId,
- workspaceId: input.workspaceId,
- status,
- transcript: transcript || undefined,
- error: error || undefined,
- })
-
- try {
- const res = await fetch(`${input.callbackUrl}/api/meeting/callback`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${input.authToken}`,
- },
- body: payload,
- })
- log.info(`callback ${status} → HTTP ${res.status}`, { meeting: input.meetingId })
- } catch (err) {
- log.error(`callback failed: ${err instanceof Error ? err.message : err}`, { meeting: input.meetingId })
- }
-}
-
-function launchBrowser(chromePath: string) {
- return chromium.launch({
- executablePath: chromePath,
- headless: false,
- args: [
- "--lang=en-US",
- "--disable-blink-features=AutomationControlled",
- "--use-fake-ui-for-media-stream",
- "--use-fake-device-for-media-stream",
- "--disable-audio-output",
- ],
- })
-}
-
-async function tryJoinAndRecord(input: MeetingRunnerInput, chromePath: string): Promise<{ status: "completed" | "blocked" | "error"; transcript: TranscriptEntry[]; error?: string }> {
- const browser = await launchBrowser(chromePath)
- const context = browser.contexts()[0]
- if (context) {
- /* istanbul ignore next -- this callback is serialized into the browser */
- await context.addInitScript(() => {
- Object.defineProperty(navigator, "webdriver", { get: () => false })
- })
- }
-
- const page = await browser.newPage({ locale: "en-US" })
- const meetingStartMs = Date.now()
- let transcript: TranscriptEntry[] = []
-
- try {
- const botName = input.agentName ? `${input.agentName} (Alook)` : DEFAULT_BOT_NAME
- await joinMeeting(page, input.meetingUrl, botName)
- log.info("joined meeting, waiting for UI ready...", { meeting: input.meetingId })
- await waitForMeetingReady(page)
-
- /* istanbul ignore next -- this callback is serialized into the browser */
- await page.evaluate(() => {
- for (const btn of document.querySelectorAll('button')) {
- const label = (btn.getAttribute('aria-label') || '').toLowerCase()
- if (label.startsWith('turn off') && (label.includes('microphone') || label.includes('camera'))) {
- (btn as HTMLElement).click()
- }
- }
- })
- log.info("meeting ready, enabling captions...", { meeting: input.meetingId })
-
- await enableCaptions(page)
- await page.evaluate(buildCaptionObserverScript())
- await page.evaluate(buildAloneDetectorScript())
- log.info("captions enabled, scraping loop started", { meeting: input.meetingId })
-
- let scrapeCount = 0
- while (true) {
- try {
- const active = await isMeetingActive(page)
- if (!active) {
- const finalRaw = await page.evaluate(buildCaptionScrapeScript()) as { speakerHtml: string; textHtml: string }[]
- const finalCaptions = parseCaptionElements(finalRaw)
- if (finalCaptions.length > 0) {
- transcript = deduplicateCaptions(transcript, finalCaptions, meetingStartMs, Date.now())
- log.debug(`final scrape: ${finalCaptions.length} caption(s), total ${transcript.length}`, { meeting: input.meetingId })
- }
- log.info("meeting ended (no longer active)", { meeting: input.meetingId })
- break
- }
-
- const rawElements = await page.evaluate(buildCaptionScrapeScript()) as { speakerHtml: string; textHtml: string }[]
- const captions = parseCaptionElements(rawElements)
- scrapeCount++
-
- if (captions.length > 0) {
- const prevLen = transcript.length
- transcript = deduplicateCaptions(transcript, captions, meetingStartMs, Date.now())
- if (transcript.length > prevLen) {
- log.debug(`caption: ${captions[captions.length - 1].speaker}: "${captions[captions.length - 1].text}" (total ${transcript.length})`, { meeting: input.meetingId })
- }
- } else if (scrapeCount <= 5) {
- log.debug(`scrape #${scrapeCount}: no captions yet`, { meeting: input.meetingId })
- }
- } catch (err) {
- log.error(`scrape error: ${err instanceof Error ? err.message : err}`, { meeting: input.meetingId })
- break
- }
-
- await new Promise((resolve) => setTimeout(resolve, SCRAPE_INTERVAL_MS))
- }
-
- await leaveMeeting(page)
- return { status: "completed", transcript }
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err)
- if (msg.includes("Blocked from joining")) {
- const screenshotPath = join(tempDir("alook-meetings"), `meeting-${input.meetingId}-blocked.png`)
- await page.screenshot({ path: screenshotPath }).catch(() => {})
- log.warn(`blocked from joining, screenshot saved: ${screenshotPath}`, { meeting: input.meetingId })
- return { status: "blocked", transcript, error: msg }
- }
- log.error(`unexpected error: ${msg}`, { meeting: input.meetingId })
- return { status: "error", transcript, error: msg }
- } finally {
- await page.close().catch(() => {})
- await browser.close().catch(() => {})
- }
-}
-
-function writeTimeline(
- input: MeetingRunnerInput,
- status: "running" | "completed" | "failed",
- responses?: string[],
- errmsg?: string,
-): void {
- if (!input.timelineDir) return
- try {
- mkdirSync(input.timelineDir, { recursive: true })
- const taskId = `meeting-${input.meetingId}`
- if (status === "running") {
- const meetingLabel = input.title || input.meetingUrl
- const entry = createTimelineEntry(
- taskId,
- `Meeting: ${meetingLabel} (participants: ${input.participants.join(", ")})`,
- "meeting",
- undefined,
- process.pid,
- )
- initEntry(input.timelineDir, entry)
- } else {
- updateEntry(input.timelineDir, taskId, (entry) => {
- entry.status = status
- entry.pid = null
- if (responses) entry.agent_responses = responses
- if (errmsg) entry.errmsg = errmsg
- })
- }
- } catch (err) {
- log.debug(`timeline write failed: ${err instanceof Error ? err.message : err}`)
- }
-}
-
-async function run(input: MeetingRunnerInput): Promise<void> {
- log.info(`starting meeting: url=${input.meetingUrl}`, { meeting: input.meetingId, workspace: input.workspaceId })
-
- writeTimeline(input, "running")
-
- let chromePath: string
- try {
- chromePath = ensureChrome()
- log.debug(`chrome found: ${chromePath}`)
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err)
- log.error(`chrome setup failed: ${msg}`, { meeting: input.meetingId })
- writeTimeline(input, "failed", undefined, `Chrome setup failed: ${msg}`)
- await callbackWeb(input, "failed", undefined, `Chrome setup failed: ${msg}`)
- process.exit(1)
- }
-
- const startTime = Date.now()
- let attempt = 0
-
- while (true) {
- attempt++
- log.info(attempt > 1 ? `retry attempt #${attempt}` : "launching browser (en-US, stealth)...", { meeting: input.meetingId })
-
- const result = await tryJoinAndRecord(input, chromePath)
-
- if (result.status === "completed") {
- const transcriptText = formatTranscript(result.transcript)
- log.info(`completed: ${result.transcript.length} transcript entries`, { meeting: input.meetingId })
-
- const transcriptR2Key = `meetings/${input.meetingId}/transcript`
- writeTimeline(input, "completed", [
- `Meeting completed. ${result.transcript.length} transcript entries captured.`,
- `Transcript stored at: ${transcriptR2Key}`,
- ])
-
- await callbackWeb(input, "completed", transcriptText)
- return
- }
-
- if (result.status === "blocked") {
- const elapsed = Date.now() - startTime
- if (elapsed >= MAX_RETRY_DURATION_MS) {
- log.warn(`giving up after ${Math.round(elapsed / 60_000)}min of retries`, { meeting: input.meetingId })
- writeTimeline(input, "failed", undefined, result.error)
- await callbackWeb(input, "failed", undefined, result.error)
- return
- }
- const backoff = RETRY_BACKOFF[Math.min(attempt - 1, RETRY_BACKOFF.length - 1)]
- log.info(`blocked, retrying in ${backoff / 1000}s (attempt=${attempt}, elapsed=${Math.round(elapsed / 60_000)}min)`, { meeting: input.meetingId })
- await new Promise((resolve) => setTimeout(resolve, backoff))
- continue
- }
-
- // Other errors — don't retry
- writeTimeline(input, "failed", undefined, result.error)
- await callbackWeb(input, "failed", undefined, result.error)
- return
- }
-}
-
-const encoded = process.argv[2]
-if (!encoded) {
- console.error("Usage: meeting-runner <base64-encoded-input>")
- process.exit(1)
-}
-
-const input: MeetingRunnerInput = JSON.parse(
- Buffer.from(encoded, "base64").toString("utf-8"),
-)
-
-run(input).then(() => process.exit(0)).catch((err) => {
- log.error(`fatal: ${err instanceof Error ? err.message : err}`)
- process.exit(1)
-})
diff --git a/src/cli/daemon/pidfile.test.ts b/src/cli/daemon/pidfile.test.ts
deleted file mode 100644
index 9fb9d46b5..000000000
--- a/src/cli/daemon/pidfile.test.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { mkdirSync, writeFileSync, readFileSync, unlinkSync, existsSync } from "fs";
-import { join } from "path";
-import { tmpdir } from "os";
-
-// Use a temp directory for each test
-let testDir: string;
-
-vi.mock("./config.js", () => ({
- pidFilePath: (profile?: string) => {
- const name = profile ? `daemon_${profile}.pid` : "daemon.pid";
- return join(testDir, name);
- },
-}));
-
-vi.mock("../lib/logger.js", () => {
- const mockLog = { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() };
- return { createLogger: () => mockLog, log: mockLog };
-});
-
-import { acquireDaemonPid, releaseDaemonPid, isProcessAlive, readDaemonPid } from "./pidfile.js";
-
-describe("pidfile", () => {
- beforeEach(() => {
- testDir = join(tmpdir(), `pidfile-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(testDir, { recursive: true });
- });
-
- afterEach(() => {
- // Clean up
- try {
- for (const name of ["daemon.pid", "daemon_dev.pid"]) {
- try { unlinkSync(join(testDir, name)); } catch {}
- }
- unlinkSync(testDir);
- } catch {}
- });
-
- it("writes PID file and returns true on fresh acquire", () => {
- const result = acquireDaemonPid();
- expect(result).toBe(true);
-
- const content = readFileSync(join(testDir, "daemon.pid"), "utf-8");
- expect(parseInt(content, 10)).toBe(process.pid);
- });
-
- it("returns false when PID file exists and process is alive", () => {
- // Write current process PID — it's alive
- writeFileSync(join(testDir, "daemon.pid"), String(process.pid));
-
- const result = acquireDaemonPid();
- expect(result).toBe(false);
- });
-
- it("overwrites stale PID file when process is not running", () => {
- // PID 999999999 is almost certainly not running
- writeFileSync(join(testDir, "daemon.pid"), "999999999");
-
- const result = acquireDaemonPid();
- expect(result).toBe(true);
-
- const content = readFileSync(join(testDir, "daemon.pid"), "utf-8");
- expect(parseInt(content, 10)).toBe(process.pid);
- });
-
- it("release removes PID file", () => {
- writeFileSync(join(testDir, "daemon.pid"), String(process.pid));
- expect(existsSync(join(testDir, "daemon.pid"))).toBe(true);
-
- releaseDaemonPid();
- expect(existsSync(join(testDir, "daemon.pid"))).toBe(false);
- });
-
- it("release is no-op if file does not exist", () => {
- // Should not throw
- expect(() => releaseDaemonPid()).not.toThrow();
- });
-
- it("release does not remove pidfile owned by a different process", () => {
- writeFileSync(join(testDir, "daemon.pid"), "999999999");
- releaseDaemonPid();
- expect(existsSync(join(testDir, "daemon.pid"))).toBe(true);
- });
-
- it("release removes pidfile when contents match own pid", () => {
- writeFileSync(join(testDir, "daemon.pid"), String(process.pid));
- releaseDaemonPid();
- expect(existsSync(join(testDir, "daemon.pid"))).toBe(false);
- });
-
- it("uses profile-specific PID file path", () => {
- const result = acquireDaemonPid("dev");
- expect(result).toBe(true);
-
- expect(existsSync(join(testDir, "daemon_dev.pid"))).toBe(true);
- });
-});
-
-describe("isProcessAlive", () => {
- it("returns true for the current process", () => {
- expect(isProcessAlive(process.pid)).toBe(true);
- });
-
- it("returns false for a PID that does not exist", () => {
- expect(isProcessAlive(999999999)).toBe(false);
- });
-});
-
-describe("readDaemonPid", () => {
- beforeEach(() => {
- testDir = join(tmpdir(), `pidfile-read-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(testDir, { recursive: true });
- });
-
- afterEach(() => {
- try {
- for (const name of ["daemon.pid", "daemon_dev.pid"]) {
- try { unlinkSync(join(testDir, name)); } catch {}
- }
- unlinkSync(testDir);
- } catch {}
- });
-
- it("returns null when pidfile is absent", () => {
- expect(readDaemonPid()).toBeNull();
- });
-
- it("returns integer when pidfile contains a number", () => {
- writeFileSync(join(testDir, "daemon.pid"), "12345");
- expect(readDaemonPid()).toBe(12345);
- });
-
- it("trims whitespace before parsing", () => {
- writeFileSync(join(testDir, "daemon.pid"), " 42 \n");
- expect(readDaemonPid()).toBe(42);
- });
-
- it("returns null when contents are unparsable", () => {
- writeFileSync(join(testDir, "daemon.pid"), "not-a-number");
- expect(readDaemonPid()).toBeNull();
- });
-
- it("uses profile-specific path", () => {
- writeFileSync(join(testDir, "daemon_dev.pid"), "7");
- expect(readDaemonPid("dev")).toBe(7);
- expect(readDaemonPid()).toBeNull();
- });
-});
diff --git a/src/cli/daemon/pidfile.ts b/src/cli/daemon/pidfile.ts
deleted file mode 100644
index d51865246..000000000
--- a/src/cli/daemon/pidfile.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { readFileSync, writeFileSync, unlinkSync, mkdirSync } from "fs";
-import { dirname } from "path";
-import { pidFilePath } from "./config.js";
-import { createLogger } from "../lib/logger.js";
-
-const log = createLogger({ module: "pidfile" });
-
-export function isProcessAlive(pid: number): boolean {
- try {
- process.kill(pid, 0);
- return true;
- } catch {
- return false;
- }
-}
-
-export function readDaemonPid(profile?: string): number | null {
- try {
- const content = readFileSync(pidFilePath(profile), "utf-8").trim();
- const pid = parseInt(content, 10);
- return Number.isNaN(pid) ? null : pid;
- } catch {
- return null;
- }
-}
-
-/**
- * Write a PID file to prevent duplicate daemon starts.
- * Returns true if acquired, false if another daemon is already running.
- */
-export function acquireDaemonPid(profile?: string): boolean {
- const pidPath = pidFilePath(profile);
-
- try {
- const content = readFileSync(pidPath, "utf-8").trim();
- const existingPid = parseInt(content, 10);
- if (!isNaN(existingPid) && isProcessAlive(existingPid)) {
- log.error(
- `Another daemon is already running (PID ${existingPid}). ` +
- `Remove ${pidPath} if this is stale.`,
- );
- return false;
- }
- } catch {
- // No existing PID file — proceed
- }
-
- mkdirSync(dirname(pidPath), { recursive: true, mode: 0o700 });
- writeFileSync(pidPath, String(process.pid), { mode: 0o600 });
- return true;
-}
-
-/**
- * Remove the pidfile only if its contents match the given PID. Prevents a
- * daemon from deleting someone else's pidfile (e.g. after a PID was reused or
- * a newer daemon acquired the slot).
- */
-export function removePidFileIfMatches(pid: number, profile?: string): void {
- const pidPath = pidFilePath(profile);
- const onDisk = readDaemonPid(profile);
- if (onDisk !== pid) return;
- try {
- unlinkSync(pidPath);
- } catch {
- // already removed
- }
-}
-
-/** Remove our own pidfile on shutdown. */
-export function releaseDaemonPid(profile?: string): void {
- removePidFileIfMatches(process.pid, profile);
-}
diff --git a/src/cli/daemon/prompt.test.ts b/src/cli/daemon/prompt.test.ts
deleted file mode 100644
index bff76435d..000000000
--- a/src/cli/daemon/prompt.test.ts
+++ /dev/null
@@ -1,419 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { buildPrompt, buildTaskObject, buildMergedPrompt } from "./prompt.js";
-import { localISOString } from "./execenv/timeline.js";
-import type { Task } from "./types.js";
-
-function makeTask(prompt: string, type = "user_dm_message"): Task {
- return {
- id: "t1",
- agentId: "a1",
- runtimeId: "r1",
- conversationId: "c1",
- workspaceId: "w1",
- prompt,
- type,
- status: "pending",
- priority: 1,
- createdAt: new Date().toISOString(),
- traceId: null,
- parentTaskId: null,
- channel: null,
- };
-}
-
-describe("buildPrompt", () => {
- it("returns structured JSON with type and instruction", () => {
- const task = makeTask("Fix the login bug");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.type).toBe("user_dm_message");
- expect(parsed.instruction).toBe("Fix the login bug");
- });
-
- it("handles empty prompt", () => {
- const task = makeTask("");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.type).toBe("user_dm_message");
- expect(parsed.instruction).toBe("");
- });
-
- it("includes the task type in output", () => {
- const task = makeTask("Check inbox", "email_inbound");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.type).toBe("email_inbound");
- expect(parsed.instruction).toBe("Check inbox");
- expect(buildPrompt(task)).toBe(
- JSON.stringify({
- type: "email_inbound",
- received_at: parsed.received_at,
- instruction: "Check inbox",
- }),
- );
- });
-
- it("stamps received_at from createdAt, matching localISOString", () => {
- const task = makeTask("Hi");
- task.createdAt = "2026-06-04T14:12:33.000Z";
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.received_at).toBe(localISOString(new Date(task.createdAt)));
- // Round-trip to the same instant, avoiding brittle tz-string assertions on CI.
- expect(new Date(parsed.received_at).getTime()).toBe(Date.parse(task.createdAt));
- });
-
- it("stamps received_at for every input source", () => {
- for (const type of [
- "user_dm_message",
- "email_notification",
- "calendar_event",
- "issue_event",
- ]) {
- const parsed = JSON.parse(buildPrompt(makeTask("x", type)));
- expect(typeof parsed.received_at).toBe("string");
- expect(parsed.received_at).not.toBe("");
- }
- });
-
- it("keeps calendar datetime (scheduled) distinct from received_at (arrival)", () => {
- const task: Task = {
- ...makeTask("scheduled task", "calendar_event"),
- createdAt: "2026-06-04T14:12:33.000Z",
- context: { datetime: "2026-06-10T09:00" },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.datetime).toBe("2026-06-10T09:00");
- expect(parsed.received_at).toBe(localISOString(new Date("2026-06-04T14:12:33.000Z")));
- expect(parsed.received_at).not.toBe(parsed.datetime);
- });
-
- it("falls back to a valid current time when createdAt is invalid", () => {
- const task = makeTask("Hi");
- task.createdAt = "";
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.received_at).not.toBe("");
- expect(Number.isNaN(Date.parse(parsed.received_at))).toBe(false);
- });
-
- it("adds EMAIL_NOTICE for email_notification tasks without context", () => {
- const task = makeTask("New email from [email protected]: Hi", "email_notification");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("triggered by an incoming email");
- expect(parsed.notice).toContain("email sending tool");
- expect(parsed.notice).toContain("email them and then exit");
- expect(parsed.notice).toContain("new task will be triggered automatically");
- });
-
- it("adds EMAIL_NOTICE when conversationType is email_notification", () => {
- const task: Task = {
- ...makeTask("New email from [email protected]: Hi", "email_notification"),
- context: { conversationType: "email_notification" },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("Reply to the sender via email");
- });
-
- it("adds DM_NOTICE when conversationType is user_dm_message with dmUser", () => {
- const task: Task = {
- ...makeTask("New email from [email protected]: Review this", "email_notification"),
- context: { conversationType: "user_dm_message", dmUser: { name: "Alice", email: "[email protected]" } },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("Alice");
- expect(parsed.notice).toContain("[email protected]");
- expect(parsed.notice).toContain("reply to them directly");
- expect(parsed.notice).not.toContain("Reply to the sender via email");
- });
-
- it("falls back to EMAIL_NOTICE when conversationType is user_dm_message but dmUser is missing", () => {
- const task: Task = {
- ...makeTask("New email from [email protected]: Hi", "email_notification"),
- context: { conversationType: "user_dm_message" },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("Reply to the sender via email");
- });
-
- it("falls back to EMAIL_NOTICE when conversationType is undefined in context", () => {
- const task: Task = {
- ...makeTask("New email from [email protected]: Hi", "email_notification"),
- context: { someOtherField: "value" },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("Reply to the sender via email");
- });
-
- it("adds DM_RESPONSE_NOTICE for user_dm_message tasks", () => {
- const task = makeTask("Fix the bug", "user_dm_message");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("sync send-dm");
- expect(parsed.notice).toContain("at milestones");
- expect(parsed.notice).not.toContain("final text response is visible to the user");
- });
-
- it("adds CALENDAR_NOTICE for calendar_event tasks with no context", () => {
- const task = makeTask("Do the standup", "calendar_event");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("scheduled calendar event");
- expect(parsed.notice).toContain("send an email");
- expect(parsed.notice).toContain("email sending tool");
- expect(parsed.description).toBeUndefined();
- expect(parsed.scheduled_by).toBeUndefined();
- });
-
- it("includes description and scheduled_by for calendar_event with full context", () => {
- const task: Task = {
- ...makeTask("Do the standup", "calendar_event"),
- context: {
- event_id: "ce_1",
- datetime: "2026-04-17T09:00:00.000Z",
- is_recurring: true,
- repeat_interval: "1day",
- description: "Check PRs merged this week",
- scheduled_by: { name: "Gus", email: "[email protected]" },
- },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("scheduled calendar event");
- expect(parsed.event_id).toBe("ce_1");
- expect(parsed.datetime).toBe("2026-04-17T09:00:00.000Z");
- expect(parsed.is_recurring).toBe(true);
- expect(parsed.repeat_interval).toBe("1day");
- expect(parsed.description).toBe("Check PRs merged this week");
- expect(parsed.scheduled_by).toEqual({ name: "Gus", email: "[email protected]" });
- });
-
- it("includes only description for calendar_event when scheduled_by is absent", () => {
- const task: Task = {
- ...makeTask("Do the standup", "calendar_event"),
- context: {
- event_id: "ce_1",
- datetime: "2026-04-17T09:00:00.000Z",
- is_recurring: false,
- repeat_interval: null,
- description: "Check PRs merged this week",
- },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("scheduled calendar event");
- expect(parsed.description).toBe("Check PRs merged this week");
- expect(parsed.scheduled_by).toBeUndefined();
- });
-
- it("includes only scheduled_by for calendar_event when description is absent", () => {
- const task: Task = {
- ...makeTask("Do the standup", "calendar_event"),
- context: {
- event_id: "ce_2",
- datetime: "2026-04-17T09:00:00.000Z",
- is_recurring: false,
- repeat_interval: null,
- scheduled_by: { name: "Gus", email: "[email protected]" },
- },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("scheduled calendar event");
- expect(parsed.description).toBeUndefined();
- expect(parsed.scheduled_by).toEqual({ name: "Gus", email: "[email protected]" });
- });
-
- it("omits description for calendar_event when description is empty string", () => {
- const task: Task = {
- ...makeTask("Do the standup", "calendar_event"),
- context: {
- event_id: "ce_3",
- datetime: "2026-04-17T09:00:00.000Z",
- is_recurring: false,
- repeat_interval: null,
- description: "",
- scheduled_by: { name: "Gus", email: "[email protected]" },
- },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("scheduled calendar event");
- expect(parsed.description).toBeUndefined();
- expect(parsed.scheduled_by).toEqual({ name: "Gus", email: "[email protected]" });
- });
-
- it("forwards is_recurring=false and repeat_interval=null for one-off calendar events", () => {
- const task: Task = {
- ...makeTask("One-off reminder", "calendar_event"),
- context: {
- event_id: "ce_4",
- datetime: "2026-05-01T14:00:00.000Z",
- is_recurring: false,
- repeat_interval: null,
- },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.event_id).toBe("ce_4");
- expect(parsed.datetime).toBe("2026-05-01T14:00:00.000Z");
- expect(parsed.is_recurring).toBe(false);
- expect(parsed.repeat_interval).toBeNull();
- });
-
- it("forwards is_recurring=true and repeat_interval for recurring calendar events", () => {
- const task: Task = {
- ...makeTask("Weekly sync", "calendar_event"),
- context: {
- event_id: "ce_5",
- datetime: "2026-05-05T10:00:00.000Z",
- is_recurring: true,
- repeat_interval: "1week",
- },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.event_id).toBe("ce_5");
- expect(parsed.datetime).toBe("2026-05-05T10:00:00.000Z");
- expect(parsed.is_recurring).toBe(true);
- expect(parsed.repeat_interval).toBe("1week");
- });
-
- it("includes email_id in prompt JSON when context has emailId", () => {
- const task: Task = {
- ...makeTask("New email from [email protected]: Hi", "email_notification"),
- context: { conversationType: "email_notification", emailId: "em_abc123" },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.email_id).toBe("em_abc123");
- });
-
- it("omits email_id when context has no emailId", () => {
- const task: Task = {
- ...makeTask("New email from [email protected]: Hi", "email_notification"),
- context: { conversationType: "email_notification" },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.email_id).toBeUndefined();
- });
-
- it("omits email_id when context is undefined", () => {
- const task = makeTask("New email from [email protected]: Hi", "email_notification");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.email_id).toBeUndefined();
- });
-
- it("omits email_id when emailId is null in context", () => {
- const task: Task = {
- ...makeTask("New email from [email protected]: Hi", "email_notification"),
- context: { conversationType: "email_notification", emailId: null },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.email_id).toBeUndefined();
- });
-
- it("includes message_id in DM prompt when context has it", () => {
- const task: Task = {
- ...makeTask("Fix the bug"),
- context: { message_id: "msg_abc123" },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.message_id).toBe("msg_abc123");
- });
-
- it("omits message_id for DM tasks without context", () => {
- const task = makeTask("Hello");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.message_id).toBeUndefined();
- });
-
- it("includes quoted_message in DM prompt when context has it", () => {
- const task: Task = {
- ...makeTask("Can you fix this?"),
- context: { quoted_message: { message_id: "msg_orig", excerpt: "The auth module has a bug" } },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.quoted_message).toEqual({ message_id: "msg_orig", excerpt: "The auth module has a bug" });
- });
-
- it("omits quoted_message for DM tasks without quote context", () => {
- const task = makeTask("Hello");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.quoted_message).toBeUndefined();
- });
-
- it("does not add notice for unknown task types", () => {
- const task = makeTask("Check inbox", "some_other_type");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toBeUndefined();
- });
-
- it("adds issue guidance for issue_event tasks", () => {
- const task = makeTask("Issue iss_1: Fix import", "issue_event");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("assigned issue");
- expect(parsed.notice).toContain("alook issue update");
- expect(parsed.notice).toContain("in_progress");
- });
-
- it("includes sender for DM tasks when sender is present", () => {
- const task: Task = {
- ...makeTask("Fix the login bug"),
- sender: { name: "Gus", email: "[email protected]", isOwner: true },
- };
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.sender).toEqual({ name: "Gus", email: "[email protected]", is_owner: true });
- });
-
- it("omits sender when sender is undefined", () => {
- const task = makeTask("Fix the bug");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.sender).toBeUndefined();
- });
-
- it("omits sender for email tasks (sender is not set)", () => {
- const task = makeTask("New email from [email protected]: Hi", "email_notification");
- const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toBeDefined();
- expect(parsed.sender).toBeUndefined();
- });
-});
-
-describe("buildTaskObject", () => {
- it("returns the same object that buildPrompt would JSON.stringify", () => {
- const task = makeTask("Fix bug");
- const obj = buildTaskObject(task);
- expect(JSON.stringify(obj)).toBe(buildPrompt(task));
- });
-
- it("includes attachments when provided", () => {
- const task = makeTask("Fix bug");
- const att = [{ path: "/tmp/a.txt", content_type: "text/plain", filename: "a.txt" }];
- const obj = buildTaskObject(task, att);
- expect(obj.attachments).toEqual([{ path: "/tmp/a.txt", content_type: "text/plain", filename: "a.txt" }]);
- });
-});
-
-describe("buildMergedPrompt", () => {
- it("wraps multiple sub-tasks in a merge_tasks envelope sorted by received_at", () => {
- const taskA: Task = { ...makeTask("DM message", "user_dm_message"), id: "tA", createdAt: "2026-06-03T12:00:02.000Z" };
- const taskB: Task = {
- ...makeTask("New email from X: subject", "email_notification"),
- id: "tB",
- createdAt: "2026-06-03T12:00:01.000Z",
- context: { emailId: "em_abc" },
- };
- const taskC: Task = { ...makeTask("Another DM", "user_dm_message"), id: "tC", createdAt: "2026-06-03T12:00:03.000Z" };
-
- const attMap = new Map<string, any[]>();
- attMap.set("tA", [{ path: "/tmp/a.txt", content_type: "text/plain", filename: "a.txt" }]);
-
- const result = JSON.parse(buildMergedPrompt([taskA, taskB, taskC], attMap));
-
- expect(result.type).toBe("merge_tasks");
- expect(result.notice).toContain("simultaneously");
- expect(result.tasks).toHaveLength(3);
- // Sorted by received_at ascending (B=12:00:01, A=12:00:02, C=12:00:03).
- expect(result.tasks[0].instruction).toBe("New email from X: subject");
- expect(result.tasks[0].email_id).toBe("em_abc");
- expect(result.tasks[1].instruction).toBe("DM message");
- expect(result.tasks[1].attachments).toHaveLength(1);
- expect(result.tasks[2].instruction).toBe("Another DM");
- });
-
- it("produces valid JSON with self-contained sub-tasks", () => {
- const task = makeTask("Single task", "user_dm_message");
- const result = JSON.parse(buildMergedPrompt([task], new Map()));
- expect(result.type).toBe("merge_tasks");
- expect(result.tasks).toHaveLength(1);
- expect(result.tasks[0].type).toBe("user_dm_message");
- expect(result.tasks[0].instruction).toBe("Single task");
- });
-});
diff --git a/src/cli/daemon/prompt.ts b/src/cli/daemon/prompt.ts
deleted file mode 100644
index f14176acd..000000000
--- a/src/cli/daemon/prompt.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import type { Task, Attachment } from "./types.js";
-import { localISOString } from "./execenv/timeline.js";
-
-const DM_RESPONSE_NOTICE =
- "Reply with `alook sync send-dm` — that's the only thing the user sees; your task output and reasoning are not shown." +
- " Talk to them at milestones like a colleague would, and don't end your turn without sending what they need." +
- " If this task will take more than 30 seconds, send a quick ack first so the user knows you're on it." +
- " IMPORTANT: If you were working on a previous task before this message arrived, do NOT silently drop it. After handling this message, return to any prior unfinished work and report the result to the user.";
-
-const EMAIL_NOTICE =
- "This task was triggered by an incoming email. Reply to the sender via email — use the email sending tool to respond." +
- " If you need more information or confirmation, email them and then exit." +
- " Do not wait — when they reply, a new task will be triggered automatically and you will be woken up with their response." +
- " IMPORTANT: Do not let this email interrupt any task you were previously working on. After handling this email, return to your original task and make sure it reaches completion.";
-
-const CALENDAR_NOTICE =
- "This task was triggered by a scheduled calendar event." +
- " If you need to communicate with someone, send an email using the email sending tool." +
- " If you need more information or confirmation, email them and then exit." +
- " Do not wait — when they reply, a new task will be triggered automatically and you will be woken up with their response.";
-
-const ISSUE_NOTICE =
- "This task was triggered by an assigned issue. The issue_id is provided in this message." +
- " Use `alook issue show --issue_id <issue_id>` to read full context." +
- " Use `alook issue update --issue_id <issue_id> --status <status>` to change status." +
- " Use `alook issue comment --issue_id <issue_id> --body <text>` to leave a comment." +
- " CRITICAL — You MUST manage the issue status correctly. This is NOT optional:" +
- " 1. Set status to 'in_progress' when you start working." +
- " 2. If you complete the work yourself: leave a summary comment, then set status to 'review' as your last action. 'review' means there is actual completed work (code, artifact, result) ready for the owner to look at." +
- " 3. If you delegated work to colleagues and are waiting for their response: KEEP status as 'in_progress' and exit. This is expected — you will be woken up when they reply. Set 'review' only after all delegated work is confirmed complete." +
- " 4. NEVER set 'review' unless there is concrete completed work for the owner to review. Sending a plan to a colleague is NOT completed work." +
- " NEVER exit without doing at least one of: updating the status, or leaving a comment explaining what you did and what you're waiting for.";
-
-function buildEmailDmNotice(name: string, email: string): string {
- return (
- `This task was triggered by an incoming email on a conversation with ${name} (${email}).` +
- ` ${name} is present in this session — reply to them directly.` +
- ` If you need to communicate with anyone else, use the email sending tool.` +
- ` IMPORTANT: Do not let this email interrupt any task you were previously working on. After handling this email, return to your original task and make sure it reaches completion — report the result to the user.`
- );
-}
-
-export function buildTaskObject(task: Task, attachments?: Attachment[]): Record<string, unknown> {
- const createdAt = new Date(task.createdAt);
- const receivedAt = Number.isNaN(createdAt.getTime())
- ? localISOString()
- : localISOString(createdAt);
- const obj: Record<string, unknown> = {
- type: task.type,
- received_at: receivedAt,
- instruction: task.prompt,
- };
- if (task.type === "user_dm_message") {
- obj.notice = DM_RESPONSE_NOTICE;
- const ctx = task.context as Record<string, unknown> | undefined;
- if (ctx?.message_id) {
- obj.message_id = ctx.message_id;
- }
- if (ctx?.quoted_message) {
- obj.quoted_message = ctx.quoted_message;
- }
- if (ctx?.conversation_history || ctx?.root_message) {
- obj.thread_context = {
- note: "The user started this thread by replying to the root_message below. The history is the conversation leading up to it.",
- ...(ctx.root_message ? { root_message: ctx.root_message } : {}),
- ...(ctx.conversation_history ? { history: ctx.conversation_history } : {}),
- };
- }
- }
- if (task.type === "email_notification") {
- const ctx = task.context as Record<string, unknown> | undefined;
- const dmUser = ctx?.dmUser as { name: string; email: string } | undefined;
- if (ctx?.conversationType === "user_dm_message" && dmUser) {
- obj.notice = buildEmailDmNotice(dmUser.name, dmUser.email);
- } else {
- obj.notice = EMAIL_NOTICE;
- }
- if (ctx?.emailId != null) {
- obj.email_id = ctx.emailId;
- }
- }
- if (task.type === "calendar_event") {
- obj.notice = CALENDAR_NOTICE;
- const ctx = task.context as Record<string, unknown> | undefined;
- if (ctx?.event_id != null) {
- obj.event_id = ctx.event_id;
- }
- if (ctx?.datetime != null) {
- obj.datetime = ctx.datetime;
- }
- if (ctx?.is_recurring !== undefined) {
- obj.is_recurring = ctx.is_recurring;
- }
- if (ctx?.repeat_interval !== undefined) {
- obj.repeat_interval = ctx.repeat_interval;
- }
- if (ctx?.description) {
- obj.description = ctx.description;
- }
- if (ctx?.scheduled_by) {
- obj.scheduled_by = ctx.scheduled_by;
- }
- }
- if (task.type === "issue_event") {
- obj.notice = ISSUE_NOTICE;
- const ctx = task.context as Record<string, unknown> | undefined;
- if (ctx?.issue_id) {
- obj.issue_id = ctx.issue_id;
- }
- }
- if (task.sender) {
- obj.sender = {
- name: task.sender.name,
- email: task.sender.email,
- is_owner: task.sender.isOwner,
- };
- }
- if (attachments && attachments.length > 0) {
- obj.attachments = attachments.map((a) => ({
- path: a.path,
- content_type: a.content_type,
- filename: a.filename,
- }));
- }
- return obj;
-}
-
-export function buildPrompt(task: Task, attachments?: Attachment[]): string {
- return JSON.stringify(buildTaskObject(task, attachments));
-}
-
-export function buildMergedPrompt(tasks: Task[], attachmentsMap: Map<string, Attachment[]>): string {
- const subTasks = tasks
- .map((t) => buildTaskObject(t, attachmentsMap.get(t.id)))
- .sort((a, b) => String(a.received_at).localeCompare(String(b.received_at)));
- return JSON.stringify({
- type: "merge_tasks",
- notice: "These messages arrived simultaneously. Process each one completely.",
- tasks: subTasks,
- });
-}
diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.ts
deleted file mode 100644
index 727428227..000000000
--- a/src/cli/daemon/session-runner.test.ts
+++ /dev/null
@@ -1,1626 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import path from "path";
-
-// --- Mocks ---
-
-const mockClientInstance = {
- completeTask: vi.fn(async () => ({})),
- failTask: vi.fn(async () => ({})),
- supersedeTask: vi.fn(async () => ({})),
- reportMessages: vi.fn(async () => ({})),
- getArtifactMeta: vi.fn(async () => ({ filename: "file.txt", content_type: "text/plain" })),
- downloadArtifact: vi.fn(async () => new ArrayBuffer(0)),
-};
-vi.mock("./client.js", () => {
- function MockDaemonClient() { return mockClientInstance; }
- return { DaemonClient: MockDaemonClient };
-});
-
-const mockPrepare = vi.fn(() => ({
- workDir: "/tmp/ws/ws1/agent1/workdir",
- timelineDir: "/tmp/ws/ws1/agent1/workdir/.context_timeline",
- env: {
- ALOOK_WORKSPACE_ID: "ws1",
- ALOOK_AGENT_ID: "agent1",
- ALOOK_TASK_ID: "t1",
- ALOOK_CONVERSATION_ID: "c1",
- ALOOK_HEALTH_PORT: "19514",
- },
-}));
-vi.mock("./execenv/index.js", () => ({
- prepare: (...args: any[]) => (mockPrepare as any)(...args),
-}));
-
-const mockInitEntryAsync = vi.fn(async () => {});
-const mockUpdateEntry = vi.fn();
-const mockCreateTimelineEntry = vi.fn(
- (
- taskId: string,
- prompt: string,
- type: string,
- sessionId?: string,
- pid?: number,
- provider?: string,
- contextKey?: string | null,
- detailedLog?: string | null,
- ) => ({
- task_id: taskId,
- context_key: contextKey ?? null,
- session_id: sessionId || null,
- pid: pid ?? null,
- status: "running",
- datetime: "2026-04-16T10:00:00-05:00",
- type,
- prompt,
- agent_responses: [],
- errmsg: null,
- provider: provider || null,
- detailed_log: detailedLog ?? null,
- }),
-);
-const mockFindResumableSessionByContextKey = vi.fn((): string | null => null);
-vi.mock("./execenv/timeline.js", () => ({
- initEntryAsync: (...args: any[]) => (mockInitEntryAsync as any)(...args),
- updateEntry: (...args: any[]) => (mockUpdateEntry as any)(...args),
- createTimelineEntry: (...args: any[]) => (mockCreateTimelineEntry as any)(...args),
- findResumableSessionByContextKey: (...args: any[]) => (mockFindResumableSessionByContextKey as any)(...args),
-}));
-
-const mockReadKillIntent = vi.fn((): any => null);
-const mockClearKillIntent = vi.fn();
-vi.mock("./execenv/steering.js", () => ({
- readKillIntent: (...args: any[]) => (mockReadKillIntent as any)(...args),
- clearKillIntent: (...args: any[]) => (mockClearKillIntent as any)(...args),
-}));
-
-// killProcessTree is exercised directly in kill-tree.test.ts. Here we stub it to
-// a synchronous group-SIGTERM so the handler tests can assert the kill via the
-// process.kill spy without waiting on the real SIGKILL grace loop.
-const mockKillProcessTree = vi.fn(async (pid: number) => {
- try { process.kill(-pid, "SIGTERM"); } catch { /* */ }
-});
-vi.mock("./kill-tree.js", () => ({
- killProcessTree: (...args: any[]) => (mockKillProcessTree as any)(...args),
- isAlive: vi.fn(() => false),
-}));
-
-vi.mock("./prompt.js", () => ({
- buildPrompt: vi.fn((task: any) => task.prompt),
-}));
-
-const mockBackendExecute = vi.fn();
-vi.mock("./agent/index.js", () => ({
- createBackend: vi.fn(() => ({
- name: "claude",
- execute: (...args: any[]) => mockBackendExecute(...args),
- })),
-}));
-
-vi.mock("../lib/logger.js", () => {
- const mockLog = { info: vi.fn(), error: vi.fn(), debug: vi.fn(), warn: vi.fn() };
- return { createLogger: () => mockLog, log: mockLog };
-});
-
-const mockMkdir = vi.fn(async () => undefined);
-const mockWriteFile = vi.fn(async () => undefined);
-const mockRename = vi.fn(async () => undefined);
-const mockRm = vi.fn(async () => undefined);
-vi.mock("fs/promises", () => ({
- mkdir: (...args: any[]) => (mockMkdir as any)(...args),
- writeFile: (...args: any[]) => (mockWriteFile as any)(...args),
- rename: (...args: any[]) => (mockRename as any)(...args),
- rm: (...args: any[]) => (mockRm as any)(...args),
- readdir: vi.fn(async () => []),
- readFile: vi.fn(async () => ""),
- unlink: vi.fn(async () => undefined),
- stat: vi.fn(async () => ({ mtimeMs: 0 })),
-}));
-
-import { runSession, writeMarkerFile, reportToServer, type MarkerData } from "./session-runner.js";
-import { createBackend } from "./agent/index.js";
-import { buildPrompt } from "./prompt.js";
-import { log as mockLog } from "../lib/logger.js";
-import type { SessionRunnerInput } from "./types.js";
-
-function makeInput(overrides?: Partial<SessionRunnerInput>): SessionRunnerInput {
- return {
- task: {
- id: "t1",
- agentId: "a1",
- runtimeId: "rt1",
- conversationId: "c1",
- workspaceId: "ws1",
- prompt: "do the thing",
- status: "dispatched",
- priority: 0,
- type: "user_dm_message",
- contextKey: "c1",
- createdAt: "2026-01-01T00:00:00Z",
- traceId: null,
- parentTaskId: null,
- channel: null,
- },
- provider: "claude",
- cliPath: "claude",
- model: "opus",
- serverURL: "http://localhost:8080",
- token: "test_token",
- workspacesRoot: "/tmp/ws",
- agentTimeout: 7200000,
- messageInactivityTimeout: 300000,
- ...overrides,
- };
-}
-
-function setupBackend(
- messages: any[],
- result: any,
- sessionId = "sess-1",
-) {
- mockBackendExecute.mockReturnValue({
- pid: 12345,
- messages: (async function* () {
- for (const msg of messages) yield msg;
- })(),
- sessionId: Promise.resolve(sessionId),
- result: Promise.resolve(result),
- });
-}
-
-describe("session-runner runSession", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("parses input, calls prepare, executes backend, and calls completeTask", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done!",
- error: "",
- durationMs: 1000,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- expect(mockPrepare).toHaveBeenCalledWith(
- { workspacesRoot: "/tmp/ws", token: "test_token" },
- expect.objectContaining({ id: "t1" }),
- );
- expect(createBackend).toHaveBeenCalledWith("claude", "claude");
- expect(mockBackendExecute).toHaveBeenCalledWith(
- "do the thing",
- expect.objectContaining({
- cwd: "/tmp/ws/ws1/agent1/workdir",
- model: "opus",
- timeout: 7200000,
- }),
- );
- expect(mockClientInstance.completeTask).toHaveBeenCalledWith(
- "test_token",
- "t1",
- expect.objectContaining({ output: "Done!", session_id: "sess-1" }),
- );
- });
-
- it("calls buildPrompt with task", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "s1",
- });
-
- await runSession(makeInput());
-
- expect(buildPrompt).toHaveBeenCalledWith(
- expect.objectContaining({ id: "t1", prompt: "do the thing" }),
- undefined,
- );
- });
-
- it("calls failTask on failed agent result", async () => {
- setupBackend([], {
- status: "failed",
- output: "",
- error: "something broke",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- expect(mockClientInstance.failTask).toHaveBeenCalledWith(
- "test_token",
- "t1",
- "something broke",
- );
- expect(mockClientInstance.completeTask).not.toHaveBeenCalled();
- });
-
- it("uses 'agent exited unexpectedly' when result.error is empty on failure", async () => {
- setupBackend([], {
- status: "failed",
- output: "",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- expect(mockClientInstance.failTask).toHaveBeenCalledWith(
- "test_token",
- "t1",
- "agent exited unexpectedly",
- );
- });
-
- it("writes timeline init entry with session runner PID (process.pid) and sessionId=undefined", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- expect(mockCreateTimelineEntry).toHaveBeenCalledWith(
- "t1",
- "do the thing",
- "user_dm_message",
- undefined,
- process.pid,
- "claude",
- "c1",
- undefined,
- );
- expect(mockInitEntryAsync).toHaveBeenCalledWith(
- "/tmp/ws/ws1/a1/workdir/.context_timeline",
- expect.objectContaining({ task_id: "t1", pid: process.pid, session_id: null }),
- );
- });
-
- it("updates timeline entry with session_id after agent starts", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- // The first updateEntry call should set session_id and mark the agent started.
- const firstCall = mockUpdateEntry.mock.calls[0];
- expect(firstCall[0]).toBe("/tmp/ws/ws1/a1/workdir/.context_timeline");
- expect(firstCall[1]).toBe("t1");
- const entry = { session_id: null as string | null, agent_started: undefined as boolean | undefined };
- firstCall[2](entry);
- expect(entry.session_id).toBe("sess-1");
- expect(entry.agent_started).toBe(true);
- });
-
- // TC13 — codex handshake failure: sessionId resolves to "" → agent_started NOT set.
- // The row then falls through to the staleness path rather than looking like a live agent.
- it("does not mark agent_started when sessionId resolves to an empty string", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "",
- }, "");
-
- await runSession(makeInput());
-
- const firstCall = mockUpdateEntry.mock.calls[0];
- const entry = { session_id: "stale" as string | null, agent_started: undefined as boolean | undefined };
- firstCall[2](entry);
- expect(entry.session_id).toBeNull();
- expect(entry.agent_started).toBeUndefined();
- });
-
- it("initEntryAsync is called with detailedLog from input.logFilePath", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput({ logFilePath: "/tmp/logs/t1.log" }));
-
- expect(mockCreateTimelineEntry).toHaveBeenCalledWith(
- "t1",
- "do the thing",
- "user_dm_message",
- undefined,
- process.pid,
- "claude",
- "c1",
- "/tmp/logs/t1.log",
- );
- });
-
- it("finalizes timeline on completion (status=completed, pid=null, session_id set)", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-2",
- });
-
- await runSession(makeInput());
-
- // Find the finalization call (last updateEntry)
- const calls = mockUpdateEntry.mock.calls;
- const lastCall = calls[calls.length - 1];
- const entry = {
- session_id: null as string | null,
- pid: process.pid as number | null,
- status: "running" as string,
- errmsg: null as string | null,
- agent_responses: [] as string[],
- };
- lastCall[2](entry);
- expect(entry.session_id).toBe("sess-2");
- expect(entry.pid).toBeNull();
- expect(entry.status).toBe("completed");
- });
-
- it("finalizes timeline on failure (status=failed, pid=null, errmsg set)", async () => {
- setupBackend([], {
- status: "failed",
- output: "",
- error: "kaboom",
- durationMs: 100,
- sessionId: "sess-3",
- });
-
- await runSession(makeInput());
-
- const calls = mockUpdateEntry.mock.calls;
- const lastCall = calls[calls.length - 1];
- const entry = {
- pid: process.pid as number | null,
- status: "running" as string,
- errmsg: null as string | null,
- agent_responses: [] as string[],
- };
- lastCall[2](entry);
- expect(entry.pid).toBeNull();
- expect(entry.status).toBe("failed");
- expect(entry.errmsg).toBe("kaboom");
- });
-
- it("text messages update timeline agent_responses array", async () => {
- setupBackend(
- [
- { type: "text", content: "Looking at code..." },
- { type: "tool-use", tool: "read", content: undefined },
- { type: "text", content: "Found the issue." },
- ],
- {
- status: "completed",
- output: "Fixed",
- error: "",
- durationMs: 2000,
- sessionId: "sess-1",
- },
- );
-
- await runSession(makeInput());
-
- const textCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
- const updater = call[2];
- const testEntry = { agent_responses: [] as string[] };
- updater(testEntry);
- return testEntry.agent_responses.length > 0;
- });
- expect(textCalls.length).toBe(2);
- });
-
- it("batches and flushes messages to server via reportMessages", async () => {
- const messages = Array.from({ length: 25 }, (_, i) => ({
- type: "text",
- content: `msg-${i}`,
- }));
-
- setupBackend(messages, {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- expect(mockClientInstance.reportMessages).toHaveBeenCalled();
- // Should have flushed at least once during the batch (at 20) + final flush
- const totalReported = mockClientInstance.reportMessages.mock.calls
- .flatMap((c: any[]) => c[2])
- .length;
- expect(totalReported).toBe(25);
- });
-
- it("uses findResumableSessionByContextKey and passes to backend for user_dm_message tasks", async () => {
- mockFindResumableSessionByContextKey.mockReturnValueOnce("prev-session-123");
-
- setupBackend([], {
- status: "completed",
- output: "Resumed",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- expect(mockFindResumableSessionByContextKey).toHaveBeenCalledWith(
- "/tmp/ws/ws1/a1/workdir/.context_timeline",
- "c1",
- "claude",
- );
- expect(mockBackendExecute).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({ resumeSessionId: "prev-session-123" }),
- );
- });
-
- it("skips findResumableSessionByContextKey for calendar_event tasks (no contextKey)", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-2",
- });
-
- await runSession(
- makeInput({
- task: {
- id: "t2",
- agentId: "a1",
- runtimeId: "rt1",
- conversationId: "c2",
- workspaceId: "ws1",
- prompt: "Run daily standup",
- status: "dispatched",
- priority: 0,
- type: "calendar_event",
- createdAt: "2026-04-17T09:00:00Z",
- traceId: null,
- parentTaskId: null,
- channel: null,
- },
- }),
- );
-
- expect(mockFindResumableSessionByContextKey).not.toHaveBeenCalled();
- expect(mockBackendExecute).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({ resumeSessionId: undefined }),
- );
- });
-
- it("writes timeline entries with task.type (calendar_event) for calendar tasks", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-3",
- });
-
- await runSession(
- makeInput({
- task: {
- id: "t3",
- agentId: "a1",
- runtimeId: "rt1",
- conversationId: "c3",
- workspaceId: "ws1",
- prompt: "scheduled work",
- status: "dispatched",
- priority: 0,
- type: "calendar_event",
- createdAt: "2026-04-17T09:00:00Z",
- traceId: null,
- parentTaskId: null,
- channel: null,
- },
- }),
- );
-
- // The 3rd positional arg to createTimelineEntry is the type.
- const typeArg = mockCreateTimelineEntry.mock.calls[0]![2];
- expect(typeArg).toBe("calendar_event");
- });
-
- it("passes branchName through to completeTask (forward-compat)", async () => {
- // branchName is currently always undefined in AgentResult
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- // completeTask should be called — branchName is not in the body since it's undefined
- const callBody = (mockClientInstance.completeTask.mock.calls as any)[0][2];
- expect(callBody.output).toBe("Done");
- expect(callBody.session_id).toBe("sess-1");
- // branch_name key should not be present (undefined values aren't serialized)
- expect(callBody.branch_name).toBeUndefined();
- });
-
- it("catches top-level errors and calls failTask before exiting", async () => {
- // Make prepare throw to simulate a crash before the agent starts
- mockPrepare.mockImplementationOnce(() => {
- throw new Error("disk full");
- });
-
- // runSession should throw, but the caller (main) wraps it in try/catch
- // Here we test that runSession itself propagates the error
- await expect(runSession(makeInput())).rejects.toThrow("disk full");
-
- // failTask should NOT have been called by runSession itself —
- // that's main()'s responsibility. But completeTask shouldn't have been called either.
- expect(mockClientInstance.completeTask).not.toHaveBeenCalled();
- });
-
- it("updates timeline to failed when attachment download fails", async () => {
- mockClientInstance.getArtifactMeta.mockRejectedValueOnce(new Error("network error"));
-
- await runSession(makeInput({
- task: {
- id: "t1",
- agentId: "a1",
- runtimeId: "rt1",
- conversationId: "c1",
- workspaceId: "ws1",
- prompt: "do the thing",
- status: "dispatched",
- priority: 0,
- type: "user_dm_message",
- contextKey: "c1",
- createdAt: "2026-01-01T00:00:00Z",
- traceId: null,
- parentTaskId: null,
- channel: null,
- context: { attachment_ids: ["art-1"] },
- },
- }));
-
- // Timeline entry should have been written immediately
- expect(mockInitEntryAsync).toHaveBeenCalled();
-
- // Timeline should be updated to "failed" on attachment download error
- const failCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
- const updater = call[2];
- const entry = { pid: 1, status: "running" as string, errmsg: null as string | null };
- updater(entry);
- return entry.status === "failed" && entry.errmsg?.includes("failed to download attachments");
- });
- expect(failCalls.length).toBe(1);
-
- // failTask should have been called
- expect(mockClientInstance.failTask).toHaveBeenCalledWith(
- "test_token",
- "t1",
- expect.stringContaining("failed to download attachments"),
- );
-
- // Agent should NOT have been started
- expect(mockBackendExecute).not.toHaveBeenCalled();
- });
-
- it("SIGTERM during setup phase (before agent starts) cleans up properly", async () => {
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
-
- // Make downloadAttachments hang so SIGTERM fires during setup
- let resolveDownload: (() => void) | null = null;
- mockClientInstance.getArtifactMeta.mockImplementation(async () => {
- await new Promise<void>((resolve) => { resolveDownload = resolve; });
- return { filename: "file.txt", content_type: "text/plain" };
- });
-
- const sessionPromise = runSession(makeInput({
- task: {
- id: "t1",
- agentId: "a1",
- runtimeId: "rt1",
- conversationId: "c1",
- workspaceId: "ws1",
- prompt: "do the thing",
- status: "dispatched",
- priority: 0,
- type: "user_dm_message",
- contextKey: "c1",
- createdAt: "2026-01-01T00:00:00Z",
- traceId: null,
- parentTaskId: null,
- channel: null,
- context: { attachment_ids: ["art-1"] },
- },
- }));
-
- // Wait for initEntryAsync to complete and signal handler to be registered
- await new Promise((r) => setTimeout(r, 50));
-
- // Fire SIGTERM during attachment download (before agent starts)
- process.emit("SIGTERM", "SIGTERM");
-
- // Unblock the download so the promise can settle
- if (resolveDownload) (resolveDownload as () => void)();
-
- await new Promise((r) => setTimeout(r, 50));
-
- // Timeline should be updated (killed or cancelled depending on intent)
- const killCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
- const updater = call[2];
- const entry = { pid: 1, status: "running" as string, errmsg: null as string | null };
- updater(entry);
- return entry.status === "killed";
- });
- expect(killCalls.length).toBe(1);
-
- // Should have called process.exit(1)
- expect(exitSpy).toHaveBeenCalledWith(1);
-
- // TC5: agent not yet spawned, so no process-tree kill is attempted.
- expect(mockKillProcessTree).not.toHaveBeenCalled();
-
- exitSpy.mockRestore();
- });
-
- it("TC7: SIGTERM during sessionId negotiation reaps the freshly-spawned agent", async () => {
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
-
- const agentPid = 55555;
- // sessionId never resolves on its own — the kill lands while we await it,
- // after backend.execute() has already returned a live pid.
- mockBackendExecute.mockReturnValue({
- pid: agentPid,
- messages: (async function* () { await new Promise<void>(() => {}); })(),
- sessionId: new Promise<string>(() => {}),
- result: new Promise(() => {}),
- });
-
- const sessionPromise = runSession(makeInput());
- // Let execution reach the `await session.sessionId` suspension point.
- await new Promise((r) => setTimeout(r, 50));
-
- process.emit("SIGTERM", "SIGTERM");
- await new Promise((r) => setTimeout(r, 50));
-
- // The inner agent that was spawned must be reaped, not orphaned.
- expect(mockKillProcessTree).toHaveBeenCalledWith(agentPid);
- expect(exitSpy).toHaveBeenCalledWith(1);
-
- exitSpy.mockRestore();
- void sessionPromise;
- });
-
- it("gracefully cleans up on SIGTERM: kills agent, updates timeline to killed, calls failTask", async () => {
- // Mock process.kill to track calls
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
- // Mock process.exit to prevent test process from actually exiting
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
-
- // Create a backend that yields messages with a pause in the middle
- // so we can fire SIGTERM during execution
- let resolveMessage: (() => void) | null = null;
- const agentPid = 99999;
-
- mockBackendExecute.mockReturnValue({
- pid: agentPid,
- messages: (async function* () {
- yield { type: "text", content: "working..." };
- // Pause — signal will fire here
- await new Promise<void>((resolve) => { resolveMessage = resolve; });
- yield { type: "text", content: "should not reach" };
- })(),
- sessionId: Promise.resolve("sess-kill"),
- result: new Promise(() => {}), // never resolves (agent is killed)
- });
-
- const sessionPromise = runSession(makeInput());
-
- // Wait for the first message to be processed
- await new Promise((r) => setTimeout(r, 50));
-
- // Fire SIGTERM
- process.emit("SIGTERM", "SIGTERM");
-
- // Unblock the message iterator so runSession can finish
- if (resolveMessage) (resolveMessage as () => void)();
-
- // Wait for cleanup to finish
- await new Promise((r) => setTimeout(r, 50));
-
- // 1. Should have reaped the inner agent's process group
- expect(mockKillProcessTree).toHaveBeenCalledWith(agentPid);
-
- // 2. Timeline should be updated to "killed"
- const killCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
- const updater = call[2];
- const entry = { pid: 1, status: "running" as string, errmsg: null as string | null, agent_responses: [] as string[] };
- updater(entry);
- return entry.status === "killed";
- });
- expect(killCalls.length).toBe(1);
-
- // 3. Should have called failTask with "killed by signal"
- expect(mockClientInstance.failTask).toHaveBeenCalledWith(
- "test_token",
- "t1",
- "killed by signal",
- );
-
- // 4. Should have called process.exit(1)
- expect(exitSpy).toHaveBeenCalledWith(1);
-
- // Cleanup
- killSpy.mockRestore();
- exitSpy.mockRestore();
- });
-
- it("signal handler cleans up listeners after normal completion", async () => {
- const listenersBefore = process.listenerCount("SIGTERM");
-
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- // After normal completion, signal listeners should be removed
- expect(process.listenerCount("SIGTERM")).toBe(listenersBefore);
- });
-
- it("passes provider to createTimelineEntry", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput({ provider: "codex" }));
-
- expect(mockCreateTimelineEntry).toHaveBeenCalledWith(
- "t1",
- "do the thing",
- "user_dm_message",
- undefined,
- process.pid,
- "codex",
- "c1",
- undefined,
- );
- });
-
- it("passes provider to findResumableSessionByContextKey", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput({ provider: "codex" }));
-
- expect(mockFindResumableSessionByContextKey).toHaveBeenCalledWith(
- "/tmp/ws/ws1/a1/workdir/.context_timeline",
- "c1",
- "codex",
- );
- });
-
- it("session resume works when findResumableSessionByContextKey returns a session for matching provider", async () => {
- mockFindResumableSessionByContextKey.mockReturnValueOnce("prev-sess-codex");
-
- setupBackend([], {
- status: "completed",
- output: "Resumed",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput({ provider: "codex" }));
-
- expect(mockBackendExecute).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({ resumeSessionId: "prev-sess-codex" }),
- );
- });
-
- it("session starts fresh when provider has no matching prior entry", async () => {
- mockFindResumableSessionByContextKey.mockReturnValueOnce(null);
-
- setupBackend([], {
- status: "completed",
- output: "Fresh",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput({ provider: "opencode" }));
-
- expect(mockFindResumableSessionByContextKey).toHaveBeenCalledWith(
- "/tmp/ws/ws1/a1/workdir/.context_timeline",
- "c1",
- "opencode",
- );
- expect(mockBackendExecute).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({ resumeSessionId: undefined }),
- );
- });
-
- // --- Logging tests ---
-
- describe("logging", () => {
- it("logs task start with metadata", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 1000,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- expect(mockLog.info).toHaveBeenCalledWith(
- "starting (task=t1, type=user_dm_message, agent=a1, provider=claude, model=opus)",
- );
- });
-
- it("logs agent started with PID and session ID", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 1000,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- expect(mockLog.info).toHaveBeenCalledWith(
- "agent started (pid=12345, session=sess-1)",
- );
- });
-
- it("logs user prompt with role=user", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 1000,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- expect(mockLog.info).toHaveBeenCalledWith(
- JSON.stringify({ role: "user", type: "text", content: "do the thing" }),
- );
- });
-
- it("logs each agent message with role=assistant", async () => {
- const msg = { type: "text", content: "hello world" };
- setupBackend(
- [msg],
- {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 1000,
- sessionId: "sess-1",
- },
- );
-
- await runSession(makeInput());
-
- expect(mockLog.info).toHaveBeenCalledWith(
- JSON.stringify({ role: "assistant", ...msg }),
- );
- });
-
- it("logs tool-use messages with role=assistant and counts tools", async () => {
- const messages = [
- { type: "tool-use", tool: "Read", callId: "c1", input: { file_path: "a.ts" } },
- { type: "tool-result", tool: "Read", callId: "c1", output: "ok" },
- { type: "tool-use", tool: "Edit", callId: "c2", input: { file_path: "a.ts" } },
- { type: "tool-result", tool: "Edit", callId: "c2", output: "ok" },
- ];
- setupBackend(messages, {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 5400,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput());
-
- for (const msg of messages) {
- expect(mockLog.info).toHaveBeenCalledWith(
- JSON.stringify({ role: "assistant", ...msg }),
- );
- }
- expect(mockLog.info).toHaveBeenCalledWith(
- "completed (duration=5.4s, messages=4, tools=2)",
- );
- });
-
- it("logs completion with duration, message count, and tool count", async () => {
- setupBackend(
- [
- { type: "text", content: "thinking..." },
- { type: "tool-use", tool: "Read", callId: "c1", input: { file_path: "a.ts" } },
- { type: "tool-result", tool: "Read", callId: "c1", output: "ok" },
- ],
- {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 5400,
- sessionId: "sess-1",
- },
- );
-
- await runSession(makeInput());
-
- expect(mockLog.info).toHaveBeenCalledWith(
- "completed (duration=5.4s, messages=3, tools=1)",
- );
- });
-
- it("logs failure with duration, message count, tool count, and error", async () => {
- setupBackend(
- [
- { type: "tool-use", tool: "Bash", callId: "c1", input: { command: "exit 1" } },
- { type: "tool-result", tool: "Bash", callId: "c1", output: "err" },
- ],
- {
- status: "failed",
- output: "",
- error: "command failed",
- durationMs: 1200,
- sessionId: "sess-1",
- },
- );
-
- await runSession(makeInput());
-
- expect(mockLog.info).toHaveBeenCalledWith(
- "failed (duration=1.2s, messages=2, tools=1) — command failed",
- );
- });
-
- it("logs kill with message count and tool count", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
-
- let resolveMessage: (() => void) | null = null;
-
- mockBackendExecute.mockReturnValue({
- pid: 99999,
- messages: (async function* () {
- yield { type: "tool-use", tool: "Read", callId: "c1", input: { file_path: "x.ts" } };
- yield { type: "tool-result", tool: "Read", callId: "c1", output: "ok" };
- yield { type: "text", content: "working..." };
- await new Promise<void>((resolve) => { resolveMessage = resolve; });
- })(),
- sessionId: Promise.resolve("sess-kill"),
- result: new Promise(() => {}),
- });
-
- const sessionPromise = runSession(makeInput());
- await new Promise((r) => setTimeout(r, 50));
-
- process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) (resolveMessage as () => void)();
- await new Promise((r) => setTimeout(r, 50));
-
- expect(mockLog.info).toHaveBeenCalledWith(
- "killed by signal (messages=3, tools=1)",
- );
-
- killSpy.mockRestore();
- exitSpy.mockRestore();
- });
-
- it("logs 'default' when model is empty", async () => {
- setupBackend([], {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- await runSession(makeInput({ model: "" }));
-
- expect(mockLog.info).toHaveBeenCalledWith(
- expect.stringContaining("model=default"),
- );
- });
-
- it("truncates tool-result output longer than 500 chars in log", async () => {
- const longOutput = "x".repeat(1000);
- setupBackend(
- [
- { type: "tool-result", tool: "Read", callId: "c1", output: longOutput },
- ],
- {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- },
- );
-
- await runSession(makeInput());
-
- const logCalls = (mockLog.info as any).mock.calls.map((c: any[]) => c[0] as string);
- const toolResultLog = logCalls.find((s: string) => s.includes('"type":"tool-result"'));
- expect(toolResultLog).toBeDefined();
-
- const parsed = JSON.parse(toolResultLog!);
- expect(parsed.output).toBe("x".repeat(500) + "... (1000 chars)");
- });
-
- it("does not truncate tool-result output under 500 chars in log", async () => {
- const shortOutput = "x".repeat(200);
- setupBackend(
- [
- { type: "tool-result", tool: "Read", callId: "c1", output: shortOutput },
- ],
- {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- },
- );
-
- await runSession(makeInput());
-
- const logCalls = (mockLog.info as any).mock.calls.map((c: any[]) => c[0] as string);
- const toolResultLog = logCalls.find((s: string) => s.includes('"type":"tool-result"'));
- expect(toolResultLog).toBeDefined();
-
- const parsed = JSON.parse(toolResultLog!);
- expect(parsed.output).toBe(shortOutput);
- });
- });
-
- describe("kill-intent handling", () => {
- it("on SIGTERM with superseded intent: marks timeline superseded and calls supersedeTask", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
-
- mockReadKillIntent.mockReturnValueOnce({
- reason: "superseded",
- targetTaskId: "t1",
- expectedPid: process.pid,
- successorTaskId: "t_new",
- });
-
- let resolveMessage: (() => void) | null = null;
- mockBackendExecute.mockReturnValue({
- pid: 99999,
- messages: (async function* () {
- yield { type: "text", content: "working..." };
- await new Promise<void>((resolve) => { resolveMessage = resolve; });
- })(),
- sessionId: Promise.resolve("sess-sup"),
- result: new Promise(() => {}),
- });
-
- const sessionPromise = runSession(makeInput());
- await new Promise((r) => setTimeout(r, 50));
-
- process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) (resolveMessage as () => void)();
- await new Promise((r) => setTimeout(r, 50));
-
- // Timeline should be updated to "superseded"
- const supersedeCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
- const updater = call[2];
- const entry = { pid: 1, status: "running" as string, errmsg: null as string | null, agent_responses: [] as string[], successor_task_id: null as string | null, supersede_reason: null as string | null };
- updater(entry);
- return entry.status === "superseded";
- });
- expect(supersedeCalls.length).toBe(1);
-
- // Should call supersedeTask, not failTask
- expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("test_token", "t1");
- expect(mockClientInstance.failTask).not.toHaveBeenCalled();
-
- // Should clear the intent
- expect(mockClearKillIntent).toHaveBeenCalled();
-
- killSpy.mockRestore();
- exitSpy.mockRestore();
- });
-
- it("on SIGTERM with cancelled intent: marks timeline cancelled and calls failTask", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
-
- mockReadKillIntent.mockReturnValueOnce({
- reason: "cancelled",
- targetTaskId: "t1",
- expectedPid: process.pid,
- });
-
- let resolveMessage: (() => void) | null = null;
- mockBackendExecute.mockReturnValue({
- pid: 99999,
- messages: (async function* () {
- yield { type: "text", content: "working..." };
- await new Promise<void>((resolve) => { resolveMessage = resolve; });
- })(),
- sessionId: Promise.resolve("sess-cancel"),
- result: new Promise(() => {}),
- });
-
- const sessionPromise = runSession(makeInput());
- await new Promise((r) => setTimeout(r, 50));
-
- process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) (resolveMessage as () => void)();
- await new Promise((r) => setTimeout(r, 50));
-
- // Timeline should be updated to "cancelled" (not "killed")
- const cancelCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
- const updater = call[2];
- const entry = { pid: 1, status: "running" as string, errmsg: null as string | null, agent_responses: [] as string[] };
- updater(entry);
- return entry.status === "cancelled";
- });
- expect(cancelCalls.length).toBe(1);
-
- // Should call failTask with "cancelled by user"
- expect(mockClientInstance.failTask).toHaveBeenCalledWith("test_token", "t1", "cancelled by user");
- expect(mockClientInstance.supersedeTask).not.toHaveBeenCalled();
-
- killSpy.mockRestore();
- exitSpy.mockRestore();
- });
-
- it("on SIGTERM without kill-intent file: preserves existing killed behavior", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
-
- mockReadKillIntent.mockReturnValueOnce(null);
-
- let resolveMessage: (() => void) | null = null;
- mockBackendExecute.mockReturnValue({
- pid: 99999,
- messages: (async function* () {
- yield { type: "text", content: "working..." };
- await new Promise<void>((resolve) => { resolveMessage = resolve; });
- })(),
- sessionId: Promise.resolve("sess-kill"),
- result: new Promise(() => {}),
- });
-
- const sessionPromise = runSession(makeInput());
- await new Promise((r) => setTimeout(r, 50));
-
- process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) (resolveMessage as () => void)();
- await new Promise((r) => setTimeout(r, 50));
-
- // Timeline should be updated to "killed" (original behavior)
- const killCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
- const updater = call[2];
- const entry = { pid: 1, status: "running" as string, errmsg: null as string | null, agent_responses: [] as string[] };
- updater(entry);
- return entry.status === "killed";
- });
- expect(killCalls.length).toBe(1);
-
- // Should call failTask with "killed by signal"
- expect(mockClientInstance.failTask).toHaveBeenCalledWith("test_token", "t1", "killed by signal");
- expect(mockClientInstance.supersedeTask).not.toHaveBeenCalled();
-
- killSpy.mockRestore();
- exitSpy.mockRestore();
- });
- });
-});
-
-describe("writeMarkerFile", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- const marker: MarkerData = {
- taskId: "t1",
- type: "complete",
- payload: { output: "Done!", session_id: "sess-1" },
- token: "tok",
- serverURL: "http://localhost",
- createdAt: "2026-04-20T21:00:00Z",
- };
-
- it("writes marker with correct JSON structure", async () => {
- await writeMarkerFile("/tmp/ws", marker);
-
- expect(mockMkdir).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions"), { recursive: true, mode: 0o700 });
- expect(mockWriteFile).toHaveBeenCalledWith(
- path.join("/tmp", "ws", ".pending_completions", "t1.tmp"),
- JSON.stringify(marker),
- { mode: 0o600 },
- );
- expect(mockRename).toHaveBeenCalledWith(
- path.join("/tmp", "ws", ".pending_completions", "t1.tmp"),
- path.join("/tmp", "ws", ".pending_completions", "t1.json"),
- );
- });
-
- it("creates .pending_completions/ directory if missing", async () => {
- await writeMarkerFile("/tmp/ws", marker);
- expect(mockMkdir).toHaveBeenCalledWith(path.join("/tmp", "ws", ".pending_completions"), { recursive: true, mode: 0o700 });
- });
-
- it("works when directory already exists", async () => {
- await writeMarkerFile("/tmp/ws", marker);
- await writeMarkerFile("/tmp/ws", { ...marker, taskId: "t2" });
- expect(mockMkdir).toHaveBeenCalledTimes(2);
- expect(mockWriteFile).toHaveBeenCalledTimes(2);
- });
-
- it("atomic write: uses .tmp then renames to .json", async () => {
- await writeMarkerFile("/tmp/ws", marker);
- const writeCall = (mockWriteFile.mock.calls as any)[0][0];
- const renameArgs = (mockRename.mock.calls as any)[0];
- expect(writeCall).toContain(".tmp");
- expect(renameArgs[0]).toContain(".tmp");
- expect(renameArgs[1]).toContain(".json");
- });
-
- it("write failure propagates", async () => {
- mockWriteFile.mockRejectedValueOnce(new Error("ENOSPC"));
- await expect(writeMarkerFile("/tmp/ws", marker)).rejects.toThrow("ENOSPC");
- });
-});
-
-describe("reportToServer", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- const marker: MarkerData = {
- taskId: "t1",
- type: "complete",
- payload: { output: "Done!" },
- token: "tok",
- serverURL: "http://localhost",
- createdAt: "2026-04-20T21:00:00Z",
- };
-
- it("succeeds without writing marker", async () => {
- await reportToServer(async () => ({}), marker, "/tmp/ws");
- expect(mockWriteFile).not.toHaveBeenCalled();
- });
-
- it("writes marker on fn failure", async () => {
- const promise = reportToServer(async () => { throw new Error("network"); }, marker, "/tmp/ws");
- await vi.runAllTimersAsync();
- await promise;
- expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
- expect(written.taskId).toBe("t1");
- expect(written.type).toBe("complete");
- });
-
- it("does not throw when fn fails", async () => {
- const promise = reportToServer(async () => { throw new Error("network"); }, marker, "/tmp/ws");
- await vi.runAllTimersAsync();
- await expect(promise).resolves.toBeUndefined();
- });
-
- it("does not throw when both fn and marker write fail", async () => {
- mockWriteFile.mockRejectedValueOnce(new Error("ENOSPC"));
- const promise = reportToServer(async () => { throw new Error("network"); }, marker, "/tmp/ws");
- await vi.runAllTimersAsync();
- await expect(promise).resolves.toBeUndefined();
- });
-
- it("does not retry on HTTP 4xx (client error)", async () => {
- await reportToServer(async () => { throw new Error("HTTP 400: bad request"); }, marker, "/tmp/ws");
- expect(mockWriteFile).not.toHaveBeenCalled();
- });
-
- it("retries on retryable error and succeeds on 2nd attempt", async () => {
- let attempt = 0;
- const fn = async () => {
- attempt++;
- if (attempt === 1) throw new Error("ECONNREFUSED");
- };
- const promise = reportToServer(fn, marker, "/tmp/ws");
- await vi.runAllTimersAsync();
- await promise;
- expect(attempt).toBe(2);
- expect(mockWriteFile).not.toHaveBeenCalled();
- });
-});
-
-describe("session-runner marker integration", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("completeTask failure writes 'complete' marker", async () => {
- mockClientInstance.completeTask.mockRejectedValue(new Error("server down"));
- setupBackend([], {
- status: "completed",
- output: "Done!",
- error: "",
- durationMs: 1000,
- sessionId: "sess-1",
- });
-
- const promise = runSession(makeInput());
- await vi.runAllTimersAsync();
- await promise;
-
- expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
- expect(written.type).toBe("complete");
- expect(written.taskId).toBe("t1");
- expect(written.payload.output).toBe("Done!");
- mockClientInstance.completeTask.mockResolvedValue({});
- });
-
- it("failTask failure writes 'fail' marker", async () => {
- mockClientInstance.failTask.mockRejectedValue(new Error("server down"));
- setupBackend([], {
- status: "failed",
- output: "",
- error: "something broke",
- durationMs: 100,
- sessionId: "sess-1",
- });
-
- const promise = runSession(makeInput());
- await vi.runAllTimersAsync();
- await promise;
-
- expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
- expect(written.type).toBe("fail");
- expect(written.taskId).toBe("t1");
- expect(written.payload.error).toBe("something broke");
- mockClientInstance.failTask.mockResolvedValue({});
- });
-
- it("onKill cancel writes marker on failure", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
- mockClientInstance.failTask.mockRejectedValue(new Error("server down"));
- mockReadKillIntent.mockReturnValueOnce({ reason: "cancelled", targetTaskId: "t1", expectedPid: process.pid });
-
- let resolveMessage: (() => void) | null = null;
- mockBackendExecute.mockReturnValue({
- pid: 99999,
- messages: (async function* () {
- yield { type: "text", content: "working..." };
- await new Promise<void>((resolve) => { resolveMessage = resolve; });
- })(),
- sessionId: Promise.resolve("sess-cancel"),
- result: new Promise(() => {}),
- });
-
- const sessionPromise = runSession(makeInput());
- await vi.advanceTimersByTimeAsync(50);
- process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) (resolveMessage as () => void)();
- await vi.runAllTimersAsync();
-
- expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
- expect(written.type).toBe("fail");
- expect(written.payload.error).toBe("cancelled by user");
-
- killSpy.mockRestore();
- exitSpy.mockRestore();
- mockClientInstance.failTask.mockResolvedValue({});
- });
-
- it("onKill kill writes marker on failure", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
- mockClientInstance.failTask.mockRejectedValue(new Error("server down"));
- mockReadKillIntent.mockReturnValueOnce(null);
-
- let resolveMessage: (() => void) | null = null;
- mockBackendExecute.mockReturnValue({
- pid: 99999,
- messages: (async function* () {
- yield { type: "text", content: "working..." };
- await new Promise<void>((resolve) => { resolveMessage = resolve; });
- })(),
- sessionId: Promise.resolve("sess-kill"),
- result: new Promise(() => {}),
- });
-
- const sessionPromise = runSession(makeInput());
- await vi.advanceTimersByTimeAsync(50);
- process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) (resolveMessage as () => void)();
- await vi.runAllTimersAsync();
-
- expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
- expect(written.type).toBe("fail");
- expect(written.payload.error).toBe("killed by signal");
-
- killSpy.mockRestore();
- exitSpy.mockRestore();
- mockClientInstance.failTask.mockResolvedValue({});
- });
-});
-
-describe("message inactivity timeout", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("kills agent and fails task when no messages arrive within timeout", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
-
- const agentPid = 88888;
- mockBackendExecute.mockReturnValue({
- pid: agentPid,
- messages: (async function* () {
- yield { type: "text", content: "first message" };
- // Hang forever — simulating a stuck agent
- await new Promise<void>(() => {});
- })(),
- sessionId: Promise.resolve("sess-hang"),
- result: new Promise<any>((resolve) => {
- // Resolve when the agent group is signalled (proc close after SIGTERM).
- const interval = setInterval(() => {
- if (killSpy.mock.calls.some((c) => c[0] === -agentPid)) {
- clearInterval(interval);
- resolve({
- status: "timeout",
- output: "",
- error: "",
- durationMs: 5000,
- sessionId: "sess-hang",
- });
- }
- }, 10);
- }),
- });
-
- // Use a very short inactivity timeout (100ms) for the test
- await runSession(makeInput({ messageInactivityTimeout: 100 }));
-
- // Should have reaped the hung agent's process group
- expect(mockKillProcessTree).toHaveBeenCalledWith(agentPid);
-
- // Should have failed the task with inactivity timeout error
- expect(mockClientInstance.failTask).toHaveBeenCalledWith(
- "test_token",
- "t1",
- "message inactivity timeout (no messages for 0.1s)",
- );
- expect(mockClientInstance.completeTask).not.toHaveBeenCalled();
-
- // Timeline should show failure
- const failCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
- const updater = call[2];
- const entry = { pid: 1, status: "running" as string, errmsg: null as string | null, agent_responses: [] as string[] };
- updater(entry);
- return entry.status === "failed" && entry.errmsg?.includes("inactivity");
- });
- expect(failCalls.length).toBe(1);
-
- killSpy.mockRestore();
- });
-
- it("kills agent when it hangs immediately with zero messages", async () => {
- const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
-
- const agentPid = 77777;
- mockBackendExecute.mockReturnValue({
- pid: agentPid,
- messages: (async function* () {
- // Hang forever from the start — no messages at all
- await new Promise<void>(() => {});
- })(),
- sessionId: Promise.resolve("sess-zero"),
- result: new Promise<any>((resolve) => {
- const interval = setInterval(() => {
- if (killSpy.mock.calls.some((c) => c[0] === -agentPid)) {
- clearInterval(interval);
- resolve({
- status: "timeout",
- output: "",
- error: "",
- durationMs: 100,
- sessionId: "sess-zero",
- });
- }
- }, 10);
- }),
- });
-
- await runSession(makeInput({ messageInactivityTimeout: 100 }));
-
- expect(mockKillProcessTree).toHaveBeenCalledWith(agentPid);
- expect(mockClientInstance.failTask).toHaveBeenCalledWith(
- "test_token",
- "t1",
- "message inactivity timeout (no messages for 0.1s)",
- );
-
- killSpy.mockRestore();
- });
-
- it("does not timeout when messages keep flowing", async () => {
- setupBackend(
- [
- { type: "text", content: "msg 1" },
- { type: "text", content: "msg 2" },
- { type: "text", content: "msg 3" },
- ],
- {
- status: "completed",
- output: "Done",
- error: "",
- durationMs: 100,
- sessionId: "sess-1",
- },
- );
-
- // Short timeout — but messages arrive instantly so no timeout
- await runSession(makeInput({ messageInactivityTimeout: 100 }));
-
- expect(mockClientInstance.completeTask).toHaveBeenCalled();
- expect(mockClientInstance.failTask).not.toHaveBeenCalled();
- });
-});
diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.ts
deleted file mode 100644
index c3623efa4..000000000
--- a/src/cli/daemon/session-runner.ts
+++ /dev/null
@@ -1,878 +0,0 @@
-/**
- * Session Runner — standalone process that executes a single agent task.
- *
- * Spawned by the daemon as a detached child (`spawn('bun', ['run', thisFile, base64Input])`).
- * Survives daemon restarts: owns the full lifecycle of message syncing, timeline writes,
- * log capture, and server completion reporting.
- */
-
-import { mkdir, writeFile, rm, rename } from "fs/promises";
-import { mkdirSync } from "fs";
-import path from "path";
-import { DaemonClient } from "./client.js";
-import { createBackend } from "./agent/index.js";
-import { prepare } from "./execenv/index.js";
-import {
- initEntryAsync,
- updateEntry,
- createTimelineEntry,
- findResumableSessionByContextKey,
-} from "./execenv/timeline.js";
-import { readKillIntent, clearKillIntent } from "./execenv/steering.js";
-import { watchInbox, writeAck, writeNack, cleanupInboxFile, cleanupSteeringDir, type MailboxWatcher } from "./steering/mailbox.js";
-import { RuntimeTurnState } from "./steering/turnState.js";
-import {
- createInitialApmState,
- reduceApmGatedToolUse,
- reduceApmGatedCompaction,
- reduceApmGatedEnqueue,
- reduceApmGatedTurnEnd,
- reduceApmGatedError,
- reduceApmGatedFlushReadiness,
- reduceApmGatedRecentEvent,
- reduceApmStalledRecoveryTermination,
- reduceApmStartupTimeoutTermination,
-} from "./steering/apmStateMachine.js";
-import { RuntimeNotificationState } from "./steering/notificationState.js";
-import { RuntimeProgressState } from "./steering/progressState.js";
-import { classifyRuntimeError, scrubDiagnosticText } from "./steering/errorDiagnostics.js";
-import { killProcessTree } from "./kill-tree.js";
-import { buildPrompt } from "./prompt.js";
-import { createLogger } from "../lib/logger.js";
-
-const log = createLogger({ module: "session-runner" });
-import { tempDir } from "../lib/platform.js";
-import type { SessionRunnerInput, Attachment } from "./types.js";
-
-const ATTACHMENTS_BASE = tempDir("alook-attachments");
-
-// --- Marker file support for resilient server reporting ---
-
-export type MarkerData =
- | {
- taskId: string;
- type: "complete";
- payload: { output: string; session_id?: string; branch_name?: string };
- token: string;
- serverURL: string;
- createdAt: string;
- }
- | {
- taskId: string;
- type: "fail";
- payload: { error: string };
- token: string;
- serverURL: string;
- createdAt: string;
- };
-
-export async function writeMarkerFile(
- workspacesRoot: string,
- marker: MarkerData,
-): Promise<void> {
- const dir = path.join(workspacesRoot, ".pending_completions");
- await mkdir(dir, { recursive: true, mode: 0o700 });
- const tmpPath = path.join(dir, `${marker.taskId}.tmp`);
- const finalPath = path.join(dir, `${marker.taskId}.json`);
- await writeFile(tmpPath, JSON.stringify(marker), { mode: 0o600 });
- await rename(tmpPath, finalPath);
-}
-
-function isRetryableError(e: unknown): boolean {
- if (!(e instanceof Error)) return true;
- const msg = e.message;
- if (/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|EAI_AGAIN/.test(msg)) return true;
- const httpMatch = msg.match(/^HTTP (\d+):/);
- if (httpMatch) {
- const status = Number(httpMatch[1]);
- if (status >= 500) return true;
- if (status === 408 || status === 429) return true;
- return false;
- }
- return true;
-}
-
-function isClientError(e: unknown): boolean {
- if (!(e instanceof Error)) return false;
- const match = e.message.match(/^HTTP (\d+):/);
- if (!match) return false;
- const status = Number(match[1]);
- if (status === 408 || status === 429) return false;
- return status >= 400 && status < 500;
-}
-
-export async function reportToServer(
- fn: () => Promise<unknown>,
- markerData: MarkerData,
- workspacesRoot: string,
-): Promise<void> {
- const RETRY_DELAYS = [1000, 3000, 9000];
- let lastErr: unknown;
-
- for (let attempt = 0; attempt <= RETRY_DELAYS.length; attempt++) {
- try {
- await fn();
- return;
- } catch (e) {
- lastErr = e;
- if (isClientError(e)) {
- log.info(`server report for task ${markerData.taskId}: task already in terminal state (${e})`);
- return;
- }
- if (attempt < RETRY_DELAYS.length && isRetryableError(e)) {
- log.debug(`server report attempt ${attempt + 1} failed for task ${markerData.taskId}, retrying in ${RETRY_DELAYS[attempt]}ms`);
- await new Promise((r) => setTimeout(r, RETRY_DELAYS[attempt]));
- }
- }
- }
-
- log.warn(`server report failed for task ${markerData.taskId} after retries, writing marker: ${lastErr}`);
- try {
- await writeMarkerFile(workspacesRoot, markerData);
- } catch (writeErr) {
- log.error(`marker write also failed for task ${markerData.taskId}: ${writeErr}`);
- }
-}
-
-function sanitizeFilename(name: string): string {
- return path.basename(name).replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";
-}
-
-export async function cleanupAttachments(taskId: string): Promise<void> {
- try {
- await rm(path.join(ATTACHMENTS_BASE, taskId), { recursive: true, force: true });
- } catch {
- // best-effort
- }
-}
-
-export async function downloadAttachments(
- client: DaemonClient,
- token: string,
- workspaceId: string,
- taskId: string,
- attachmentIds: string[],
-): Promise<Attachment[]> {
- const dir = path.join(ATTACHMENTS_BASE, taskId);
- await mkdir(dir, { recursive: true });
-
- const attachments: Attachment[] = [];
- for (const artId of attachmentIds) {
- const meta = await client.getArtifactMeta(token, artId, workspaceId);
- const content = await client.downloadArtifact(token, artId, workspaceId);
- const filename = sanitizeFilename(meta.filename);
- const localPath = path.join(dir, `${artId}_${filename}`);
- await writeFile(localPath, Buffer.from(content));
- attachments.push({
- path: localPath,
- content_type: meta.content_type,
- filename: meta.filename,
- });
- }
- return attachments;
-}
-
-export async function runSession(input: SessionRunnerInput): Promise<void> {
- const { task, provider, cliPath, model, serverURL, token, workspacesRoot, agentTimeout, messageInactivityTimeout } = input;
-
- log.info(`starting (task=${task.id}, type=${task.type}, agent=${task.agentId}, provider=${provider}, model=${model || "default"})`);
-
- const client = new DaemonClient(serverURL);
- const backend = createBackend(provider, cliPath);
-
- // Compute timelineDir before prepare() so timeline entry exists even on early crashes
- const agentBaseDir = path.join(workspacesRoot, task.workspaceId, task.agentId, "workdir");
- const timelineDir = path.join(agentBaseDir, ".context_timeline").replace(/\\/g, "/");
- mkdirSync(timelineDir, { recursive: true });
-
- // Timeline entry: write IMMEDIATELY so KILL_TASK can find our PID
- await initEntryAsync(
- timelineDir,
- createTimelineEntry(task.id, task.prompt, task.type, undefined, process.pid, provider, task.contextKey, input.logFilePath),
- );
-
- const { workDir, env } = prepare(
- { workspacesRoot, token },
- task,
- );
-
- // --- State shared by the kill handler, hoisted so the SINGLE handler below
- // can see it whether the kill lands before or after the agent spawns. ---
- let killed = false;
- // Assigned once after the agent spawns (below) but READ earlier inside onKill;
- // prefer-const can't see the closure read, so it must stay `let`.
- // eslint-disable-next-line prefer-const
- let agentPid: number | undefined;
- // eslint-disable-next-line prefer-const
- let flushTimer: ReturnType<typeof setInterval> | undefined;
-
- // Message batching
- const pendingMessages: {
- seq: number;
- type: string;
- tool?: string;
- call_id?: string;
- content?: string;
- input?: Record<string, unknown>;
- output?: string;
- }[] = [];
- let seq = 0;
- let toolCount = 0;
- const BATCH_SIZE = Number(process.env.ALOOK_MESSAGE_BATCH_SIZE) || 20;
- const FLUSH_INTERVAL_MS = Number(process.env.ALOOK_MESSAGE_FLUSH_INTERVAL_MS) || 100;
-
- const flushMessages = async () => {
- if (pendingMessages.length === 0) return;
- const batch = pendingMessages.splice(0);
- try {
- await client.reportMessages(token, task.id, batch);
- } catch (e) {
- log.debug("message report failed", e);
- }
- };
-
- let mailboxWatcher: MailboxWatcher | null = null;
- let stalledRecoveryTimer: ReturnType<typeof setInterval> | undefined;
-
- // --- Single SIGTERM/SIGINT handler, registered ONCE for the whole lifetime.
- // Every field it touches is guarded for the "not yet initialized" window
- // (kill arriving before the agent is spawned / batching has started). ---
- const onKill = async () => {
- if (killed) return;
- killed = true;
- log.info(`killed by signal (messages=${seq}, tools=${toolCount})`);
-
- // 0. Stop mailbox watcher and stalled recovery timer (if running)
- if (mailboxWatcher) mailboxWatcher.stop();
- if (stalledRecoveryTimer) clearInterval(stalledRecoveryTimer);
-
- // 1. Kill the inner agent process group (CLI + tool/MCP subprocesses),
- // escalating to SIGKILL if it ignores SIGTERM. No-op if not yet spawned.
- if (agentPid !== undefined) {
- log.info(`killing inner agent group (pid=${agentPid})`);
- await killProcessTree(agentPid);
- }
-
- // 2. Flush any pending messages
- if (flushTimer) clearInterval(flushTimer);
- try { await flushMessages(); } catch { /* best-effort */ }
-
- // 3. Cleanup attachments
- await cleanupAttachments(task.id);
-
- // 4. Read kill-intent to determine reason
- const intent = readKillIntent(agentBaseDir, task.id);
- clearKillIntent(agentBaseDir, task.id);
-
- if (intent?.reason === "superseded") {
- // Superseded: update timeline and report via dedicated API
- updateEntry(timelineDir, task.id, (entry) => {
- entry.pid = null;
- entry.status = "superseded";
- entry.successor_task_id = intent.successorTaskId ?? null;
- entry.supersede_reason = "superseded by newer task";
- });
- try {
- await client.supersedeTask(token, task.id);
- } catch { /* best-effort — daemon steering may have already marked it */ }
- } else if (intent?.reason === "cancelled") {
- // User cancel: update timeline to cancelled (not killed)
- updateEntry(timelineDir, task.id, (entry) => {
- entry.pid = null;
- entry.status = "cancelled";
- entry.errmsg = "cancelled by user";
- });
- await reportToServer(
- () => client.failTask(token, task.id, "cancelled by user"),
- { taskId: task.id, type: "fail", payload: { error: "cancelled by user" }, token, serverURL, createdAt: new Date().toISOString() },
- workspacesRoot,
- );
- } else {
- // No intent file: preserve existing behavior
- updateEntry(timelineDir, task.id, (entry) => {
- entry.pid = null;
- entry.status = "killed";
- entry.errmsg = "killed by signal";
- });
- await reportToServer(
- () => client.failTask(token, task.id, "killed by signal"),
- { taskId: task.id, type: "fail", payload: { error: "killed by signal" }, token, serverURL, createdAt: new Date().toISOString() },
- workspacesRoot,
- );
- }
-
- process.exit(1);
- };
- process.on("SIGTERM", onKill);
- process.on("SIGINT", onKill);
-
- // Download attachments before building prompt
- const attachmentIds = (task.context?.attachment_ids as string[]) ?? [];
- let attachments: Attachment[] | undefined;
- if (attachmentIds.length > 0) {
- log.info(`downloading ${attachmentIds.length} attachment(s)`);
- try {
- attachments = await downloadAttachments(client, token, task.workspaceId, task.id, attachmentIds);
- log.info(`attachments ready (${attachments.length} file(s))`);
- } catch (e) {
- await cleanupAttachments(task.id);
- const errMsg = `failed to download attachments: ${e}`;
- log.error(errMsg);
- updateEntry(timelineDir, task.id, (entry) => {
- entry.pid = null;
- entry.status = "failed";
- entry.errmsg = errMsg;
- });
- await reportToServer(
- () => client.failTask(token, task.id, errMsg),
- { taskId: task.id, type: "fail", payload: { error: errMsg }, token, serverURL, createdAt: new Date().toISOString() },
- workspacesRoot,
- );
- // Leave onKill installed until the very end — no window where the pid is
- // findable but unhandled. agentPid is still undefined, so onKill just reports.
- process.removeListener("SIGTERM", onKill);
- process.removeListener("SIGINT", onKill);
- return;
- }
- }
-
- // A kill may have arrived during attachment download (onKill set killed=true
- // and called process.exit — but if exit hasn't flushed yet, don't spawn).
- if (killed) return;
-
- const prompt = input.promptOverride ?? buildPrompt(task, attachments);
-
- const resumeSessionId = task.contextKey
- ? findResumableSessionByContextKey(timelineDir, task.contextKey, provider) ?? undefined
- : undefined;
- if (resumeSessionId) {
- log.info(`resuming session ${resumeSessionId} (context_key: ${task.contextKey})`);
- }
-
- const session = backend.execute(prompt, {
- cwd: workDir,
- model: model || undefined,
- env,
- timeout: agentTimeout,
- resumeSessionId,
- steeringEnabled: input.steeringEnabled,
- });
-
- // Capture agent PID so the handler can reap it. backend.execute() spawns
- // synchronously and returns immediately, so the only gap is the JS between
- // the timeline write and here — closed by the re-check below.
- agentPid = session.pid;
-
- // If a kill landed while the agent was spawning, the handler ran with
- // agentPid===undefined and killed nothing. Reap the freshly-spawned process
- // now and exit before streaming starts.
- if (killed) {
- if (agentPid !== undefined) {
- log.info(`kill landed during spawn — reaping inner agent group (pid=${agentPid})`);
- await killProcessTree(agentPid);
- }
- process.exit(1);
- }
-
- // Update timeline entry with session_id once agent starts
- const earlySessionId = await session.sessionId;
- log.info(`agent started (pid=${agentPid ?? "unknown"}, session=${earlySessionId})`);
- log.info(JSON.stringify({ role: "user", type: "text", content: prompt }));
- updateEntry(timelineDir, task.id, (entry) => {
- entry.session_id = earlySessionId || null;
- // Mark the agent as genuinely started so steering may supersede this run.
- // Gate on a non-empty session id: codex resolves sessionId to "" if its
- // thread/start handshake fails before completing — that is NOT a started
- // agent, so leave the marker falsy and let the staleness path reap it.
- if (earlySessionId) entry.agent_started = true;
- });
-
- flushTimer = setInterval(flushMessages, FLUSH_INTERVAL_MS);
-
- // --- Steering: mailbox watcher + state machines ---
- const turnState = new RuntimeTurnState();
- let apmState = createInitialApmState();
- const notificationState = new RuntimeNotificationState();
- const progressState = new RuntimeProgressState();
- const pendingSteeredTasks = new Set<string>();
- const pendingAcks: { seq: string; sessionId: string }[] = [];
- let hasReceivedProgressEvent = false;
-
- if (input.steeringEnabled && input.steeringMailboxDir && task.contextKey) {
- const descriptor = session.descriptor;
- const STALLED_THRESHOLD_MS = 120_000; // 2 minutes
- const STALLED_CHECK_INTERVAL_MS = 30_000; // 30 seconds
-
- // Start a background ParsedEvent consumer for steering state machine updates
- if (session.parsedEvents) {
- const parsedIter = session.parsedEvents[Symbol.asyncIterator]();
- const consumeParsedEvents = async () => {
- try {
- while (!killed) {
- const { value: event, done } = await parsedIter.next();
- if (done) break;
-
- hasReceivedProgressEvent = true;
-
- // Track progress for granular liveness detection
- progressState.processEvent(event);
-
- // Record recent event for diagnostics
- const recentResult = reduceApmGatedRecentEvent(apmState, { event: event.kind });
- apmState = recentResult.nextState;
-
- // Classify errors for structured diagnostics + update APM state
- if (event.kind === "error") {
- const classified = classifyRuntimeError(event.message);
- log.info(`steering: error classified as ${classified.errorClass}: ${scrubDiagnosticText(event.message)}`);
- const errResult = reduceApmGatedError(apmState, { disableToolBoundaryFlush: true });
- apmState = errResult.nextState;
- }
-
- // turnState gate transitions — BEFORE reducer calls
- switch (event.kind) {
- case "tool_call":
- case "thinking":
- case "compaction_started":
- turnState.markToolBoundary();
- break;
- case "text":
- case "tool_output":
- case "compaction_finished":
- turnState.markProgress();
- break;
- }
-
- switch (event.kind) {
- case "session_init":
- turnState.markTurnStarted(event.sessionId);
- break;
- case "text":
- if (!turnState.isInTurn) turnState.markTurnStarted();
- break;
- case "tool_call": {
- if (!turnState.isInTurn) turnState.markTurnStarted();
- const result = reduceApmGatedToolUse(apmState, { kind: "tool_call" });
- apmState = result.nextState;
- break;
- }
- case "tool_output": {
- const result = reduceApmGatedToolUse(apmState, { kind: "tool_output" });
- apmState = result.nextState;
- if (result.shouldFlushToolBatch && session.send && apmState.pendingMessages.length > 0) {
- const readiness = reduceApmGatedFlushReadiness(apmState, {
- isGated: descriptor?.busyDeliveryMode === "gated",
- hasSession: !!earlySessionId,
- inboxLength: apmState.pendingMessages.length,
- reason: "tool_batch_complete",
- });
- if (readiness.shouldNotify) {
- let allSent = true;
- for (const msg of apmState.pendingMessages) {
- const sendResult = session.send(msg, "busy");
- if (!sendResult.ok) { allSent = false; break; }
- }
- if (allSent) {
- apmState = { ...apmState, pendingMessages: [] };
- for (const ack of pendingAcks) {
- notificationState.recordNoticeWritten(String(ack.seq), ack.sessionId, [{ id: String(ack.seq) }]);
- writeAck(agentBaseDir, task.contextKey!, ack.seq);
- }
- pendingAcks.length = 0;
- }
- }
- }
- break;
- }
- case "compaction_started":
- case "compaction_finished": {
- const result = reduceApmGatedCompaction(apmState, { kind: event.kind });
- apmState = result.nextState;
- if (event.kind === "compaction_finished" && session.send && apmState.pendingMessages.length > 0) {
- const readiness = reduceApmGatedFlushReadiness(apmState, {
- isGated: descriptor?.busyDeliveryMode === "gated",
- hasSession: !!earlySessionId,
- inboxLength: apmState.pendingMessages.length,
- reason: "compaction_finished",
- });
- if (readiness.shouldNotify) {
- let allSent = true;
- for (const msg of apmState.pendingMessages) {
- const sendResult = session.send(msg, "busy");
- if (!sendResult.ok) { allSent = false; break; }
- }
- if (allSent) {
- apmState = { ...apmState, pendingMessages: [] };
- for (const ack of pendingAcks) {
- notificationState.recordNoticeWritten(String(ack.seq), ack.sessionId, [{ id: String(ack.seq) }]);
- writeAck(agentBaseDir, task.contextKey!, ack.seq);
- }
- pendingAcks.length = 0;
- }
- }
- }
- break;
- }
- case "turn_end": {
- const result = reduceApmGatedTurnEnd(apmState, {
- inboxLength: apmState.pendingMessages.length,
- supportsStdinNotification: descriptor?.supportsStdinNotification,
- hasSession: !!earlySessionId,
- });
- apmState = result.nextState;
- let flushedOk = false;
- for (const eff of result.effects) {
- if (eff.kind === "deliver_stdin" && session.send) {
- let allSent = true;
- for (const msg of apmState.pendingMessages) {
- const sendResult = session.send(msg, eff.stdinMode);
- if (!sendResult.ok) {
- log.warn("steering: send failed during turn_end flush", { reason: sendResult.reason });
- allSent = false;
- break;
- }
- }
- if (allSent) {
- apmState = { ...apmState, pendingMessages: [] };
- flushedOk = true;
- }
- }
- }
- // Write deferred acks only after successful flush
- if (flushedOk && pendingAcks.length > 0) {
- for (const ack of pendingAcks) {
- notificationState.recordNoticeWritten(String(ack.seq), ack.sessionId, [{ id: String(ack.seq) }]);
- writeAck(agentBaseDir, task.contextKey!, ack.seq);
- }
- pendingAcks.length = 0;
- }
- // Complete pending steered tasks only after successful delivery
- if (flushedOk || apmState.pendingMessages.length === 0) {
- for (const steeredId of pendingSteeredTasks) {
- client.completeTask(token, steeredId, { output: "" }).catch((e) => {
- log.debug(`steering: failed to complete steered task ${steeredId}`, e);
- });
- }
- pendingSteeredTasks.clear();
- }
- turnState.markTurnCompleted();
- break;
- }
- }
- }
- } catch (err) {
- log.warn("steering: consumeParsedEvents error", { err: err instanceof Error ? err.message : String(err) });
- }
- };
- consumeParsedEvents().catch((err) => {
- log.error("steering: consumeParsedEvents unhandled error", { err: err instanceof Error ? err.message : String(err) });
- });
- }
-
- // Stalled recovery + startup timeout timer
- stalledRecoveryTimer = setInterval(() => {
- if (killed) return;
-
- // Startup timeout check on first tick
- if (!hasReceivedProgressEvent) {
- const startupResult = reduceApmStartupTimeoutTermination(apmState, {
- hasRuntimeProgressEvent: hasReceivedProgressEvent,
- });
- apmState = startupResult.nextState;
- if (startupResult.shouldTerminate) {
- log.warn("steering: startup timeout — no progress events received, killing agent");
- if (agentPid !== undefined) void killProcessTree(agentPid);
- return;
- }
- }
-
- // Stalled recovery check
- const staleForMs = progressState.ageMs();
- if (staleForMs > STALLED_THRESHOLD_MS && !progressState.isStale) {
- progressState.markStale();
- }
- const stalledResult = reduceApmStalledRecoveryTermination(apmState, {
- inboxLength: apmState.pendingMessages.length,
- staleForMs,
- staleThresholdMs: STALLED_THRESHOLD_MS,
- runtimeProgressIsStale: progressState.isStale,
- hasSession: !!earlySessionId,
- busyDeliveryMode: descriptor?.busyDeliveryMode ?? "none",
- hasDirectStdinRecoveryEvidence: false,
- });
- apmState = stalledResult.nextState;
- if (stalledResult.shouldTerminate) {
- log.warn(`steering: stalled recovery — agent stale for ${(staleForMs / 1000).toFixed(1)}s with ${apmState.pendingMessages.length} pending messages, killing`);
- if (agentPid !== undefined) void killProcessTree(agentPid);
- }
- }, STALLED_CHECK_INTERVAL_MS);
-
- // Start watching the mailbox for steered messages from daemon
- mailboxWatcher = watchInbox(
- agentBaseDir,
- task.contextKey,
- (seq, message) => {
- const sessionId = earlySessionId || "";
- if (notificationState.isDuplicateNotice(String(seq), sessionId)) {
- writeAck(agentBaseDir, task.contextKey!, seq);
- cleanupInboxFile(agentBaseDir, task.contextKey!, seq);
- return;
- }
-
- const busyMode = session.descriptor?.busyDeliveryMode;
- let delivered = false;
-
- if (busyMode === "direct" && session.send) {
- const result = session.send(message.text, turnState.isInTurn ? "busy" : "idle");
- if (result.ok) {
- notificationState.recordNoticeWritten(String(seq), sessionId, [{ id: String(seq) }]);
- writeAck(agentBaseDir, task.contextKey!, seq);
- delivered = true;
- } else {
- writeNack(agentBaseDir, task.contextKey!, seq, result.reason || "send failed");
- }
- } else if (busyMode === "gated") {
- const enqueueResult = reduceApmGatedEnqueue(apmState, message.text);
- apmState = enqueueResult.nextState;
-
- // Check if we can flush immediately
- if (turnState.canSteerBusy && session.send && apmState.pendingMessages.length > 0) {
- const readiness = reduceApmGatedFlushReadiness(apmState, {
- isGated: true,
- hasSession: !!earlySessionId,
- inboxLength: apmState.pendingMessages.length,
- reason: "enqueue",
- });
- if (readiness.shouldNotify) {
- let allSent = true;
- for (const msg of apmState.pendingMessages) {
- const sendResult = session.send(msg, "busy");
- if (!sendResult.ok) { allSent = false; break; }
- }
- if (allSent) {
- apmState = { ...apmState, pendingMessages: [] };
- }
- }
- }
-
- // Ack only if already flushed (no pending), otherwise defer ack to flush time
- if (apmState.pendingMessages.length === 0) {
- notificationState.recordNoticeWritten(String(seq), sessionId, [{ id: String(seq) }]);
- writeAck(agentBaseDir, task.contextKey!, seq);
- } else {
- // Track pending acks to write on successful flush
- pendingAcks.push({ seq, sessionId });
- }
- delivered = true;
- } else {
- writeNack(agentBaseDir, task.contextKey!, seq, "unsupported backend");
- }
-
- // Report steered task lifecycle to server
- if (delivered && message.taskId) {
- pendingSteeredTasks.add(message.taskId);
- client.startTask(token, message.taskId).catch((e) => {
- log.debug(`steering: failed to start steered task ${message.taskId}`, e);
- });
- }
-
- cleanupInboxFile(agentBaseDir, task.contextKey!, seq);
- },
- );
-
- }
-
- // Message inactivity timeout — kill hung agent if no messages arrive within the window
- const INACTIVITY_TIMEOUT_MS = messageInactivityTimeout ?? 5 * 60 * 1000;
- let inactivityTimedOut = false;
-
- try {
- const iter = session.messages[Symbol.asyncIterator]();
- while (!killed) {
- const next = iter.next();
- const raceResult = await (INACTIVITY_TIMEOUT_MS > 0
- ? Promise.race([
- next,
- new Promise<"timeout">((resolve) => {
- const timer = setTimeout(() => resolve("timeout"), INACTIVITY_TIMEOUT_MS);
- next.then(() => clearTimeout(timer), () => clearTimeout(timer));
- }),
- ])
- : next);
-
- if (raceResult === "timeout") {
- inactivityTimedOut = true;
- log.warn(`message inactivity timeout (${INACTIVITY_TIMEOUT_MS / 1000}s) — killing agent`);
- if (session.pid !== undefined) {
- // Reap the whole agent group, not just the leader, so MCP/tool
- // subprocesses don't orphan on an inactivity timeout.
- await killProcessTree(session.pid);
- }
- iter.return?.(undefined as never);
- break;
- }
-
- const iterResult = raceResult as IteratorResult<import("./types.js").AgentMessage>;
- if (iterResult.done) break;
-
- const msg = iterResult.value;
- seq++;
-
- if (msg.type === "tool-use") toolCount++;
- if (msg.type === "tool-result" && msg.output && msg.output.length > 500) {
- log.info(JSON.stringify({ role: "assistant", ...msg, output: msg.output.slice(0, 500) + `... (${msg.output.length} chars)` }));
- } else {
- log.info(JSON.stringify({ role: "assistant", ...msg }));
- }
-
- if (msg.type === "status" || msg.type === "log") continue;
-
- pendingMessages.push({
- seq,
- type: msg.type,
- tool: msg.tool,
- call_id: msg.callId,
- content: msg.type === "tool-result" ? "" : msg.content,
- input: msg.type === "tool-result" ? undefined : msg.input,
- output: msg.type === "tool-result" ? "" : msg.output,
- });
-
- // Timeline — record assistant text messages
- if (msg.type === "text" && msg.content) {
- updateEntry(timelineDir, task.id, (entry) => {
- entry.agent_responses.push(msg.content!);
- });
- }
-
- if (pendingMessages.length >= BATCH_SIZE) {
- await flushMessages();
- }
- }
-
- if (!killed) await flushMessages();
- } finally {
- if (flushTimer) clearInterval(flushTimer);
- }
-
- if (killed) return;
-
- // onKill stays installed across the result await so a kill landing here still
- // reaps the inner agent group; removed only once the result resolves.
- const result = await session.result;
-
- // Remove signal handlers — normal completion takes over
- process.removeListener("SIGTERM", onKill);
- process.removeListener("SIGINT", onKill);
-
- if (killed) return;
-
- // Override result on inactivity timeout
- if (inactivityTimedOut) {
- result.status = "failed";
- result.error = `message inactivity timeout (no messages for ${INACTIVITY_TIMEOUT_MS / 1000}s)`;
- }
-
- // Stop steering timers and clean up
- if (stalledRecoveryTimer) clearInterval(stalledRecoveryTimer);
- if (mailboxWatcher) {
- mailboxWatcher.stop();
- if (task.contextKey) cleanupSteeringDir(agentBaseDir, task.contextKey);
- }
-
- // Cleanup attachments after task completion
- await cleanupAttachments(task.id);
-
- // Timeline — finalize entry
- if (result.status === "completed") {
- updateEntry(timelineDir, task.id, (entry) => {
- entry.session_id = result.sessionId || null;
- entry.pid = null;
- entry.status = "completed";
- });
- } else {
- updateEntry(timelineDir, task.id, (entry) => {
- entry.pid = null;
- entry.status = "failed";
- entry.errmsg = result.error || "agent exited unexpectedly";
- });
- }
-
- // Report to server
- if (result.status === "completed") {
- const body: { output: string; session_id?: string; branch_name?: string } = {
- output: result.output || "",
- };
- if (result.sessionId) body.session_id = result.sessionId;
- // branchName is currently always undefined — forward-compat passthrough
- await reportToServer(
- () => client.completeTask(token, task.id, body),
- { taskId: task.id, type: "complete", payload: body, token, serverURL, createdAt: new Date().toISOString() },
- workspacesRoot,
- );
- const dur = (result.durationMs / 1000).toFixed(1);
- log.info(`completed (duration=${dur}s, messages=${seq}, tools=${toolCount})`);
- } else {
- const errorMsg = result.error || "agent exited unexpectedly";
- await reportToServer(
- () => client.failTask(token, task.id, errorMsg),
- { taskId: task.id, type: "fail", payload: { error: errorMsg }, token, serverURL, createdAt: new Date().toISOString() },
- workspacesRoot,
- );
- const dur = (result.durationMs / 1000).toFixed(1);
- log.info(`failed (duration=${dur}s, messages=${seq}, tools=${toolCount}) — ${result.error}`);
- }
-}
-
-// --- Entry point when run as a standalone process ---
-
-async function main(): Promise<void> {
- const encoded = process.argv[2];
- if (!encoded) {
- log.error("session-runner: missing base64-encoded input argument");
- process.exit(1);
- }
-
- let input: SessionRunnerInput;
- try {
- const json = Buffer.from(encoded, "base64").toString("utf-8");
- input = JSON.parse(json);
- } catch (e) {
- log.error("session-runner: failed to parse input", e);
- process.exit(1);
- }
-
- const client = new DaemonClient(input.serverURL);
-
- try {
- await runSession(input);
- } catch (e) {
- log.error(`session-runner: unhandled error for task ${input.task.id}`, e);
- await cleanupAttachments(input.task.id);
-
- // Update timeline entry to reflect failure
- const timelineDir = path.join(input.workspacesRoot, input.task.workspaceId, input.task.agentId, "workdir", ".context_timeline").replace(/\\/g, "/");
- updateEntry(timelineDir, input.task.id, (entry) => {
- entry.pid = null;
- entry.status = "failed";
- entry.errmsg = `session-runner crash: ${e}`;
- });
-
- const errorMsg = `session-runner crash: ${e}`;
- await reportToServer(
- () => client.failTask(input.token, input.task.id, errorMsg),
- { taskId: input.task.id, type: "fail", payload: { error: errorMsg }, token: input.token, serverURL: input.serverURL, createdAt: new Date().toISOString() },
- input.workspacesRoot,
- );
- process.exit(1);
- }
-}
-
-// Only run main() when executed directly (not when imported for testing)
-const isDirectExecution =
- typeof Bun !== "undefined"
- ? Bun.main === import.meta.path
- : process.argv[1]?.endsWith("session-runner.ts") || process.argv[1]?.endsWith("session-runner.js");
-
-if (isDirectExecution) {
- main();
-}
diff --git a/src/cli/daemon/skill-scanner.test.ts b/src/cli/daemon/skill-scanner.test.ts
deleted file mode 100644
index ebd9ccc49..000000000
--- a/src/cli/daemon/skill-scanner.test.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "fs";
-import { join } from "path";
-import { tmpdir } from "os";
-
-const mockState = { home: "/tmp" };
-
-vi.mock("os", async (importOriginal) => {
- const actual = await importOriginal<typeof import("os")>();
- return { ...actual, homedir: () => mockState.home };
-});
-
-vi.mock("../lib/logger.js", () => ({
- createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),
-}));
-
-vi.mock("../lib/config.js", () => ({
- configDir: () => join(tmpdir(), "alook-skill-scanner-test-config-" + process.pid),
-}));
-
-import { startSkillScanner, stopSkillScanner, parseFrontmatter, isClientError } from "./skill-scanner.js";
-import type { DaemonClient } from "./client.js";
-
-describe("parseFrontmatter", () => {
- it("parses name and description", () => {
- const content = `---\nname: my-skill\ndescription: Does stuff\n---\nBody`;
- expect(parseFrontmatter(content)).toEqual({ name: "my-skill", description: "Does stuff" });
- });
-
- it("returns null without frontmatter", () => {
- expect(parseFrontmatter("Just text")).toBeNull();
- });
-});
-
-describe("isClientError", () => {
- it("returns true for 4xx HTTP errors", () => {
- expect(isClientError(new Error("HTTP 400: Bad Request"))).toBe(true);
- expect(isClientError(new Error("HTTP 401: Unauthorized"))).toBe(true);
- expect(isClientError(new Error("HTTP 403: Forbidden"))).toBe(true);
- expect(isClientError(new Error("HTTP 404: Not Found"))).toBe(true);
- expect(isClientError(new Error("HTTP 422: Unprocessable Entity"))).toBe(true);
- });
-
- it("returns false for 5xx HTTP errors", () => {
- expect(isClientError(new Error("HTTP 500: Internal Server Error"))).toBe(false);
- expect(isClientError(new Error("HTTP 502: Bad Gateway"))).toBe(false);
- expect(isClientError(new Error("HTTP 503: Service Unavailable"))).toBe(false);
- });
-
- it("returns false for network errors", () => {
- expect(isClientError(new TypeError("fetch failed"))).toBe(false);
- expect(isClientError(new Error("ECONNREFUSED"))).toBe(false);
- });
-
- it("returns false for non-Error values", () => {
- expect(isClientError("string error")).toBe(false);
- expect(isClientError(null)).toBe(false);
- expect(isClientError(undefined)).toBe(false);
- });
-});
-
-describe("runScan global skills syncs to all workspaces", () => {
- let tempDir: string;
- let workspacesRoot: string;
- let mockClient: { syncSkills: ReturnType<typeof vi.fn> };
-
- beforeEach(() => {
- tempDir = mkdtempSync(join(tmpdir(), "skill-scan-"));
- workspacesRoot = join(tempDir, "workspaces");
- mkdirSync(workspacesRoot, { recursive: true });
- mockClient = {
- syncSkills: vi.fn(async () => ({})),
- };
- });
-
- afterEach(() => {
- stopSkillScanner();
- try { rmSync(tempDir, { recursive: true }); } catch { /* ok */ }
- });
-
- it("syncs global skills to multiple workspaces", async () => {
- const home = join(tempDir, "home");
- mockState.home = home;
-
- const skillDir = join(home, ".claude", "skills", "test-skill");
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, "SKILL.md"), "---\nname: test-skill\ndescription: A test\n---\nContent");
-
- const ws1Dir = join(workspacesRoot, "ws1", "agent1");
- const ws2Dir = join(workspacesRoot, "ws2", "agent2");
- mkdirSync(join(ws1Dir, "workdir"), { recursive: true });
- mkdirSync(join(ws2Dir, "workdir"), { recursive: true });
-
- startSkillScanner(mockClient as unknown as DaemonClient, {
- workspacesRoot,
- workspaces: [
- { workspaceId: "ws1", token: "token-ws1", agentIds: ["agent1"] },
- { workspaceId: "ws2", token: "token-ws2", agentIds: ["agent2"] },
- ],
- runtimes: ["claude"],
- daemonId: "test-daemon",
- }, 999_999);
-
- await new Promise((r) => setTimeout(r, 100));
-
- const globalCalls = mockClient.syncSkills.mock.calls.filter(
- (args) => (args[1] as { scope: string }).scope === "global"
- );
- expect(globalCalls.length).toBe(2);
-
- const tokens = globalCalls.map((args) => args[0] as string);
- expect(tokens).toContain("token-ws1");
- expect(tokens).toContain("token-ws2");
- });
-
- it("does nothing with empty workspaces array", () => {
- startSkillScanner(mockClient as unknown as DaemonClient, {
- workspacesRoot,
- workspaces: [],
- runtimes: ["claude"],
- daemonId: "test-daemon",
- }, 999_999);
-
- expect(mockClient.syncSkills).not.toHaveBeenCalled();
- });
-
- it("scans codex and opencode runtimes", async () => {
- const home = join(tempDir, "home-multi");
- mockState.home = home;
-
- mkdirSync(join(home, ".agents", "skills"), { recursive: true });
- mkdirSync(join(home, ".config", "opencode", "commands"), { recursive: true });
-
- const wsDir = join(workspacesRoot, "ws1", "agent1");
- mkdirSync(join(wsDir, "workdir"), { recursive: true });
-
- startSkillScanner(mockClient as unknown as DaemonClient, {
- workspacesRoot,
- workspaces: [
- { workspaceId: "ws1", token: "token-ws1", agentIds: ["agent1"] },
- ],
- runtimes: ["codex", "opencode"],
- daemonId: "test-daemon-multi",
- }, 999_999);
-
- await new Promise((r) => setTimeout(r, 100));
-
- const globalCalls = mockClient.syncSkills.mock.calls.filter(
- (args) => (args[1] as { scope: string }).scope === "global"
- );
- expect(globalCalls.length).toBe(2);
- });
-
- it("writes cache on 4xx error so next scan does not retry", async () => {
- const home = join(tempDir, "home-4xx");
- mockState.home = home;
-
- const skillDir = join(home, ".claude", "skills", "my-skill");
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, "SKILL.md"), "---\nname: my-skill\ndescription: Test 4xx\n---\nBody");
-
- const wsDir = join(workspacesRoot, "ws1", "agent1");
- mkdirSync(join(wsDir, "workdir"), { recursive: true });
-
- mockClient.syncSkills.mockRejectedValue(new Error("HTTP 401: Unauthorized"));
-
- startSkillScanner(mockClient as unknown as DaemonClient, {
- workspacesRoot,
- workspaces: [
- { workspaceId: "ws1", token: "token-ws1", agentIds: ["agent1"] },
- ],
- runtimes: ["claude"],
- daemonId: "test-daemon-4xx",
- }, 999_999);
-
- await new Promise((r) => setTimeout(r, 100));
-
- // First scan should have attempted the sync
- expect(mockClient.syncSkills).toHaveBeenCalled();
- const callCount = mockClient.syncSkills.mock.calls.length;
-
- // Stop and restart to trigger a second scan — cache should prevent re-request
- stopSkillScanner();
- mockClient.syncSkills.mockClear();
-
- startSkillScanner(mockClient as unknown as DaemonClient, {
- workspacesRoot,
- workspaces: [
- { workspaceId: "ws1", token: "token-ws1", agentIds: ["agent1"] },
- ],
- runtimes: ["claude"],
- daemonId: "test-daemon-4xx",
- }, 999_999);
-
- await new Promise((r) => setTimeout(r, 100));
-
- // Second scan should NOT call syncSkills because cache was written after 4xx
- expect(mockClient.syncSkills).not.toHaveBeenCalled();
- });
-
- it("does not write cache on 5xx error so next scan retries", async () => {
- const home = join(tempDir, "home-5xx");
- mockState.home = home;
-
- const skillDir = join(home, ".claude", "skills", "retry-skill");
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, "SKILL.md"), "---\nname: retry-skill\ndescription: Test 5xx\n---\nBody");
-
- const wsDir = join(workspacesRoot, "ws1", "agent1");
- mkdirSync(join(wsDir, "workdir"), { recursive: true });
-
- mockClient.syncSkills.mockRejectedValue(new Error("HTTP 500: Internal Server Error"));
-
- startSkillScanner(mockClient as unknown as DaemonClient, {
- workspacesRoot,
- workspaces: [
- { workspaceId: "ws1", token: "token-ws1", agentIds: ["agent1"] },
- ],
- runtimes: ["claude"],
- daemonId: "test-daemon-5xx",
- }, 999_999);
-
- await new Promise((r) => setTimeout(r, 100));
-
- expect(mockClient.syncSkills).toHaveBeenCalled();
-
- // Stop and restart to trigger a second scan — no cache, so it should retry
- stopSkillScanner();
- mockClient.syncSkills.mockClear();
-
- startSkillScanner(mockClient as unknown as DaemonClient, {
- workspacesRoot,
- workspaces: [
- { workspaceId: "ws1", token: "token-ws1", agentIds: ["agent1"] },
- ],
- runtimes: ["claude"],
- daemonId: "test-daemon-5xx",
- }, 999_999);
-
- await new Promise((r) => setTimeout(r, 100));
-
- // Second scan SHOULD call syncSkills because cache was NOT written after 5xx
- expect(mockClient.syncSkills).toHaveBeenCalled();
- });
-});
diff --git a/src/cli/daemon/skill-scanner.ts b/src/cli/daemon/skill-scanner.ts
deleted file mode 100644
index aa3651700..000000000
--- a/src/cli/daemon/skill-scanner.ts
+++ /dev/null
@@ -1,423 +0,0 @@
-import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync, realpathSync } from "fs";
-import { join, basename } from "path";
-import { homedir } from "os";
-import { createHash } from "crypto";
-import { createLogger } from "../lib/logger.js";
-import { configDir } from "../lib/config.js";
-import type { DaemonClient } from "./client.js";
-
-const log = createLogger({ module: "skill-scanner" });
-
-interface SkillEntry {
- name: string;
- description: string;
-}
-
-function getCacheDir(): string {
- return join(configDir(), "skills");
-}
-
-
-
-export function parseFrontmatter(content: string): { name: string; description: string } | null {
- const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
- if (!match) return null;
-
- const block = match[1];
- const nameMatch = block.match(/^name:\s*(.+)$/m);
- const descMatch = block.match(/^description:\s*(.+)$/m);
-
- if (!nameMatch) return null;
-
- return {
- name: nameMatch[1].trim().replace(/^["']|["']$/g, ""),
- description: descMatch ? descMatch[1].trim().replace(/^["']|["']$/g, "") : "",
- };
-}
-
-function safeReadDir(dir: string): string[] {
- try {
- if (!existsSync(dir)) return [];
- return readdirSync(dir);
- } catch {
- return [];
- }
-}
-
-function findSkillFiles(baseDir: string, pattern: string): string[] {
- const results: string[] = [];
- if (!existsSync(baseDir)) return results;
-
- if (pattern === "*/SKILL.md") {
- for (const entry of safeReadDir(baseDir)) {
- const skillPath = join(baseDir, entry, "SKILL.md");
- try {
- if (existsSync(skillPath) && statSync(skillPath).isFile()) {
- results.push(skillPath);
- }
- } catch { /* skip */ }
- }
- } else if (pattern === "**/skills/*/SKILL.md") {
- walkForSkills(baseDir, results);
- } else if (pattern === "*.md") {
- for (const entry of safeReadDir(baseDir)) {
- if (entry.endsWith(".md")) {
- const filePath = join(baseDir, entry);
- try {
- if (statSync(filePath).isFile()) {
- results.push(filePath);
- }
- } catch { /* skip */ }
- }
- }
- }
-
- return results;
-}
-
-function walkForSkills(dir: string, results: string[], depth = 0): void {
- if (depth > 5) return;
- try {
- for (const entry of readdirSync(dir)) {
- const full = join(dir, entry);
- try {
- const st = statSync(full);
- if (st.isDirectory()) {
- if (entry === "skills") {
- for (const skillDir of safeReadDir(full)) {
- const skillPath = join(full, skillDir, "SKILL.md");
- try {
- if (existsSync(skillPath) && statSync(skillPath).isFile()) {
- results.push(skillPath);
- }
- } catch { /* skip */ }
- }
- } else {
- walkForSkills(full, results, depth + 1);
- }
- }
- } catch { /* skip */ }
- }
- } catch { /* skip */ }
-}
-
-function scanFrontmatterSkills(paths: string[]): SkillEntry[] {
- const skills = new Map<string, SkillEntry>();
- for (const filePath of paths) {
- try {
- const content = readFileSync(filePath, "utf-8");
- const meta = parseFrontmatter(content);
- if (meta && !skills.has(meta.name)) {
- skills.set(meta.name, meta);
- }
- } catch { /* skip */ }
- }
- return Array.from(skills.values());
-}
-
-function scanClaudeGlobalSkills(): SkillEntry[] {
- const home = homedir();
- const allSkills: SkillEntry[] = [];
-
- const directPaths = findSkillFiles(join(home, ".claude", "skills"), "*/SKILL.md");
- allSkills.push(...scanFrontmatterSkills(directPaths));
-
- const pluginCacheDir = join(home, ".claude", "plugins", "cache");
- const pluginPaths = findSkillFiles(pluginCacheDir, "**/skills/*/SKILL.md");
- const names = new Set(allSkills.map((s) => s.name));
- for (const filePath of pluginPaths) {
- try {
- const content = readFileSync(filePath, "utf-8");
- const meta = parseFrontmatter(content);
- if (meta && !names.has(meta.name)) {
- names.add(meta.name);
- allSkills.push(meta);
- }
- } catch { /* skip */ }
- }
-
- return allSkills;
-}
-
-function scanClaudeAgentSkills(workdir: string): SkillEntry[] {
- const paths = findSkillFiles(join(workdir, ".claude", "skills"), "*/SKILL.md");
- return scanFrontmatterSkills(paths);
-}
-
-function scanCodexGlobalSkills(): SkillEntry[] {
- const home = homedir();
- const allSkills: SkillEntry[] = [];
-
- const paths = [
- ...findSkillFiles(join(home, ".agents", "skills"), "*/SKILL.md"),
- ...findSkillFiles(join(home, ".codex", "skills", ".system"), "*/SKILL.md"),
- ];
- allSkills.push(...scanFrontmatterSkills(paths));
-
- const codexPluginDir = join(home, ".codex", "plugins", "cache");
- const pluginPaths = findSkillFiles(codexPluginDir, "**/skills/*/SKILL.md");
- const names = new Set(allSkills.map((s) => s.name));
- for (const filePath of pluginPaths) {
- try {
- const content = readFileSync(filePath, "utf-8");
- const meta = parseFrontmatter(content);
- if (meta && !names.has(meta.name)) {
- names.add(meta.name);
- allSkills.push(meta);
- }
- } catch { /* skip */ }
- }
-
- return allSkills;
-}
-
-function scanCodexAgentSkills(workdir: string): SkillEntry[] {
- const paths = findSkillFiles(join(workdir, ".agents", "skills"), "*/SKILL.md");
- return scanFrontmatterSkills(paths);
-}
-
-function scanOpenCodeMdFiles(dir: string): SkillEntry[] {
- const skills: SkillEntry[] = [];
- const files = findSkillFiles(dir, "*.md");
- for (const filePath of files) {
- try {
- const content = readFileSync(filePath, "utf-8");
- const name = basename(filePath, ".md");
- const firstLine = content.split("\n").find((l) => l.trim().length > 0) ?? "";
- skills.push({ name, description: firstLine.replace(/^#\s*/, "").trim() });
- } catch { /* skip */ }
- }
- return skills;
-}
-
-function scanOpenCodeGlobalSkills(): SkillEntry[] {
- const home = homedir();
- const skills: SkillEntry[] = [];
- const names = new Set<string>();
-
- for (const s of scanOpenCodeMdFiles(join(home, ".config", "opencode", "commands"))) {
- if (!names.has(s.name)) { names.add(s.name); skills.push(s); }
- }
-
- for (const s of scanOpenCodeMdFiles(join(home, ".config", "opencode", "skills"))) {
- if (!names.has(s.name)) { names.add(s.name); skills.push(s); }
- }
-
- return skills;
-}
-
-function scanOpenCodeAgentSkills(workdir: string): SkillEntry[] {
- const skills: SkillEntry[] = [];
- const names = new Set<string>();
-
- for (const s of scanOpenCodeMdFiles(join(workdir, ".opencode", "commands"))) {
- if (!names.has(s.name)) { names.add(s.name); skills.push(s); }
- }
-
- for (const s of scanOpenCodeMdFiles(join(workdir, ".opencode", "skills"))) {
- if (!names.has(s.name)) { names.add(s.name); skills.push(s); }
- }
-
- return skills;
-}
-
-type Runtime = "claude" | "codex" | "opencode";
-
-export interface SkillScannerConfig {
- workspacesRoot: string;
- workspaces: { workspaceId: string; token: string; agentIds: string[] }[];
- runtimes: Runtime[];
- daemonId: string;
-}
-
-
-interface SkillCache {
- hash: string;
- skills: SkillEntry[];
-}
-
-function computeHash(skills: SkillEntry[]): string {
- return createHash("md5").update(JSON.stringify(skills)).digest("hex");
-}
-
-function globalCachePath(daemonId: string, runtime: Runtime): string {
- return join(getCacheDir(), "global", daemonId, `${runtime}.json`);
-}
-
-function agentCachePath(agentId: string, runtime: Runtime): string {
- return join(getCacheDir(), "agents", agentId, `${runtime}.json`);
-}
-
-function readCacheHash(filePath: string): string | null {
- try {
- if (!existsSync(filePath)) return null;
- const data: SkillCache = JSON.parse(readFileSync(filePath, "utf-8"));
- return data.hash ?? null;
- } catch {
- return null;
- }
-}
-
-function writeCacheFile(filePath: string, hash: string, skills: SkillEntry[]) {
- const dir = join(filePath, "..");
- mkdirSync(dir, { recursive: true });
- const data: SkillCache = { hash, skills };
- writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
-}
-
-export function isClientError(err: unknown): boolean {
- if (err instanceof Error) {
- const match = err.message.match(/^HTTP (\d+):/);
- if (match) {
- const status = parseInt(match[1], 10);
- return status >= 400 && status < 500;
- }
- }
- return false;
-}
-
-let scanTimer: ReturnType<typeof setInterval> | null = null;
-let scannerConfig: SkillScannerConfig | null = null;
-let clientRef: DaemonClient | null = null;
-
-function discoverTargets(): { agentId: string; workdir: string | null; runtime: Runtime; token: string }[] {
- if (!scannerConfig) return [];
- const rootExists = existsSync(scannerConfig.workspacesRoot);
- const rootReal = rootExists ? realpathSync(scannerConfig.workspacesRoot) : null;
- const targets: { agentId: string; workdir: string | null; runtime: Runtime; token: string }[] = [];
-
- for (const ws of scannerConfig.workspaces) {
- const agentIds = new Set(ws.agentIds);
-
- // Also discover agents from filesystem (covers agents not yet in config)
- if (rootReal) {
- const wsDir = join(scannerConfig.workspacesRoot, ws.workspaceId);
- try {
- if (existsSync(wsDir)) {
- for (const dir of readdirSync(wsDir)) {
- if (existsSync(join(wsDir, dir, "workdir"))) agentIds.add(dir);
- }
- }
- } catch { /* skip */ }
- }
-
- for (const agentId of agentIds) {
- let validWorkdir: string | null = null;
- if (rootReal) {
- const workdir = join(scannerConfig.workspacesRoot, ws.workspaceId, agentId, "workdir");
- if (existsSync(workdir)) {
- try {
- if (realpathSync(workdir).startsWith(rootReal)) validWorkdir = workdir;
- } catch { /* skip */ }
- }
- }
- for (const runtime of scannerConfig.runtimes) {
- targets.push({ agentId, workdir: validWorkdir, runtime, token: ws.token });
- }
- }
- }
- return targets;
-}
-
-function getGlobalScanner(runtime: Runtime): () => SkillEntry[] {
- if (runtime === "claude") return scanClaudeGlobalSkills;
- if (runtime === "codex") return scanCodexGlobalSkills;
- return scanOpenCodeGlobalSkills;
-}
-
-function getAgentScanner(runtime: Runtime): (workdir: string) => SkillEntry[] {
- if (runtime === "claude") return scanClaudeAgentSkills;
- if (runtime === "codex") return scanCodexAgentSkills;
- return scanOpenCodeAgentSkills;
-}
-
-function runScan() {
- if (!scannerConfig || !clientRef) return;
-
- if (scannerConfig.workspaces.length === 0) return;
-
- // 1. Scan + sync global skills per runtime to ALL workspaces
- for (const runtime of scannerConfig.runtimes) {
- try {
- const skills = getGlobalScanner(runtime)();
- const hash = computeHash(skills);
- const prevHash = readCacheHash(globalCachePath(scannerConfig.daemonId, runtime));
-
- if (prevHash !== hash) {
- const skillItems = skills.map((s) => ({ name: s.name, description: s.description }));
- log.debug(`Syncing global ${runtime} — ${skills.length} skills`);
- const daemonId = scannerConfig.daemonId;
- const syncPromises = scannerConfig.workspaces.map((ws) =>
- clientRef!.syncSkills(ws.token, {
- scope: "global",
- runtime,
- skills: skillItems,
- daemon_id: daemonId,
- })
- );
- Promise.all(syncPromises).then(() => {
- writeCacheFile(globalCachePath(daemonId, runtime), hash, skills);
- }).catch((e) => {
- if (isClientError(e)) {
- writeCacheFile(globalCachePath(daemonId, runtime), hash, skills);
- }
- log.debug("Global skill sync failed", e);
- });
- }
- } catch (e) {
- log.debug(`Global scan error for ${runtime}`, e);
- }
- }
-
- // 2. Scan + sync agent-scope skills per agent (only if workdir exists)
- const targets = discoverTargets();
-
- for (const target of targets) {
- if (!target.workdir) continue;
- try {
- const skills = getAgentScanner(target.runtime)(target.workdir);
- const hash = computeHash(skills);
- const prevHash = readCacheHash(agentCachePath(target.agentId, target.runtime));
-
- if (prevHash !== hash) {
- const skillItems = skills.map((s) => ({ name: s.name, description: s.description }));
- log.debug(`Syncing ${target.agentId}:${target.runtime} — ${skills.length} agent skills`);
- clientRef.syncSkills(target.token, {
- scope: "agent",
- agent_id: target.agentId,
- runtime: target.runtime,
- skills: skillItems,
- }).then(() => {
- writeCacheFile(agentCachePath(target.agentId, target.runtime), hash, skills);
- }).catch((e) => {
- if (isClientError(e)) {
- writeCacheFile(agentCachePath(target.agentId, target.runtime), hash, skills);
- }
- log.debug("Agent skill sync failed", e);
- });
- }
- } catch (e) {
- log.debug(`Agent scan error for ${target.agentId}:${target.runtime}`, e);
- }
- }
-}
-
-export function startSkillScanner(
- client: DaemonClient,
- config: SkillScannerConfig,
- interval = 60_000,
-): void {
- clientRef = client;
- scannerConfig = config;
- runScan();
- scanTimer = setInterval(runScan, interval);
-}
-
-export function stopSkillScanner(): void {
- if (scanTimer) {
- clearInterval(scanTimer);
- scanTimer = null;
- }
-}
-
-
diff --git a/src/cli/daemon/steering/__tests__/apmStateMachine.test.ts b/src/cli/daemon/steering/__tests__/apmStateMachine.test.ts
deleted file mode 100644
index 834b27cc3..000000000
--- a/src/cli/daemon/steering/__tests__/apmStateMachine.test.ts
+++ /dev/null
@@ -1,334 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- createInitialApmState,
- reduceApmGatedToolUse,
- reduceApmGatedCompaction,
- reduceApmGatedEnqueue,
- reduceApmGatedTurnEnd,
- reduceApmGatedError,
- reduceApmGatedFlushReadiness,
- reduceApmGatedRecentEvent,
- reduceApmStalledRecoveryTermination,
- reduceApmStartupTimeoutTermination,
- reduceApmIdleState,
- reduceApmGatedAssistantContinuation,
- reduceApmGatedFlush,
- MAX_APM_GATED_STEERING_EVENTS,
-} from "../apmStateMachine.js";
-
-describe("ApmGatedSteeringState", () => {
- describe("createInitialApmState", () => {
- it("returns default state", () => {
- const state = createInitialApmState();
- expect(state.isIdle).toBe(false);
- expect(state.phase).toBe("idle");
- expect(state.outstandingToolUses).toBe(0);
- expect(state.compacting).toBe(false);
- expect(state.toolBoundaryFlushDisabled).toBe(false);
- expect(state.pendingMessages).toEqual([]);
- expect(state.recentEvents).toEqual([]);
- });
- });
-
- describe("reduceApmIdleState", () => {
- it("sets isIdle", () => {
- const state = createInitialApmState();
- const r = reduceApmIdleState(state, { isIdle: true });
- expect(r.nextState.isIdle).toBe(true);
- });
- });
-
- describe("reduceApmGatedToolUse", () => {
- it("tool_call increments outstanding and enters tool_wait", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedToolUse(state, { kind: "tool_call" });
- expect(r.nextState.outstandingToolUses).toBe(1);
- expect(r.nextState.phase).toBe("tool_wait");
- expect(r.hadOutstandingToolUse).toBe(false);
- expect(r.shouldFlushToolBatch).toBe(false);
- });
-
- it("tool_output decrements and enters tool_boundary", () => {
- let state = createInitialApmState();
- state = reduceApmGatedToolUse(state, { kind: "tool_call" }).nextState;
- const r = reduceApmGatedToolUse(state, { kind: "tool_output" });
- expect(r.nextState.outstandingToolUses).toBe(0);
- expect(r.nextState.phase).toBe("tool_boundary");
- expect(r.hadOutstandingToolUse).toBe(true);
- expect(r.shouldFlushToolBatch).toBe(true);
- });
-
- it("3 overlapping tool_calls, flush only after 3rd tool_output", () => {
- let state = createInitialApmState();
- for (let i = 0; i < 3; i++) {
- state = reduceApmGatedToolUse(state, { kind: "tool_call" }).nextState;
- }
- expect(state.outstandingToolUses).toBe(3);
-
- for (let i = 0; i < 2; i++) {
- const r = reduceApmGatedToolUse(state, { kind: "tool_output" });
- state = r.nextState;
- expect(r.shouldFlushToolBatch).toBe(false);
- }
- const r = reduceApmGatedToolUse(state, { kind: "tool_output" });
- expect(r.shouldFlushToolBatch).toBe(true);
- });
-
- it("tool_output never goes below 0", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedToolUse(state, { kind: "tool_output" });
- expect(r.nextState.outstandingToolUses).toBe(0);
- });
- });
-
- describe("reduceApmGatedCompaction", () => {
- it("compaction_started sets compacting and phase", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedCompaction(state, { kind: "compaction_started" });
- expect(r.nextState.compacting).toBe(true);
- expect(r.nextState.phase).toBe("compacting");
- });
-
- it("compaction_finished clears compacting, enters assistant_continuation", () => {
- let state = createInitialApmState();
- state = reduceApmGatedCompaction(state, { kind: "compaction_started" }).nextState;
- const r = reduceApmGatedCompaction(state, { kind: "compaction_finished" });
- expect(r.nextState.compacting).toBe(false);
- expect(r.nextState.phase).toBe("assistant_continuation");
- });
-
- it("compaction_interrupted resets compacting without changing phase to assistant_continuation", () => {
- let state = createInitialApmState();
- state = reduceApmGatedCompaction(state, { kind: "compaction_started" }).nextState;
- const r = reduceApmGatedCompaction(state, { kind: "compaction_interrupted" });
- expect(r.nextState.compacting).toBe(false);
- expect(r.nextState.phase).not.toBe("assistant_continuation");
- });
- });
-
- describe("reduceApmGatedAssistantContinuation", () => {
- it("sets phase to assistant_continuation", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedAssistantContinuation(state);
- expect(r.nextState.phase).toBe("assistant_continuation");
- expect(r.nextState.isIdle).toBe(false);
- });
- });
-
- describe("reduceApmGatedFlushReadiness", () => {
- it("blocks when not gated", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedFlushReadiness(state, { isGated: false, hasSession: true, inboxLength: 1, reason: "test" });
- expect(r.shouldNotify).toBe(false);
- expect(r.blockedReason).toBe("non_gated");
- });
-
- it("blocks when no session", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: false, inboxLength: 1, reason: "test" });
- expect(r.shouldNotify).toBe(false);
- expect(r.blockedReason).toBe("missing_session");
- });
-
- it("blocks when inbox empty", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 0, reason: "test" });
- expect(r.shouldNotify).toBe(false);
- expect(r.blockedReason).toBe("empty_inbox");
- });
-
- it("blocks when tool_boundary_flush_disabled", () => {
- let state = createInitialApmState();
- state = reduceApmGatedError(state, { disableToolBoundaryFlush: true }).nextState;
- const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 1, reason: "test" });
- expect(r.shouldNotify).toBe(false);
- expect(r.blockedReason).toBe("tool_boundary_flush_disabled");
- });
-
- it("blocks when compacting", () => {
- let state = createInitialApmState();
- state = reduceApmGatedCompaction(state, { kind: "compaction_started" }).nextState;
- const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 1, reason: "test" });
- expect(r.shouldNotify).toBe(false);
- expect(r.blockedReason).toBe("compacting");
- });
-
- it("blocks when outstanding tool uses", () => {
- let state = createInitialApmState();
- state = reduceApmGatedToolUse(state, { kind: "tool_call" }).nextState;
- const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 1, reason: "test" });
- expect(r.shouldNotify).toBe(false);
- expect(r.blockedReason).toBe("outstanding_tool_uses");
- });
-
- it("notifies when all conditions met", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 2, reason: "test" });
- expect(r.shouldNotify).toBe(true);
- expect(r.blockedReason).toBeNull();
- expect(r.effects).toHaveLength(1);
- expect(r.effects[0].kind).toBe("notify_stdin");
- expect(r.effects[0].stdinMode).toBe("busy");
- expect(r.effects[0].clauseId).toBe("SMR-002");
- });
- });
-
- describe("reduceApmGatedTurnEnd", () => {
- it("with pending messages and conditions met → deliver_stdin", () => {
- let state = createInitialApmState();
- state = reduceApmGatedEnqueue(state, "msg1").nextState;
- const r = reduceApmGatedTurnEnd(state, { inboxLength: 1, supportsStdinNotification: true, hasSession: true });
- expect(r.effects).toHaveLength(1);
- expect(r.effects[0].kind).toBe("deliver_stdin");
- expect(r.effects[0].stdinMode).toBe("idle");
- expect(r.nextState.isIdle).toBe(false);
- expect(r.nextState.phase).toBe("idle");
- });
-
- it("with no inbox → idle, no effects", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedTurnEnd(state, { inboxLength: 0, supportsStdinNotification: true, hasSession: true });
- expect(r.effects).toHaveLength(0);
- expect(r.nextState.isIdle).toBe(true);
- });
-
- it("with no defaults → idle, no effects", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedTurnEnd(state);
- expect(r.effects).toHaveLength(0);
- expect(r.nextState.isIdle).toBe(true);
- });
-
- it("resets tool counts and compaction", () => {
- let state = createInitialApmState();
- state = reduceApmGatedToolUse(state, { kind: "tool_call" }).nextState;
- state = reduceApmGatedCompaction(state, { kind: "compaction_started" }).nextState;
- const r = reduceApmGatedTurnEnd(state);
- expect(r.nextState.outstandingToolUses).toBe(0);
- expect(r.nextState.compacting).toBe(false);
- });
- });
-
- describe("reduceApmGatedError", () => {
- it("sets phase to error", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedError(state);
- expect(r.nextState.phase).toBe("error");
- });
-
- it("disableToolBoundaryFlush sets flag", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedError(state, { disableToolBoundaryFlush: true });
- expect(r.nextState.toolBoundaryFlushDisabled).toBe(true);
- expect(r.shouldDisableToolBoundaryFlush).toBe(true);
- });
-
- it("toolBoundaryFlushDisabled is sticky", () => {
- let state = createInitialApmState();
- state = reduceApmGatedError(state, { disableToolBoundaryFlush: true }).nextState;
- const r = reduceApmGatedError(state);
- expect(r.nextState.toolBoundaryFlushDisabled).toBe(true);
- });
- });
-
- describe("reduceApmGatedFlush", () => {
- it("records lastFlushReason", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedFlush(state, { reason: "tool_boundary" });
- expect(r.nextState.lastFlushReason).toBe("tool_boundary");
- });
- });
-
- describe("reduceApmGatedRecentEvent", () => {
- it("appends event summary", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedRecentEvent(state, { event: "tool_call" });
- expect(r.nextState.recentEvents).toHaveLength(1);
- expect(r.nextState.recentEvents[0]).toContain("tool_call");
- });
-
- it("caps at MAX_APM_GATED_STEERING_EVENTS", () => {
- let state = createInitialApmState();
- for (let i = 0; i < MAX_APM_GATED_STEERING_EVENTS + 5; i++) {
- state = reduceApmGatedRecentEvent(state, { event: `e${i}` }).nextState;
- }
- expect(state.recentEvents).toHaveLength(MAX_APM_GATED_STEERING_EVENTS);
- });
- });
-
- describe("reduceApmGatedEnqueue", () => {
- it("appends message to pendingMessages", () => {
- const state = createInitialApmState();
- const r = reduceApmGatedEnqueue(state, "hello");
- expect(r.nextState.pendingMessages).toEqual(["hello"]);
- });
-
- it("accumulates messages", () => {
- let state = createInitialApmState();
- state = reduceApmGatedEnqueue(state, "a").nextState;
- state = reduceApmGatedEnqueue(state, "b").nextState;
- expect(state.pendingMessages).toEqual(["a", "b"]);
- });
- });
-
- describe("reduceApmStalledRecoveryTermination", () => {
- const baseInput = {
- inboxLength: 1,
- staleForMs: 200_000,
- staleThresholdMs: 120_000,
- runtimeProgressIsStale: true,
- hasSession: true,
- busyDeliveryMode: "none",
- hasDirectStdinRecoveryEvidence: false,
- };
-
- it("terminates when stale with inbox", () => {
- const state = createInitialApmState();
- const r = reduceApmStalledRecoveryTermination(state, baseInput);
- expect(r.shouldTerminate).toBe(true);
- expect(r.nextState.expectedTerminationReason).toBe("stalled_recovery");
- });
-
- it("does not terminate with empty inbox", () => {
- const state = createInitialApmState();
- const r = reduceApmStalledRecoveryTermination(state, { ...baseInput, inboxLength: 0 });
- expect(r.shouldTerminate).toBe(false);
- expect(r.blockedReason).toBe("empty_inbox");
- });
-
- it("does not terminate when not stale", () => {
- const state = createInitialApmState();
- const r = reduceApmStalledRecoveryTermination(state, {
- ...baseInput,
- staleForMs: 10_000,
- runtimeProgressIsStale: false,
- });
- expect(r.shouldTerminate).toBe(false);
- expect(r.blockedReason).toBe("runtime_progress_recent");
- });
-
- it("already recovering returns alreadyRecovering", () => {
- let state = createInitialApmState();
- state = reduceApmStalledRecoveryTermination(state, baseInput).nextState;
- const r = reduceApmStalledRecoveryTermination(state, baseInput);
- expect(r.shouldTerminate).toBe(false);
- expect(r.alreadyRecovering).toBe(true);
- });
- });
-
- describe("reduceApmStartupTimeoutTermination", () => {
- it("terminates when no progress events", () => {
- const state = createInitialApmState();
- const r = reduceApmStartupTimeoutTermination(state, { hasRuntimeProgressEvent: false });
- expect(r.shouldTerminate).toBe(true);
- expect(r.nextState.expectedTerminationReason).toBe("startup_timeout");
- });
-
- it("does not terminate when has progress events", () => {
- const state = createInitialApmState();
- const r = reduceApmStartupTimeoutTermination(state, { hasRuntimeProgressEvent: true });
- expect(r.shouldTerminate).toBe(false);
- expect(r.blockedReason).toBe("runtime_progress_started");
- });
- });
-});
diff --git a/src/cli/daemon/steering/__tests__/errorDiagnostics.test.ts b/src/cli/daemon/steering/__tests__/errorDiagnostics.test.ts
deleted file mode 100644
index bc402e3ff..000000000
--- a/src/cli/daemon/steering/__tests__/errorDiagnostics.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- classifyRuntimeError,
- extractHttpStatus,
- scrubDiagnosticText,
-} from "../errorDiagnostics.js";
-
-describe("extractHttpStatus", () => {
- it("extracts from 'HTTP 429'", () => {
- expect(extractHttpStatus("HTTP 429 Too Many Requests")).toBe(429);
- });
-
- it("extracts from 'status: 401'", () => {
- expect(extractHttpStatus("status: 401")).toBe(401);
- });
-
- it("extracts from 'API Error: 500'", () => {
- expect(extractHttpStatus("API Error: 500")).toBe(500);
- });
-
- it("extracts from semantic '404 Not Found'", () => {
- expect(extractHttpStatus("404 Not Found")).toBe(404);
- });
-
- it("returns null for no status", () => {
- expect(extractHttpStatus("something went wrong")).toBeNull();
- });
-
- it("does not extract bare numbers without context", () => {
- expect(extractHttpStatus("processed 429 records")).toBeNull();
- });
-});
-
-describe("classifyRuntimeError", () => {
- it("explicit RateLimitError token → RateLimitError", () => {
- const r = classifyRuntimeError("RateLimitError: try again later");
- expect(r.errorClass).toBe("RateLimitError");
- expect(r.action).toBe("retry_backoff");
- });
-
- it("explicit AuthenticationError token → AuthError", () => {
- const r = classifyRuntimeError("AuthenticationError: invalid credentials");
- expect(r.errorClass).toBe("AuthError");
- });
-
- it("HTTP 429 → RateLimitError", () => {
- const r = classifyRuntimeError("HTTP 429 Too Many Requests");
- expect(r.errorClass).toBe("RateLimitError");
- expect(r.action).toBe("retry_backoff");
- });
-
- it("status: 401 → AuthError", () => {
- const r = classifyRuntimeError("status: 401 Unauthorized");
- expect(r.errorClass).toBe("AuthError");
- expect(r.action).toBe("abort");
- });
-
- it("HTTP 404 → NotFoundError", () => {
- const r = classifyRuntimeError("HTTP 404 Not Found");
- expect(r.errorClass).toBe("NotFoundError");
- expect(r.action).toBe("report");
- });
-
- it("HTTP 500 → ProviderServerError", () => {
- const r = classifyRuntimeError("HTTP 500 Internal Server Error");
- expect(r.errorClass).toBe("ProviderServerError");
- expect(r.action).toBe("retry");
- });
-
- it("rate limit text → RateLimitError", () => {
- const r = classifyRuntimeError("API rate limit exceeded, please slow down");
- expect(r.errorClass).toBe("RateLimitError");
- });
-
- it("overloaded → RateLimitError", () => {
- const r = classifyRuntimeError("Service overloaded, try again later");
- expect(r.errorClass).toBe("RateLimitError");
- });
-
- it("token revoked → AuthError (expanded pattern)", () => {
- const r = classifyRuntimeError("your token revoked by admin");
- expect(r.errorClass).toBe("AuthError");
- });
-
- it("refresh token expired → AuthError (expanded pattern)", () => {
- const r = classifyRuntimeError("refresh token expired, please re-authenticate");
- expect(r.errorClass).toBe("AuthError");
- });
-
- it("session expired → AuthError", () => {
- const r = classifyRuntimeError("Your session expired");
- expect(r.errorClass).toBe("AuthError");
- });
-
- it("credentials not found → AuthError", () => {
- const r = classifyRuntimeError("credentials not found in keychain");
- expect(r.errorClass).toBe("AuthError");
- });
-
- it("invalid api key → AuthError", () => {
- const r = classifyRuntimeError("Invalid API key provided");
- expect(r.errorClass).toBe("AuthError");
- });
-
- it("model not supported → ModelConfigError", () => {
- const r = classifyRuntimeError("model not supported: gpt-99");
- expect(r.errorClass).toBe("ModelConfigError");
- expect(r.action).toBe("abort");
- });
-
- it("ETIMEDOUT → TimeoutError", () => {
- const r = classifyRuntimeError("connect ETIMEDOUT 1.2.3.4:443");
- expect(r.errorClass).toBe("TimeoutError");
- expect(r.action).toBe("retry");
- });
-
- it("ECONNREFUSED → ProviderConnectionError", () => {
- const r = classifyRuntimeError("connect ECONNREFUSED 127.0.0.1:8080");
- expect(r.errorClass).toBe("ProviderConnectionError");
- expect(r.action).toBe("retry_jitter");
- });
-
- it("ECONNRESET → ProviderConnectionError", () => {
- const r = classifyRuntimeError("read ECONNRESET");
- expect(r.errorClass).toBe("ProviderConnectionError");
- });
-
- it("Unable to connect to API → ProviderConnectionError", () => {
- const r = classifyRuntimeError("Unable to connect to API endpoint");
- expect(r.errorClass).toBe("ProviderConnectionError");
- });
-
- it("unknown error → RuntimeError", () => {
- const r = classifyRuntimeError("something completely unknown happened");
- expect(r.errorClass).toBe("RuntimeError");
- expect(r.action).toBe("report");
- });
-
- it("httpStatus override via parameter", () => {
- const r = classifyRuntimeError("some generic message", 429);
- expect(r.errorClass).toBe("RateLimitError");
- });
-
- it("explicit token takes priority over HTTP status", () => {
- const r = classifyRuntimeError("TimeoutError: HTTP 429 rate limited", 429);
- expect(r.errorClass).toBe("TimeoutError");
- });
-});
-
-describe("scrubDiagnosticText", () => {
- it("redacts sk-ant tokens", () => {
- const result = scrubDiagnosticText("key=sk-ant-abc123-xyz789 failed");
- expect(result).toContain("sk-ant-***");
- expect(result).not.toContain("abc123");
- });
-
- it("redacts sk-proj tokens", () => {
- const result = scrubDiagnosticText("token: sk-proj-longtoken123");
- expect(result).toContain("sk-proj-***");
- expect(result).not.toContain("longtoken123");
- });
-
- it("redacts Bearer tokens", () => {
- const result = scrubDiagnosticText("Authorization: Bearer eyJhbGciOiJIUzI1Ni.token");
- expect(result).toContain("Bearer ***");
- expect(result).not.toContain("eyJhbGciOiJIUzI1Ni");
- });
-
- it("redacts email addresses", () => {
- const result = scrubDiagnosticText("user [email protected] failed");
- expect(result).toContain("***@***.***");
- expect(result).not.toContain("[email protected]");
- });
-
- it("redacts URL credentials", () => {
- const result = scrubDiagnosticText("https://admin:[email protected]/api");
- expect(result).toContain("://***:***@");
- expect(result).not.toContain("admin:secret");
- });
-
- it("redacts home directory paths", () => {
- const result = scrubDiagnosticText("file at /Users/john/.config/app.json");
- expect(result).toContain("/***");
- expect(result).not.toContain("/Users/john");
- });
-});
diff --git a/src/cli/daemon/steering/__tests__/notificationState.test.ts b/src/cli/daemon/steering/__tests__/notificationState.test.ts
deleted file mode 100644
index de4c5e09a..000000000
--- a/src/cli/daemon/steering/__tests__/notificationState.test.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import {
- RuntimeNotificationState,
- inboxNoticeMessageIdentity,
- computeInboxNoticeFingerprint,
-} from "../notificationState.js";
-
-describe("inboxNoticeMessageIdentity", () => {
- it("numeric seq gets s: prefix", () => {
- expect(inboxNoticeMessageIdentity({ seq: 42 })).toBe("s:42");
- });
-
- it("string message_id gets m: prefix", () => {
- expect(inboxNoticeMessageIdentity({ message_id: "abc" })).toBe("m:abc");
- });
-
- it("string id gets m: prefix", () => {
- expect(inboxNoticeMessageIdentity({ id: "xyz" })).toBe("m:xyz");
- });
-
- it("empty fields return empty string", () => {
- expect(inboxNoticeMessageIdentity({})).toBe("");
- });
-
- it("invalid seq (NaN) falls through to id", () => {
- expect(inboxNoticeMessageIdentity({ seq: NaN as unknown as number, id: "fallback" })).toBe("m:fallback");
- });
-
- it("negative seq falls through", () => {
- expect(inboxNoticeMessageIdentity({ seq: -1, message_id: "mid" })).toBe("m:mid");
- });
-
- it("seq priority over message_id", () => {
- expect(inboxNoticeMessageIdentity({ seq: 5, message_id: "mid" })).toBe("s:5");
- });
-});
-
-describe("computeInboxNoticeFingerprint", () => {
- it("empty messages → empty fingerprint", () => {
- expect(computeInboxNoticeFingerprint([])).toBe("");
- });
-
- it("sorted keys joined by comma", () => {
- const fp = computeInboxNoticeFingerprint([{ seq: 2 }, { seq: 1 }]);
- expect(fp).toBe("s:1,s:2");
- });
-
- it("skips messages with no identity", () => {
- const fp = computeInboxNoticeFingerprint([{ seq: 1 }, {}]);
- expect(fp).toBe("s:1");
- });
-});
-
-describe("RuntimeNotificationState", () => {
- beforeEach(() => { vi.useFakeTimers(); });
- afterEach(() => { vi.useRealTimers(); });
-
- describe("isDuplicateNotice", () => {
- it("same fingerprint + same session → duplicate", () => {
- const ns = new RuntimeNotificationState();
- ns.recordNoticeWritten("fp1", "sess1");
- expect(ns.isDuplicateNotice("fp1", "sess1")).toBe(true);
- });
-
- it("same fingerprint + different session → not duplicate", () => {
- const ns = new RuntimeNotificationState();
- ns.recordNoticeWritten("fp1", "sess1");
- expect(ns.isDuplicateNotice("fp1", "sess2")).toBe(false);
- });
-
- it("empty fingerprint → never duplicate", () => {
- const ns = new RuntimeNotificationState();
- ns.recordNoticeWritten("", "sess1");
- expect(ns.isDuplicateNotice("", "sess1")).toBe(false);
- });
- });
-
- describe("session boundary resets contribution tracking", () => {
- it("filterUncontributedMessages returns all on new session", () => {
- const ns = new RuntimeNotificationState();
- ns.recordNoticeWritten("fp1", "sess1", [{ seq: 1 }]);
- const result = ns.filterUncontributedMessages([{ seq: 1 }], "sess2");
- expect(result).toHaveLength(1);
- });
-
- it("filterUncontributedMessages filters contributed in same session", () => {
- const ns = new RuntimeNotificationState();
- ns.recordNoticeWritten("fp1", "sess1", [{ seq: 1 }, { seq: 2 }]);
- const result = ns.filterUncontributedMessages([{ seq: 1 }, { seq: 3 }], "sess1");
- expect(result).toHaveLength(1);
- expect(result[0].seq).toBe(3);
- });
- });
-
- describe("debounce timer", () => {
- it("schedule fires after delay", () => {
- const ns = new RuntimeNotificationState();
- let called = false;
- ns.schedule(() => { called = true; }, 100);
- expect(called).toBe(false);
- vi.advanceTimersByTime(100);
- expect(called).toBe(true);
- });
-
- it("second schedule returns false while armed", () => {
- const ns = new RuntimeNotificationState();
- expect(ns.schedule(() => {}, 100)).toBe(true);
- expect(ns.schedule(() => {}, 100)).toBe(false);
- });
-
- it("takePendingAndClearTimer cancels timer", () => {
- const ns = new RuntimeNotificationState();
- ns.add(3);
- let called = false;
- ns.schedule(() => { called = true; }, 100);
- const count = ns.takePendingAndClearTimer();
- expect(count).toBe(3);
- vi.advanceTimersByTime(200);
- expect(called).toBe(false);
- });
- });
-
- describe("encode failure tracking", () => {
- it("recordNoticeEncodeFailed caches failure", () => {
- const ns = new RuntimeNotificationState();
- ns.recordNoticeEncodeFailed("fp1", "sess1");
- expect(ns.isDuplicateEncodeFailedNotice("fp1", "sess1")).toBe(true);
- });
-
- it("successful write clears encode failure", () => {
- const ns = new RuntimeNotificationState();
- ns.recordNoticeEncodeFailed("fp1", "sess1");
- ns.recordNoticeWritten("fp1", "sess1");
- expect(ns.isDuplicateEncodeFailedNotice("fp1", "sess1")).toBe(false);
- });
-
- it("empty fingerprint not cached", () => {
- const ns = new RuntimeNotificationState();
- ns.recordNoticeEncodeFailed("", "sess1");
- expect(ns.isDuplicateEncodeFailedNotice("", "sess1")).toBe(false);
- });
- });
-
- describe("pending count", () => {
- it("add increments, takePending resets", () => {
- const ns = new RuntimeNotificationState();
- ns.add(1);
- ns.add(2);
- expect(ns.pendingCount).toBe(3);
- const count = ns.takePendingAndClearTimer();
- expect(count).toBe(3);
- expect(ns.pendingCount).toBe(0);
- });
- });
-});
diff --git a/src/cli/daemon/steering/__tests__/progressState.test.ts b/src/cli/daemon/steering/__tests__/progressState.test.ts
deleted file mode 100644
index 686190560..000000000
--- a/src/cli/daemon/steering/__tests__/progressState.test.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { RuntimeProgressState } from "../progressState.js";
-
-describe("RuntimeProgressState", () => {
- it("starts with isStale=false", () => {
- const ps = new RuntimeProgressState(1000);
- expect(ps.isStale).toBe(false);
- expect(ps.staleSince).toBeNull();
- });
-
- describe("ageMs", () => {
- it("returns elapsed time since last event", () => {
- const ps = new RuntimeProgressState(1000);
- expect(ps.ageMs(3000)).toBe(2000);
- });
-
- it("resets after recordRealEvent", () => {
- const ps = new RuntimeProgressState(1000);
- ps.recordRealEvent("text", 5000);
- expect(ps.ageMs(6000)).toBe(1000);
- });
-
- it("resets after recordInternalProgress", () => {
- const ps = new RuntimeProgressState(1000);
- ps.recordInternalProgress("internal_progress", 5000);
- expect(ps.ageMs(6000)).toBe(1000);
- });
- });
-
- describe("shouldMarkStale", () => {
- it("returns true when elapsed > threshold", () => {
- const ps = new RuntimeProgressState(1000);
- expect(ps.shouldMarkStale(2000, 5000)).toBe(true);
- });
-
- it("returns false when elapsed < threshold", () => {
- const ps = new RuntimeProgressState(1000);
- expect(ps.shouldMarkStale(2000, 2500)).toBe(false);
- });
-
- it("returns false when already stale", () => {
- const ps = new RuntimeProgressState(1000);
- ps.markStale(2000);
- expect(ps.shouldMarkStale(500, 5000)).toBe(false);
- });
-
- it("uses ageMs internally", () => {
- const ps = new RuntimeProgressState(1000);
- ps.recordRealEvent("text", 4000);
- expect(ps.shouldMarkStale(2000, 5000)).toBe(false);
- expect(ps.shouldMarkStale(2000, 7000)).toBe(true);
- });
- });
-
- describe("markStale", () => {
- it("sets isStale and staleSince", () => {
- const ps = new RuntimeProgressState(1000);
- ps.markStale(5000);
- expect(ps.isStale).toBe(true);
- expect(ps.staleSince).toBe(5000);
- });
-
- it("is idempotent — second call does not reset staleSince", () => {
- const ps = new RuntimeProgressState(1000);
- ps.markStale(5000);
- ps.markStale(9000);
- expect(ps.staleSince).toBe(5000);
- });
- });
-
- describe("recordRealEvent", () => {
- it("clears stale flag", () => {
- const ps = new RuntimeProgressState(1000);
- ps.markStale(5000);
- expect(ps.isStale).toBe(true);
- ps.recordRealEvent("text", 6000);
- expect(ps.isStale).toBe(false);
- expect(ps.staleSince).toBeNull();
- });
- });
-
- describe("recordInternalProgress", () => {
- it("does NOT clear stale flag", () => {
- const ps = new RuntimeProgressState(1000);
- ps.markStale(5000);
- ps.recordInternalProgress("internal_progress", 6000);
- expect(ps.isStale).toBe(true);
- });
- });
-
- describe("processEvent", () => {
- it("text → recordRealEvent", () => {
- const ps = new RuntimeProgressState(1000);
- ps.markStale(2000);
- ps.processEvent({ kind: "text", text: "hi" }, 3000);
- expect(ps.isStale).toBe(false);
- });
-
- it("tool_call → recordRealEvent", () => {
- const ps = new RuntimeProgressState(1000);
- ps.markStale(2000);
- ps.processEvent({ kind: "tool_call", name: "Bash" }, 3000);
- expect(ps.isStale).toBe(false);
- });
-
- it("internal_progress → recordInternalProgress", () => {
- const ps = new RuntimeProgressState(1000);
- ps.markStale(2000);
- ps.processEvent({ kind: "internal_progress" }, 3000);
- expect(ps.isStale).toBe(true);
- });
-
- it("compaction_started → recordInternalProgress", () => {
- const ps = new RuntimeProgressState(1000);
- ps.markStale(2000);
- ps.processEvent({ kind: "compaction_started" }, 3000);
- expect(ps.isStale).toBe(true);
- });
- });
-});
diff --git a/src/cli/daemon/steering/__tests__/turnState.test.ts b/src/cli/daemon/steering/__tests__/turnState.test.ts
deleted file mode 100644
index 7ff510b17..000000000
--- a/src/cli/daemon/steering/__tests__/turnState.test.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { RuntimeTurnState } from "../turnState.js";
-
-describe("RuntimeTurnState", () => {
- it("starts with isInTurn=false and canSteerBusy=false", () => {
- const ts = new RuntimeTurnState();
- expect(ts.isInTurn).toBe(false);
- expect(ts.turnId).toBeNull();
- expect(ts.canSteerBusy).toBe(false);
- });
-
- it("markTurnStarted sets isInTurn=true and canSteerBusy=true", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("turn-1");
- expect(ts.isInTurn).toBe(true);
- expect(ts.turnId).toBe("turn-1");
- expect(ts.canSteerBusy).toBe(true);
- });
-
- it("markTurnCompleted sets isInTurn=false, canSteerBusy=false", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("turn-1");
- ts.markTurnCompleted();
- expect(ts.isInTurn).toBe(false);
- expect(ts.turnId).toBeNull();
- expect(ts.canSteerBusy).toBe(false);
- });
-
- it("markTurnStarted without turnId preserves null turnId", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted();
- expect(ts.isInTurn).toBe(false);
- expect(ts.turnId).toBeNull();
- expect(ts.canSteerBusy).toBe(false);
- });
-
- it("canSteerBusy=false after markToolBoundary", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("t1");
- expect(ts.canSteerBusy).toBe(true);
- ts.markToolBoundary();
- expect(ts.canSteerBusy).toBe(false);
- });
-
- it("canSteerBusy=true after markProgress", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("t1");
- ts.markToolBoundary();
- expect(ts.canSteerBusy).toBe(false);
- ts.markProgress();
- expect(ts.canSteerBusy).toBe(true);
- });
-
- it("markToolBoundary → markProgress cycle", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("t1");
- ts.markToolBoundary();
- expect(ts.canSteerBusy).toBe(false);
- ts.markProgress();
- expect(ts.canSteerBusy).toBe(true);
- ts.markToolBoundary();
- expect(ts.canSteerBusy).toBe(false);
- });
-
- it("thinking event closes gate", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("t1");
- ts.markToolBoundary(); // thinking
- expect(ts.canSteerBusy).toBe(false);
- });
-
- it("compaction closes gate, compaction_finished reopens", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("t1");
- ts.markToolBoundary(); // compaction_started
- expect(ts.canSteerBusy).toBe(false);
- ts.markProgress(); // compaction_finished
- expect(ts.canSteerBusy).toBe(true);
- });
-
- it("adoptTurnId updates turnId without touching gate", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("t1");
- ts.markToolBoundary();
- expect(ts.canSteerBusy).toBe(false);
- ts.adoptTurnId("t2");
- expect(ts.turnId).toBe("t2");
- expect(ts.canSteerBusy).toBe(false); // gate still closed
- });
-
- it("reset clears all state", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("t1");
- ts.markToolBoundary();
- ts.reset();
- expect(ts.isInTurn).toBe(false);
- expect(ts.turnId).toBeNull();
- expect(ts.canSteerBusy).toBe(false);
- });
-
- it("multiple start/complete cycles work", () => {
- const ts = new RuntimeTurnState();
- ts.markTurnStarted("t1");
- expect(ts.isInTurn).toBe(true);
- expect(ts.canSteerBusy).toBe(true);
- ts.markTurnCompleted();
- expect(ts.isInTurn).toBe(false);
- ts.markTurnStarted("t2");
- expect(ts.isInTurn).toBe(true);
- expect(ts.turnId).toBe("t2");
- expect(ts.canSteerBusy).toBe(true);
- });
-});
diff --git a/src/cli/daemon/steering/apmStateMachine.ts b/src/cli/daemon/steering/apmStateMachine.ts
deleted file mode 100644
index f65029bfc..000000000
--- a/src/cli/daemon/steering/apmStateMachine.ts
+++ /dev/null
@@ -1,302 +0,0 @@
-/**
- * APM (Agent Process Manager) gated-steering state machine.
- *
- * Where `RuntimeTurnState` answers "is it safe *right now*?", 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;
-
-type ApmPhase =
- | "idle"
- | "tool_wait"
- | "tool_boundary"
- | "assistant_continuation"
- | "compacting"
- | "error";
-
-export interface ApmGatedSteeringState {
- isIdle: boolean;
- expectedTerminationReason: string | null;
- phase: ApmPhase;
- outstandingToolUses: number;
- compacting: boolean;
- toolBoundaryFlushDisabled: boolean;
- lastFlushReason: string | null;
- recentEvents: string[];
- pendingMessages: string[];
-}
-
-export type StdinDeliveryEffect = {
- kind: "notify_stdin" | "deliver_stdin";
- reason: string;
- stdinMode: "busy" | "idle";
- clauseId: "SMR-002";
-};
-
-export function createInitialApmState(): ApmGatedSteeringState {
- return {
- isIdle: false,
- expectedTerminationReason: null,
- phase: "idle",
- outstandingToolUses: 0,
- compacting: false,
- toolBoundaryFlushDisabled: false,
- lastFlushReason: null,
- recentEvents: [],
- pendingMessages: [],
- };
-}
-
-/* ------------------------------------------------------------------ */
-/* Phase transitions */
-/* ------------------------------------------------------------------ */
-
-export function reduceApmIdleState(
- state: ApmGatedSteeringState,
- input: { isIdle: boolean },
-): { nextState: ApmGatedSteeringState } {
- return { nextState: { ...state, isIdle: input.isIdle } };
-}
-
-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" } };
-}
-
-/* ------------------------------------------------------------------ */
-/* Delivery decisions (emit effects) */
-/* ------------------------------------------------------------------ */
-
-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.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 reduceApmGatedTurnEnd(
- state: ApmGatedSteeringState,
- input: {
- inboxLength?: number;
- supportsStdinNotification?: boolean;
- hasSession?: boolean;
- } = {},
-): { nextState: ApmGatedSteeringState; effects: StdinDeliveryEffect[] } {
- const shouldDeliverQueuedMessages = Boolean(
- input.inboxLength && input.inboxLength > 0 && input.supportsStdinNotification && input.hasSession,
- );
- return {
- nextState: {
- ...state,
- isIdle: !shouldDeliverQueuedMessages,
- phase: "idle",
- outstandingToolUses: 0,
- compacting: false,
- pendingMessages: shouldDeliverQueuedMessages ? state.pendingMessages : [],
- },
- effects: shouldDeliverQueuedMessages
- ? [{ kind: "deliver_stdin", reason: "turn_end", stdinMode: "idle", clauseId: "SMR-002" }]
- : [],
- };
-}
-
-export function reduceApmGatedError(
- state: ApmGatedSteeringState,
- input: { disableToolBoundaryFlush?: boolean } = {},
-): { nextState: ApmGatedSteeringState; shouldDisableToolBoundaryFlush: boolean } {
- const shouldDisableToolBoundaryFlush = input.disableToolBoundaryFlush === true;
- return {
- nextState: {
- ...state,
- phase: "error",
- compacting: false,
- toolBoundaryFlushDisabled: state.toolBoundaryFlushDisabled || shouldDisableToolBoundaryFlush,
- },
- shouldDisableToolBoundaryFlush,
- };
-}
-
-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),
- },
- };
-}
-
-/* ------------------------------------------------------------------ */
-/* Alook-specific: enqueue pending messages */
-/* ------------------------------------------------------------------ */
-
-export function reduceApmGatedEnqueue(
- state: ApmGatedSteeringState,
- message: string,
-): { nextState: ApmGatedSteeringState } {
- return {
- nextState: {
- ...state,
- pendingMessages: [...state.pendingMessages, message],
- },
- };
-}
-
-/* ------------------------------------------------------------------ */
-/* Recovery / termination */
-/* ------------------------------------------------------------------ */
-
-export function reduceApmStalledRecoveryTermination(
- state: ApmGatedSteeringState,
- input: {
- inboxLength: number;
- staleForMs: number;
- staleThresholdMs: number;
- runtimeProgressIsStale: boolean;
- hasSession: boolean;
- busyDeliveryMode: string;
- hasDirectStdinRecoveryEvidence: 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 supportsStdinNotification = input.busyDeliveryMode !== "none";
- const directStdinRuntime = supportsStdinNotification && input.busyDeliveryMode === "direct";
- const canRestartDirectStdinProcess =
- directStdinRuntime &&
- input.hasSession &&
- (state.outstandingToolUses === 0 || input.hasDirectStdinRecoveryEvidence);
- const canRestartStalledProcess = !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/cli/daemon/steering/errorDiagnostics.ts b/src/cli/daemon/steering/errorDiagnostics.ts
deleted file mode 100644
index efdcd97a4..000000000
--- a/src/cli/daemon/steering/errorDiagnostics.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-/**
- * Runtime error diagnostics — classify a runtime failure into a stable class
- * and reason, decide whether it needs user action (re-auth), and build a
- * scrubbed telemetry envelope.
- *
- * Classification priority:
- * 1. An explicit `XxxError` / `XxxException` token in the message.
- * 2. HTTP status code (429/401/403/404/5xx/other 4xx).
- * 3. Text-pattern regexes (rate limit, timeout, connection, …).
- * 4. Fallback: `RuntimeError`.
- */
-
-type ErrorClass =
- | "RateLimitError"
- | "AuthError"
- | "NotFoundError"
- | "ModelConfigError"
- | "TimeoutError"
- | "ProviderConnectionError"
- | "ProviderStreamError"
- | "ProviderServerError"
- | "ProviderApiError"
- | "RuntimeError";
-
-type ErrorAction = "retry" | "retry_backoff" | "retry_jitter" | "abort" | "report";
-
-export interface ClassifiedError {
- errorClass: ErrorClass;
- action: ErrorAction;
- reason: string;
-}
-
-const ACTION_BY_CLASS: Record<ErrorClass, ErrorAction> = {
- RateLimitError: "retry_backoff",
- AuthError: "abort",
- NotFoundError: "report",
- ModelConfigError: "abort",
- TimeoutError: "retry",
- ProviderConnectionError: "retry_jitter",
- ProviderStreamError: "retry",
- ProviderServerError: "retry",
- ProviderApiError: "report",
- RuntimeError: "report",
-};
-
-const EXPLICIT_TOKEN_RE = /\b([A-Z][A-Za-z0-9_]*(?:Error|Exception))\b/;
-
-const EXPLICIT_TOKEN_MAP: Record<string, ErrorClass> = {
- RateLimitError: "RateLimitError",
- TooManyRequestsError: "RateLimitError",
- AuthenticationError: "AuthError",
- AuthorizationError: "AuthError",
- PermissionError: "AuthError",
- NotFoundError: "NotFoundError",
- ModelNotFoundError: "ModelConfigError",
- TimeoutError: "TimeoutError",
- ConnectionError: "ProviderConnectionError",
- APIConnectionError: "ProviderConnectionError",
- StreamError: "ProviderStreamError",
- InternalServerError: "ProviderServerError",
- APIError: "ProviderApiError",
- BadRequestError: "ProviderApiError",
-};
-
-export function extractHttpStatus(message: string): number | null {
- const labeled = /\b(?:HTTP|status(?:\s+code)?|API\s+Error)[:\s]+([45]\d{2})\b/i.exec(message);
- if (labeled) return Number(labeled[1]);
- const semantic = /\b([45]\d{2})\s+(?:Unauthorized|Forbidden|Not Found|Too Many Requests|Internal Server Error|Bad Gateway|Service Unavailable|Gateway Timeout)\b/i.exec(
- message,
- );
- return semantic ? Number(semantic[1]) : null;
-}
-
-const AUTH_ACTION_REQUIRED_PATTERNS: RegExp[] = [
- /access token could not be refreshed/i,
- /\btoken_(?:revoked|invalidated)\b/i,
- /refresh token was already used/i,
- /access token.*invalidated/i,
- /authentication token has been invalidated/i,
- /logged out or signed in to another account/i,
- /not logged in/i,
- /not signed in/i,
- /login required/i,
- /log in first/i,
- /please log in/i,
- /authentication failed/i,
- /auth(?:entication)? failed/i,
- /authentication timed out/i,
- /missing (?:api )?token/i,
- /no (?:api )?token/i,
- /missing credentials/i,
- /credentials? not found/i,
- /invalid api key/i,
- /api key (?:is )?not set/i,
- /token revoked/i,
- /refresh token expired/i,
- /session expired/i,
- /unauthorized/i,
- /forbidden/i,
- /invalid.?token/i,
-];
-
-const RATE_LIMIT_PATTERNS = [
- /too many requests/i,
- /rate.?limit/i,
- /quota.?exceeded/i,
- /overloaded/i,
-];
-
-const MODEL_CONFIG_PATTERNS = [
- /model.?not.?(?:found|supported|available)/i,
- /invalid.?model/i,
- /does not exist/i,
-];
-
-const TIMEOUT_PATTERNS = [
- /timeout/i,
- /ETIMEDOUT/,
- /timed.?out/i,
- /deadline.?exceeded/i,
-];
-
-const CONNECTION_PATTERNS = [
- /ECONNREFUSED/,
- /ECONNRESET/,
- /ENETUNREACH/,
- /EHOSTUNREACH/,
- /EAI_AGAIN/,
- /ENOTFOUND/,
- /connection.?refused/i,
- /connection.?reset/i,
- /network.?error/i,
- /Unable to connect to API/i,
-];
-
-const STREAM_PATTERNS = [
- /stream.?error/i,
- /stream closed before response/i,
- /error decoding response body/i,
- /premature.?close/i,
- /aborted/i,
-];
-
-const SERVER_PATTERNS = [
- /internal.?server/i,
- /bad.?gateway/i,
- /service.?unavailable/i,
-];
-
-function classifyByExplicitToken(message: string): ErrorClass | null {
- const match = EXPLICIT_TOKEN_RE.exec(message);
- if (!match) return null;
- const token = match[1];
- return EXPLICIT_TOKEN_MAP[token] ?? null;
-}
-
-function classifyByHttpStatus(httpStatus: number): ErrorClass {
- if (httpStatus === 429) return "RateLimitError";
- if (httpStatus === 401 || httpStatus === 403) return "AuthError";
- if (httpStatus === 404) return "NotFoundError";
- if (httpStatus >= 500) return "ProviderServerError";
- return "ProviderApiError";
-}
-
-function classifyByTextPatterns(message: string): ErrorClass | null {
- for (const pat of RATE_LIMIT_PATTERNS) {
- if (pat.test(message)) return "RateLimitError";
- }
- for (const pat of AUTH_ACTION_REQUIRED_PATTERNS) {
- if (pat.test(message)) return "AuthError";
- }
- for (const pat of MODEL_CONFIG_PATTERNS) {
- if (pat.test(message)) return "ModelConfigError";
- }
- for (const pat of TIMEOUT_PATTERNS) {
- if (pat.test(message)) return "TimeoutError";
- }
- for (const pat of CONNECTION_PATTERNS) {
- if (pat.test(message)) return "ProviderConnectionError";
- }
- for (const pat of STREAM_PATTERNS) {
- if (pat.test(message)) return "ProviderStreamError";
- }
- for (const pat of SERVER_PATTERNS) {
- if (pat.test(message)) return "ProviderServerError";
- }
- return null;
-}
-
-export function classifyRuntimeError(message: string, httpStatus?: number | null): ClassifiedError {
- // 1. Explicit Error/Exception token
- const byToken = classifyByExplicitToken(message);
- if (byToken) {
- return { errorClass: byToken, action: ACTION_BY_CLASS[byToken], reason: message };
- }
-
- // 2. HTTP status code
- const status = httpStatus ?? extractHttpStatus(message);
- if (status !== null && status !== undefined) {
- const cls = classifyByHttpStatus(status);
- return { errorClass: cls, action: ACTION_BY_CLASS[cls], reason: message };
- }
-
- // 3. Text patterns
- const byPattern = classifyByTextPatterns(message);
- if (byPattern) {
- return { errorClass: byPattern, action: ACTION_BY_CLASS[byPattern], reason: message };
- }
-
- // 4. Fallback
- return { errorClass: "RuntimeError", action: "report", reason: message };
-}
-
-/**
- * Redact sensitive data from diagnostic text for safe logging/telemetry.
- * Redacts: API tokens, emails, URL credentials, file paths with home dirs.
- */
-export function scrubDiagnosticText(text: string): string {
- let scrubbed = text;
-
- // API tokens
- scrubbed = scrubbed.replace(/sk-ant-[a-zA-Z0-9_-]+/g, "sk-ant-***");
- scrubbed = scrubbed.replace(/sk-proj-[a-zA-Z0-9_-]+/g, "sk-proj-***");
- scrubbed = scrubbed.replace(/sk-[a-zA-Z0-9_-]{20,}/g, "sk-***");
- scrubbed = scrubbed.replace(/Bearer\s+[a-zA-Z0-9._-]+/gi, "Bearer ***");
-
- // Email addresses
- scrubbed = scrubbed.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, "***@***.***");
-
- // URL credentials (user:pass@host)
- scrubbed = scrubbed.replace(/:\/\/[^:@\s]+:[^@\s]+@/g, "://***:***@");
-
- // Home directory paths
- scrubbed = scrubbed.replace(/\/(?:Users|home)\/[a-zA-Z0-9._-]+/g, "/***");
-
- return scrubbed;
-}
diff --git a/src/cli/daemon/steering/mailbox.ts b/src/cli/daemon/steering/mailbox.ts
deleted file mode 100644
index 17ef1a805..000000000
--- a/src/cli/daemon/steering/mailbox.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * Filesystem Mailbox — IPC between daemon and session-runner for steering.
- *
- * Protocol:
- * 1. Daemon atomically writes <seq>.json.tmp → renames to <seq>.json
- * 2. Session-runner watches inbox via fs.watch() + polling fallback
- * 3. Session-runner reads file, delivers to agent stdin
- * 4. Session-runner writes <seq>.ack (or <seq>.nack with reason)
- * 5. Daemon polls for ack within timeout, falls back on nack/timeout
- */
-
-import { mkdirSync, writeFileSync, readFileSync, renameSync, readdirSync, unlinkSync, rmSync, existsSync, watch, type FSWatcher } from "fs";
-import { join } from "path";
-import { createLogger } from "../../lib/logger.js";
-
-const log = createLogger({ module: "mailbox" });
-
-export interface SteerMessage {
- taskId: string;
- text: string;
- attachments: { localPath: string; filename: string; contentType: string }[];
- createdAt: string;
-}
-
-interface NackPayload {
- reason: string;
-}
-
-// --- Directory structure helpers ---
-
-export function inboxDir(baseDir: string, contextKey: string): string {
- const safeKey = contextKey.replace(/[^a-zA-Z0-9_:-]/g, "_");
- return join(baseDir, ".steering", safeKey, "inbox");
-}
-
-function ackDir(baseDir: string, contextKey: string): string {
- const safeKey = contextKey.replace(/[^a-zA-Z0-9_:-]/g, "_");
- return join(baseDir, ".steering", safeKey, "ack");
-}
-
-function steeringDir(baseDir: string, contextKey: string): string {
- const safeKey = contextKey.replace(/[^a-zA-Z0-9_:-]/g, "_");
- return join(baseDir, ".steering", safeKey);
-}
-
-// --- Daemon side (writer) ---
-
-export function ensureMailboxDirs(baseDir: string, contextKey: string): void {
- const inbox = inboxDir(baseDir, contextKey);
- const ack = ackDir(baseDir, contextKey);
- mkdirSync(inbox, { recursive: true });
- mkdirSync(ack, { recursive: true });
-}
-
-let seqCounter = 0;
-
-export function writeSteerMessage(baseDir: string, contextKey: string, message: SteerMessage): string {
- const inbox = inboxDir(baseDir, contextKey);
- const seq = String(++seqCounter).padStart(6, "0");
- const tmpPath = join(inbox, `${seq}.json.tmp`);
- const finalPath = join(inbox, `${seq}.json`);
- writeFileSync(tmpPath, JSON.stringify(message));
- renameSync(tmpPath, finalPath);
- return seq;
-}
-
-export function waitForAck(
- baseDir: string,
- contextKey: string,
- seq: string,
- timeoutMs: number = 3000,
-): Promise<{ acked: boolean; nackReason?: string }> {
- const ackPath = join(ackDir(baseDir, contextKey), `${seq}.ack`);
- const nackPath = join(ackDir(baseDir, contextKey), `${seq}.nack`);
-
- return new Promise((resolve) => {
- const deadline = Date.now() + timeoutMs;
- const pollInterval = 100;
-
- const check = () => {
- try {
- if (existsSync(ackPath)) {
- resolve({ acked: true });
- return;
- }
- if (existsSync(nackPath)) {
- let reason = "unknown";
- try {
- const content = readFileSync(nackPath, "utf-8");
- const parsed = JSON.parse(content) as NackPayload;
- reason = parsed.reason || "unknown";
- } catch { /* best-effort */ }
- resolve({ acked: false, nackReason: reason });
- return;
- }
- } catch { /* best-effort */ }
-
- if (Date.now() >= deadline) {
- resolve({ acked: false, nackReason: "timeout" });
- return;
- }
- setTimeout(check, pollInterval);
- };
- check();
- });
-}
-
-// --- Session-runner side (reader) ---
-
-function readSteerMessage(filePath: string): SteerMessage | null {
- try {
- const content = readFileSync(filePath, "utf-8");
- return JSON.parse(content) as SteerMessage;
- } catch {
- return null;
- }
-}
-
-export function writeAck(baseDir: string, contextKey: string, seq: string): void {
- const ack = ackDir(baseDir, contextKey);
- mkdirSync(ack, { recursive: true });
- writeFileSync(join(ack, `${seq}.ack`), "");
-}
-
-export function writeNack(baseDir: string, contextKey: string, seq: string, reason: string): void {
- const ack = ackDir(baseDir, contextKey);
- mkdirSync(ack, { recursive: true });
- writeFileSync(join(ack, `${seq}.nack`), JSON.stringify({ reason }));
-}
-
-export function cleanupInboxFile(baseDir: string, contextKey: string, seq: string): void {
- try {
- unlinkSync(join(inboxDir(baseDir, contextKey), `${seq}.json`));
- } catch { /* best-effort */ }
-}
-
-export function cleanupSteeringDir(baseDir: string, contextKey: string): void {
- const dir = steeringDir(baseDir, contextKey);
- try {
- rmSync(dir, { recursive: true, force: true });
- } catch { /* best-effort */ }
-}
-
-export interface MailboxWatcher {
- stop(): void;
-}
-
-/**
- * Watch the inbox directory for new steer messages.
- * Calls onMessage for each new .json file detected.
- * Uses fs.watch + polling fallback for reliability.
- */
-export function watchInbox(
- baseDir: string,
- contextKey: string,
- onMessage: (seq: string, message: SteerMessage) => void,
-): MailboxWatcher {
- const inbox = inboxDir(baseDir, contextKey);
- mkdirSync(inbox, { recursive: true });
-
- const seen = new Set<string>();
- let stopped = false;
-
- const scan = () => {
- if (stopped) return;
- try {
- const files = readdirSync(inbox).filter((f) => f.endsWith(".json") && !f.endsWith(".tmp")).sort();
- for (const file of files) {
- if (seen.has(file)) continue;
- const seq = file.replace(/\.json$/, "");
- // Atomic claim: rename to .processing before reading to prevent redelivery on restart
- const srcPath = join(inbox, file);
- const claimPath = join(inbox, `${seq}.processing`);
- try {
- renameSync(srcPath, claimPath);
- } catch {
- continue; // Another process claimed it
- }
- seen.add(file);
- const msg = readSteerMessage(claimPath);
- // Remove claimed file after read
- try { unlinkSync(claimPath); } catch { /* best-effort */ }
- if (msg) {
- onMessage(seq, msg);
- }
- }
- } catch { /* best-effort */ }
- };
-
- // Initial scan for any pre-existing messages
- scan();
-
- // fs.watch for real-time detection
- let watcher: FSWatcher | null = null;
- try {
- watcher = watch(inbox, () => {
- if (!stopped) scan();
- });
- } catch {
- log.debug("fs.watch failed, relying on polling only");
- }
-
- // Polling fallback (200ms)
- const pollTimer = setInterval(scan, 200);
-
- return {
- stop() {
- stopped = true;
- clearInterval(pollTimer);
- watcher?.close();
- },
- };
-}
-
diff --git a/src/cli/daemon/steering/notificationState.ts b/src/cli/daemon/steering/notificationState.ts
deleted file mode 100644
index 15e5b98b2..000000000
--- a/src/cli/daemon/steering/notificationState.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- * RuntimeNotificationState — inbox-notice de-duplication and batching.
- *
- * When the daemon injects "you have N unread messages" notices into a running
- * agent, it must avoid re-sending the same notice set within a session (which
- * would spam the agent). This tracks a per-(session) fingerprint of the last
- * notice written, which message identities have already been contributed, and a
- * one-shot debounce timer for batching bursts.
- *
- * Identity priority: positive `seq` → `message_id` → `id`. Fingerprint = sorted,
- * comma-joined identities. Empty fingerprint ⇒ never a duplicate (fail toward
- * sending).
- */
-
-export interface InboxMessageLike {
- seq?: number;
- message_id?: string;
- id?: string;
-}
-
-export function inboxNoticeMessageIdentity(message: InboxMessageLike): string {
- const seq =
- typeof message.seq === "number" && Number.isFinite(message.seq) && message.seq > 0
- ? Math.floor(message.seq)
- : null;
- if (seq !== null) return `s:${seq}`;
- const id =
- typeof message.message_id === "string" && message.message_id.length > 0
- ? message.message_id
- : typeof message.id === "string" && message.id.length > 0
- ? message.id
- : "";
- return id.length > 0 ? `m:${id}` : "";
-}
-
-export function computeInboxNoticeFingerprint(messages: InboxMessageLike[]): string {
- const keys: string[] = [];
- for (const m of messages) {
- const key = inboxNoticeMessageIdentity(m);
- if (key.length > 0) keys.push(key);
- }
- if (keys.length === 0) return "";
- keys.sort();
- return keys.join(",");
-}
-
-export class RuntimeNotificationState {
- private pendingCountValue = 0;
- private timerValue: ReturnType<typeof setTimeout> | null = null;
-
- private lastNoticeFingerprint: string | null = null;
- private lastNoticeSessionId: string | null = null;
- private lastEncodeFailedFingerprint: string | null = null;
- private lastEncodeFailedSessionId: string | null = null;
-
- private contributedIdentities = new Set<string>();
- private contributionSessionId: string | null = null;
-
- get pendingCount(): number {
- return this.pendingCountValue;
- }
-
- isDuplicateNotice(fingerprint: string, sessionId: string): boolean {
- if (fingerprint.length === 0) return false;
- return this.lastNoticeFingerprint === fingerprint && this.lastNoticeSessionId === sessionId;
- }
-
- recordNoticeWritten(fingerprint: string, sessionId: string, messages: InboxMessageLike[] = []): void {
- this.lastNoticeFingerprint = fingerprint;
- this.lastNoticeSessionId = sessionId;
- this.lastEncodeFailedFingerprint = null;
- this.lastEncodeFailedSessionId = null;
- this.ensureContributionSession(sessionId);
- for (const message of messages) {
- const identity = inboxNoticeMessageIdentity(message);
- if (identity.length > 0) this.contributedIdentities.add(identity);
- }
- }
-
- recordNoticeEncodeFailed(fingerprint: string, sessionId: string): void {
- if (fingerprint.length === 0) return;
- this.lastEncodeFailedFingerprint = fingerprint;
- this.lastEncodeFailedSessionId = sessionId;
- }
-
- isDuplicateEncodeFailedNotice(fingerprint: string, sessionId: string): boolean {
- if (fingerprint.length === 0) return false;
- return this.lastEncodeFailedFingerprint === fingerprint && this.lastEncodeFailedSessionId === sessionId;
- }
-
- filterUncontributedMessages(messages: InboxMessageLike[], sessionId: string): InboxMessageLike[] {
- if (this.contributionSessionId !== sessionId) return messages;
- return messages.filter((m) => {
- const identity = inboxNoticeMessageIdentity(m);
- return identity.length === 0 || !this.contributedIdentities.has(identity);
- });
- }
-
- add(count = 1): void {
- this.pendingCountValue += count;
- }
-
- schedule(callback: () => void, delayMs: number): boolean {
- if (this.timerValue) return false;
- this.timerValue = setTimeout(() => {
- this.timerValue = null;
- callback();
- }, delayMs);
- this.timerValue.unref?.();
- return true;
- }
-
- takePendingAndClearTimer(): number {
- const count = this.pendingCountValue;
- this.pendingCountValue = 0;
- if (this.timerValue) {
- clearTimeout(this.timerValue);
- this.timerValue = null;
- }
- return count;
- }
-
- private ensureContributionSession(sessionId: string): void {
- if (this.contributionSessionId !== sessionId) {
- this.contributionSessionId = sessionId;
- this.contributedIdentities = new Set();
- }
- }
-}
diff --git a/src/cli/daemon/steering/progressState.ts b/src/cli/daemon/steering/progressState.ts
deleted file mode 100644
index f3e3c41a2..000000000
--- a/src/cli/daemon/steering/progressState.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * RuntimeProgressState — granular liveness detection.
- *
- * Distinguishes real events (tool_call, text, tool_output, turn_end) from
- * internal progress (streaming deltas, compaction). Real events reset clock
- * AND clear stale flag. Internal progress resets clock but does NOT clear stale.
- * markStale() is idempotent: second call does not reset staleSince.
- */
-
-import type { ParsedEvent } from "../types.js";
-
-export class RuntimeProgressState {
- private lastEventAt: number;
- private lastEventKind: string | null = null;
- private _staleSince: number | null = null;
- private _isStale = false;
-
- constructor(now: number = Date.now()) {
- this.lastEventAt = now;
- }
-
- get isStale(): boolean {
- return this._isStale;
- }
-
- get staleSince(): number | null {
- return this._staleSince;
- }
-
- get lastActivity(): number {
- return this.lastEventAt;
- }
-
- ageMs(nowMs: number = Date.now()): number {
- return nowMs - this.lastEventAt;
- }
-
- /**
- * Record a real event — resets clock AND clears stale flag.
- * Real events: text, tool_call, tool_output, turn_end
- */
- recordRealEvent(kind: string, now: number = Date.now()): void {
- this.lastEventAt = now;
- this.lastEventKind = kind;
- this._isStale = false;
- this._staleSince = null;
- }
-
- /**
- * Record internal progress — resets clock but does NOT clear stale flag.
- * Internal: internal_progress, compaction events, telemetry
- */
- recordInternalProgress(kind: string, now: number = Date.now()): void {
- this.lastEventAt = now;
- this.lastEventKind = kind;
- }
-
- /**
- * Mark as stale. Idempotent: second call does not reset staleSince.
- */
- markStale(now: number = Date.now()): void {
- if (this._isStale) return;
- this._isStale = true;
- this._staleSince = now;
- }
-
- /**
- * Check if the agent should be considered stale given a threshold.
- */
- shouldMarkStale(thresholdMs: number, now: number = Date.now()): boolean {
- if (this._isStale) return false; // already stale
- return this.ageMs(now) > thresholdMs;
- }
-
- /**
- * Convenience: process a ParsedEvent and record it appropriately.
- */
- processEvent(event: ParsedEvent, now: number = Date.now()): void {
- switch (event.kind) {
- case "text":
- case "tool_call":
- case "tool_output":
- case "turn_end":
- case "session_init":
- case "error":
- this.recordRealEvent(event.kind, now);
- break;
- case "internal_progress":
- case "compaction_started":
- case "compaction_finished":
- case "telemetry":
- case "thinking":
- this.recordInternalProgress(event.kind, now);
- break;
- default:
- this.recordInternalProgress(event.kind, now);
- }
- }
-}
diff --git a/src/cli/daemon/steering/turnState.ts b/src/cli/daemon/steering/turnState.ts
deleted file mode 100644
index 1be99e214..000000000
--- a/src/cli/daemon/steering/turnState.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * RuntimeTurnState — the fine-grained steering gate.
- *
- * For `busyDeliveryMode: "gated"` runtimes (Claude), the daemon may NOT inject a
- * busy message at an arbitrary instant: a raw stdin write mid-stream can collide
- * with an active signed thinking block. This tiny state machine tracks whether
- * we're currently at a safe point.
- *
- * turn starts → gate OPEN (canSteerBusy = true)
- * tool boundary hit → gate SHUT (hold writes)
- * progress observed → gate OPEN
- * turn completes → idle, gate OPEN
- *
- * `canSteerBusy` is the single question the delivery path asks before writing.
- */
-export class RuntimeTurnState {
- private currentTurnId: string | null = null;
- private steeringGateActive = false;
-
- get isInTurn(): boolean {
- return this.currentTurnId !== null;
- }
-
- get turnId(): string | null {
- return this.currentTurnId;
- }
-
- get canSteerBusy(): boolean {
- return Boolean(this.currentTurnId && !this.steeringGateActive);
- }
-
- markTurnStarted(turnId?: string | null): void {
- if (turnId !== undefined && turnId !== null) {
- this.currentTurnId = turnId;
- }
- this.steeringGateActive = false;
- }
-
- adoptTurnId(turnId: string | null): void {
- this.currentTurnId = turnId;
- }
-
- markToolBoundary(): void {
- this.steeringGateActive = true;
- }
-
- markProgress(): void {
- this.steeringGateActive = false;
- }
-
- markTurnCompleted(): void {
- this.currentTurnId = null;
- this.steeringGateActive = false;
- }
-
- reset(): void {
- this.currentTurnId = null;
- this.steeringGateActive = false;
- }
-}
diff --git a/src/cli/daemon/types.test.ts b/src/cli/daemon/types.test.ts
deleted file mode 100644
index 9e618ee15..000000000
--- a/src/cli/daemon/types.test.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { fromApiTask } from "./types.js";
-import type { TaskApi } from "@alook/shared";
-
-describe("fromApiTask", () => {
- const baseTask: TaskApi = {
- id: "t1",
- agent_id: "a1",
- runtime_id: "rt1",
- conversation_id: "c1",
- workspace_id: "ws1",
- prompt: "hello",
- status: "dispatched",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: "2026-01-01T00:00:00Z",
- type: "user_dm_message",
- agent: null,
- };
-
- it("maps runtime_config from agent data", () => {
- const task: TaskApi = {
- ...baseTask,
- agent: {
- name: "Agent 1",
- instructions: "be helpful",
- runtime_config: { model: "custom-model" },
- email_addresses: [],
- colleagues: [],
- },
- };
-
- const result = fromApiTask(task);
- expect(result.agent?.runtimeConfig).toEqual({ model: "custom-model" });
- });
-
- it("sets runtimeConfig to empty object when runtime_config is empty", () => {
- const task: TaskApi = {
- ...baseTask,
- agent: {
- name: "Agent 1",
- instructions: "be helpful",
- runtime_config: {},
- email_addresses: [],
- colleagues: [],
- },
- };
-
- const result = fromApiTask(task);
- expect(result.agent?.runtimeConfig).toEqual({});
- });
-
- it("handles missing agent gracefully", () => {
- const result = fromApiTask(baseTask);
- expect(result.agent).toBeUndefined();
- });
-
- it("maps sender snake_case is_owner to camelCase isOwner", () => {
- const task: TaskApi = {
- ...baseTask,
- sender: { name: "Gus", email: "[email protected]", is_owner: true },
- };
- const result = fromApiTask(task);
- expect(result.sender).toEqual({ name: "Gus", email: "[email protected]", isOwner: true });
- });
-
- it("maps null sender to undefined", () => {
- const task: TaskApi = { ...baseTask, sender: null };
- const result = fromApiTask(task);
- expect(result.sender).toBeUndefined();
- });
-
- it("maps undefined sender to undefined", () => {
- const result = fromApiTask(baseTask);
- expect(result.sender).toBeUndefined();
- });
-
- it("maps colleagues from agent data", () => {
- const task: TaskApi = {
- ...baseTask,
- agent: {
- name: "Agent 1",
- instructions: "be helpful",
- runtime_config: {},
- colleagues: [
- { name: "Scout", email: "[email protected]", description: "Researcher", instruction: "Share findings" },
- ],
- } as any,
- };
- const result = fromApiTask(task);
- expect(result.agent?.colleagues).toEqual([
- { name: "Scout", email: "[email protected]", description: "Researcher", instruction: "Share findings" },
- ]);
- });
-
- it("defaults colleagues to empty array when missing", () => {
- const task: TaskApi = {
- ...baseTask,
- agent: {
- name: "Agent 1",
- instructions: "be helpful",
- runtime_config: {},
- email_addresses: [],
- colleagues: [],
- },
- };
- const result = fromApiTask(task);
- expect(result.agent?.colleagues).toEqual([]);
- });
-});
diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.ts
deleted file mode 100644
index a1ce02f1a..000000000
--- a/src/cli/daemon/types.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-interface TaskSender {
- name: string;
- email: string;
- isOwner: boolean;
-}
-
-export interface Task {
- id: string;
- agentId: string;
- runtimeId: string;
- conversationId: string;
- workspaceId: string;
- prompt: string;
- status: string;
- priority: number;
- type: string;
- contextKey?: string | null;
- context?: Record<string, unknown>;
- agent?: TaskAgentData;
- sender?: TaskSender;
- repos?: RepoData[];
- createdAt: string;
- traceId: string | null;
- parentTaskId: string | null;
- channel: string | null;
-}
-
-export interface Attachment {
- path: string;
- content_type: string;
- filename: string;
-}
-
-interface ColleagueData {
- name: string;
- email: string;
- description: string;
- instruction: string;
-}
-
-interface TaskAgentData {
- id?: string;
- name: string;
- instructions: string;
- emailHandle?: string | null;
- emailAddresses?: string[];
- userEmail?: string | null;
- userName?: string | null;
- runtimeConfig?: Record<string, unknown>;
- colleagues?: ColleagueData[];
-}
-
-interface RepoData {
- url: string;
- description: string;
-}
-
-export interface AgentMessage {
- type:
- | "text"
- | "thinking"
- | "tool-use"
- | "tool-result"
- | "status"
- | "error"
- | "log";
- content?: string;
- tool?: string;
- callId?: string;
- input?: Record<string, unknown>;
- output?: string;
- status?: string;
- level?: string;
-}
-
-export interface AgentResult {
- status: "completed" | "failed" | "aborted" | "timeout";
- output: string;
- error: string;
- durationMs: number;
- sessionId: string;
-}
-
-export interface ExecOptions {
- cwd: string;
- model?: string;
- env?: Record<string, string>;
- maxTurns?: number;
- timeout?: number;
- resumeSessionId?: string;
- steeringEnabled?: boolean;
-}
-
-/** Serialized input passed from daemon to the detached session-runner process. */
-export interface SessionRunnerInput {
- task: Task;
- provider: string;
- cliPath: string;
- model: string;
- serverURL: string;
- token: string;
- workspacesRoot: string;
- agentTimeout: number;
- messageInactivityTimeout: number;
- logFilePath?: string;
- promptOverride?: string;
- steeringEnabled?: boolean;
- steeringMailboxDir?: string;
-}
-
-// --- Steering & ParsedEvent types ---
-
-type DriverLifecycleKind = "persistent" | "per_turn";
-
-export type BusyDeliveryMode = "gated" | "direct" | "none";
-
-export type StdinMode = "idle" | "busy";
-
-export interface DriverLifecycle {
- kind: DriverLifecycleKind;
- stdin?: "gated" | "direct" | "ignore";
- inFlightWake?: "queue" | "steer" | "coalesce_into_pending";
-}
-
-export interface EncodeOpts {
- sessionId?: string;
- threadId?: string;
- requestId?: number;
-}
-
-export type ParsedEvent =
- | { kind: "session_init"; sessionId: string }
- | { kind: "text"; text: string }
- | { kind: "thinking"; text: string }
- | { kind: "tool_call"; name: string; input?: unknown; callId?: string }
- | { kind: "tool_output"; name?: string; callId?: string; output?: string }
- | { kind: "turn_end"; sessionId?: string }
- | { kind: "telemetry"; name: string; source?: string; usageKind?: string; attrs: Record<string, unknown> }
- | { kind: "compaction_started" }
- | { kind: "compaction_finished" }
- | { kind: "permission_request"; requestId: string; payload: unknown }
- | { kind: "error"; message: string }
- | { kind: "internal_progress"; detail?: string; source?: string; itemType?: string; payloadBytes?: number }
- | { kind: "log"; content: string; level?: string };
-
-export interface RuntimeSessionDescriptor {
- lifecycle: DriverLifecycle;
- busyDeliveryMode: BusyDeliveryMode;
- supportsStdinNotification: boolean;
-}
-
-/** Convert a validated TaskApi (snake_case wire format) to the internal Task type. */
-export function fromApiTask(api: import("@alook/shared").TaskApi): Task {
- return {
- id: api.id,
- agentId: api.agent_id,
- runtimeId: api.runtime_id,
- conversationId: api.conversation_id,
- workspaceId: api.workspace_id,
- prompt: api.prompt,
- status: api.status,
- priority: api.priority,
- type: api.type,
- contextKey: api.context_key ?? null,
- context: (api.context as Record<string, unknown>) ?? undefined,
- agent: api.agent
- ? {
- name: api.agent.name,
- instructions: api.agent.instructions,
- emailHandle: api.agent.email_handle ?? undefined,
- emailAddresses: api.agent.email_addresses ?? [],
- userEmail: api.agent.user_email ?? undefined,
- userName: api.agent.user_name ?? undefined,
- runtimeConfig: api.agent.runtime_config ?? undefined,
- colleagues: api.agent.colleagues?.map((c) => ({
- name: c.name,
- email: c.email,
- description: c.description,
- instruction: c.instruction,
- })) ?? [],
- }
- : undefined,
- sender: api.sender
- ? { name: api.sender.name, email: api.sender.email, isOwner: api.sender.is_owner }
- : undefined,
- repos: undefined,
- createdAt: api.created_at,
- traceId: api.trace_id ?? null,
- parentTaskId: api.parent_task_id ?? null,
- channel: api.channel ?? null,
- };
-}
diff --git a/src/cli/daemon/update-handler.test.ts b/src/cli/daemon/update-handler.test.ts
deleted file mode 100644
index 1b54ff99a..000000000
--- a/src/cli/daemon/update-handler.test.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-
-const mockRunNpmUpdate = vi.fn();
-vi.mock("../lib/update.js", () => ({
- runNpmUpdate: (...args: any[]) => mockRunNpmUpdate(...args),
-}));
-vi.mock("../lib/logger.js", () => {
- const mockLog = { info: vi.fn(), error: vi.fn(), debug: vi.fn(), warn: vi.fn() };
- return { createLogger: () => mockLog, log: mockLog };
-});
-
-const mockReadFileSync = vi.fn();
-const mockWriteFileSync = vi.fn();
-const mockUnlinkSync = vi.fn();
-vi.mock("fs", () => ({
- readFileSync: (...args: any[]) => mockReadFileSync(...args),
- writeFileSync: (...args: any[]) => mockWriteFileSync(...args),
- unlinkSync: (...args: any[]) => mockUnlinkSync(...args),
-}));
-
-vi.mock("./config.js", () => ({
- lastUpdateMarkerPath: vi.fn((profile?: string) =>
- profile ? `/tmp/alook/last_update_${profile}` : "/tmp/alook/last_update",
- ),
-}));
-
-import {
- handleCliUpdate,
- isUpdating,
- resetUpdateState,
- readUpdateMarker,
- writeUpdateMarker,
- clearUpdateMarker,
-} from "./update-handler";
-
-describe("update-handler", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetUpdateState();
- mockReadFileSync.mockImplementation(() => { throw new Error("ENOENT"); });
- });
-
- it("calls runNpmUpdate and invokes onSuccess on success", async () => {
- mockRunNpmUpdate.mockResolvedValue({ success: true, output: "ok" });
- const onSuccess = vi.fn();
-
- await handleCliUpdate("1.0.0", onSuccess);
-
- expect(mockRunNpmUpdate).toHaveBeenCalledWith("1.0.0");
- expect(onSuccess).toHaveBeenCalled();
- });
-
- it("writes marker file after successful update", async () => {
- mockRunNpmUpdate.mockResolvedValue({ success: true, output: "ok" });
- const onSuccess = vi.fn();
-
- await handleCliUpdate("1.0.0", onSuccess);
-
- expect(mockWriteFileSync).toHaveBeenCalledWith(
- "/tmp/alook/last_update",
- "1.0.0",
- { mode: 0o600 },
- );
- });
-
- it("does not call onSuccess on failure", async () => {
- mockRunNpmUpdate.mockResolvedValue({ success: false, output: "error" });
- const onSuccess = vi.fn();
-
- await handleCliUpdate("1.0.0", onSuccess);
-
- expect(onSuccess).not.toHaveBeenCalled();
- });
-
- it("does not write marker file on failure", async () => {
- mockRunNpmUpdate.mockResolvedValue({ success: false, output: "error" });
- const onSuccess = vi.fn();
-
- await handleCliUpdate("1.0.0", onSuccess);
-
- expect(mockWriteFileSync).not.toHaveBeenCalled();
- });
-
- it("skips update when marker file matches target version", async () => {
- mockReadFileSync.mockReturnValue("1.0.0");
- const onSuccess = vi.fn();
-
- await handleCliUpdate("1.0.0", onSuccess);
-
- expect(mockRunNpmUpdate).not.toHaveBeenCalled();
- expect(onSuccess).not.toHaveBeenCalled();
- });
-
- it("proceeds with update when marker file has different version", async () => {
- mockReadFileSync.mockReturnValue("0.9.0");
- mockRunNpmUpdate.mockResolvedValue({ success: true, output: "ok" });
- const onSuccess = vi.fn();
-
- await handleCliUpdate("1.0.0", onSuccess);
-
- expect(mockRunNpmUpdate).toHaveBeenCalledWith("1.0.0");
- expect(onSuccess).toHaveBeenCalled();
- });
-
- it("retries up to 3 times then stops", async () => {
- mockRunNpmUpdate.mockResolvedValue({ success: false, output: "fail" });
- const onSuccess = vi.fn();
-
- await handleCliUpdate("1.0.0", onSuccess);
- await handleCliUpdate("1.0.0", onSuccess);
- await handleCliUpdate("1.0.0", onSuccess);
- await handleCliUpdate("1.0.0", onSuccess); // should be skipped
-
- expect(mockRunNpmUpdate).toHaveBeenCalledTimes(3);
- });
-
- it("prevents concurrent updates", async () => {
- let resolve: () => void;
- mockRunNpmUpdate.mockReturnValue(
- new Promise((r) => { resolve = () => r({ success: true, output: "" }); }),
- );
- const onSuccess = vi.fn();
-
- const p1 = handleCliUpdate("1.0.0", onSuccess);
- expect(isUpdating()).toBe(true);
-
- // second call while first is in-flight should be a no-op
- await handleCliUpdate("1.0.0", onSuccess);
- expect(mockRunNpmUpdate).toHaveBeenCalledTimes(1);
-
- resolve!();
- await p1;
- expect(isUpdating()).toBe(false);
- });
-});
-
-describe("update marker helpers", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("readUpdateMarker returns version from file", () => {
- mockReadFileSync.mockReturnValue("1.2.3\n");
- expect(readUpdateMarker()).toBe("1.2.3");
- });
-
- it("readUpdateMarker returns null when file does not exist", () => {
- mockReadFileSync.mockImplementation(() => { throw new Error("ENOENT"); });
- expect(readUpdateMarker()).toBeNull();
- });
-
- it("writeUpdateMarker writes version to file", () => {
- writeUpdateMarker("2.0.0");
- expect(mockWriteFileSync).toHaveBeenCalledWith(
- "/tmp/alook/last_update",
- "2.0.0",
- { mode: 0o600 },
- );
- });
-
- it("writeUpdateMarker uses profile path when provided", () => {
- writeUpdateMarker("2.0.0", "staging");
- expect(mockWriteFileSync).toHaveBeenCalledWith(
- "/tmp/alook/last_update_staging",
- "2.0.0",
- { mode: 0o600 },
- );
- });
-
- it("clearUpdateMarker deletes the marker file", () => {
- clearUpdateMarker();
- expect(mockUnlinkSync).toHaveBeenCalledWith("/tmp/alook/last_update");
- });
-
- it("clearUpdateMarker does not throw when file is missing", () => {
- mockUnlinkSync.mockImplementation(() => { throw new Error("ENOENT"); });
- expect(() => clearUpdateMarker()).not.toThrow();
- });
-});
diff --git a/src/cli/daemon/update-handler.ts b/src/cli/daemon/update-handler.ts
deleted file mode 100644
index e6bbcea6d..000000000
--- a/src/cli/daemon/update-handler.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { readFileSync, writeFileSync, unlinkSync } from "fs";
-import { runNpmUpdate } from "../lib/update.js";
-import { createLogger } from "../lib/logger.js";
-
-const log = createLogger({ module: "updater" });
-import { lastUpdateMarkerPath } from "./config.js";
-
-let updating = false;
-let retryCount = 0;
-const MAX_RETRIES = 3;
-
-export function isUpdating(): boolean {
- return updating;
-}
-
-export function resetUpdateState(): void {
- updating = false;
- retryCount = 0;
-}
-
-export function readUpdateMarker(profile?: string): string | null {
- try {
- return readFileSync(lastUpdateMarkerPath(profile), "utf-8").trim() || null;
- } catch {
- return null;
- }
-}
-
-export function writeUpdateMarker(version: string, profile?: string): void {
- try {
- writeFileSync(lastUpdateMarkerPath(profile), version, { mode: 0o600 });
- } catch {
- // best-effort
- }
-}
-
-export function clearUpdateMarker(profile?: string): void {
- try {
- unlinkSync(lastUpdateMarkerPath(profile));
- } catch {
- // already gone
- }
-}
-
-export async function handleCliUpdate(
- version: string,
- onSuccess: () => void,
- profile?: string,
-): Promise<void> {
- if (updating) return;
- if (retryCount >= MAX_RETRIES) return;
-
- if (process.env.ALOOK_CMD_PREFIX) {
- log.info(`Skipping auto-update in app mode — user should run: npx @alook/app@latest update`);
- return;
- }
-
- const marker = readUpdateMarker(profile);
- if (marker === version) {
- log.info(`Skipping update to v${version} — already attempted (marker exists)`);
- return;
- }
-
- updating = true;
- try {
- log.info(`Updating CLI to v${version}...`);
- const result = await runNpmUpdate(version);
- if (result.success) {
- writeUpdateMarker(version, profile);
- log.info(`CLI updated to v${version} — restarting`);
- onSuccess();
- } else {
- retryCount++;
- log.error(`CLI update failed (attempt ${retryCount}/${MAX_RETRIES}): ${result.output}`);
- }
- } catch (e) {
- retryCount++;
- log.error(`CLI update error (attempt ${retryCount}/${MAX_RETRIES})`, e);
- } finally {
- updating = false;
- }
-}
diff --git a/src/cli/daemon/workspace-files.test.ts b/src/cli/daemon/workspace-files.test.ts
deleted file mode 100644
index a5b6f7153..000000000
--- a/src/cli/daemon/workspace-files.test.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach } from "vitest";
-import { join } from "path";
-import { mkdirSync, writeFileSync, rmSync } from "fs";
-import { tmpdir } from "os";
-import { readDirectoryTree, readFileContent, validatePath } from "./workspace-files";
-
-let workDir: string;
-
-beforeEach(() => {
- workDir = join(tmpdir(), `alook-test-files-${Date.now()}`);
- mkdirSync(workDir, { recursive: true });
-});
-
-afterEach(() => {
- rmSync(workDir, { recursive: true, force: true });
-});
-
-describe("validatePath", () => {
- it("returns resolved path for valid relative path", () => {
- const result = validatePath(workDir, "memory.md");
- expect(result).toBe(join(workDir, "memory.md"));
- });
-
- it("returns resolved path for nested path", () => {
- const result = validatePath(workDir, "experiences/workflow.md");
- expect(result).toBe(join(workDir, "experiences", "workflow.md"));
- });
-
- it("returns null for path traversal attempt", () => {
- expect(validatePath(workDir, "../../../etc/passwd")).toBeNull();
- });
-
- it("returns null for absolute path outside workdir", () => {
- expect(validatePath(workDir, "/tmp/evil")).toBeNull();
- });
-
- it("returns the workdir itself for '.'", () => {
- const result = validatePath(workDir, ".");
- expect(result).toBe(workDir);
- });
-});
-
-describe("readDirectoryTree", () => {
- it("lists files and directories sorted correctly", async () => {
- mkdirSync(join(workDir, "experiences"));
- writeFileSync(join(workDir, "memory.md"), "# Memory");
- writeFileSync(join(workDir, "CLAUDE.md"), "# Instructions");
-
- const entries = await readDirectoryTree(workDir, workDir);
-
- expect(entries.length).toBe(3);
- expect(entries[0].name).toBe("experiences");
- expect(entries[0].isDirectory).toBe(true);
- expect(entries[1].name).toBe("CLAUDE.md");
- expect(entries[1].isDirectory).toBe(false);
- expect(entries[2].name).toBe("memory.md");
- });
-
- it("skips all dotfiles and dotdirs", async () => {
- mkdirSync(join(workDir, ".git"));
- mkdirSync(join(workDir, ".context_timeline"));
- writeFileSync(join(workDir, ".hidden"), "secret");
- writeFileSync(join(workDir, "visible.md"), "hello");
-
- const entries = await readDirectoryTree(workDir, workDir);
- const names = entries.map((e) => e.name);
-
- expect(names).toContain("visible.md");
- expect(names).not.toContain(".context_timeline");
- expect(names).not.toContain(".git");
- expect(names).not.toContain(".hidden");
- });
-
- it("skips node_modules", async () => {
- mkdirSync(join(workDir, "node_modules"));
- writeFileSync(join(workDir, "index.js"), "// ok");
-
- const entries = await readDirectoryTree(workDir, workDir);
- const names = entries.map((e) => e.name);
-
- expect(names).not.toContain("node_modules");
- expect(names).toContain("index.js");
- });
-
- it("returns empty array for non-existent directory", async () => {
- const entries = await readDirectoryTree(join(workDir, "nope"), workDir);
- expect(entries).toEqual([]);
- });
-
- it("returns relative paths from basePath", async () => {
- mkdirSync(join(workDir, "sub"));
- writeFileSync(join(workDir, "sub", "file.txt"), "hi");
-
- const entries = await readDirectoryTree(join(workDir, "sub"), workDir);
-
- expect(entries[0].path).toBe(join("sub", "file.txt"));
- });
-
- it("includes size and modifiedAt for files", async () => {
- writeFileSync(join(workDir, "data.json"), '{"key":"value"}');
-
- const entries = await readDirectoryTree(workDir, workDir);
- const file = entries.find((e) => e.name === "data.json")!;
-
- expect(file.size).toBeGreaterThan(0);
- expect(file.modifiedAt).toBeTruthy();
- expect(new Date(file.modifiedAt).getTime()).toBeGreaterThan(0);
- });
-});
-
-describe("readFileContent", () => {
- it("reads text file content", async () => {
- writeFileSync(join(workDir, "readme.md"), "# Hello World");
-
- const result = await readFileContent(join(workDir, "readme.md"));
-
- expect(result.content).toBe("# Hello World");
- expect(result.isBinary).toBe(false);
- });
-
- it("marks unknown extensions as binary", async () => {
- writeFileSync(join(workDir, "image.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
-
- const result = await readFileContent(join(workDir, "image.png"));
-
- expect(result.content).toBeNull();
- expect(result.isBinary).toBe(true);
- });
-
- it("reads files with known extensions", async () => {
- for (const ext of [".json", ".ts", ".py", ".yaml", ".sh"]) {
- writeFileSync(join(workDir, `test${ext}`), "content");
- const result = await readFileContent(join(workDir, `test${ext}`));
- expect(result.isBinary).toBe(false);
- expect(result.content).toBe("content");
- }
- });
-
- it("throws for directories", async () => {
- mkdirSync(join(workDir, "subdir"));
- await expect(readFileContent(join(workDir, "subdir"))).rejects.toThrow("Cannot read a directory");
- });
-
- it("throws for files over 1MB", async () => {
- writeFileSync(join(workDir, "big.txt"), "x".repeat(1_048_577));
- await expect(readFileContent(join(workDir, "big.txt"))).rejects.toThrow("File too large");
- });
-
- it("reads extensionless files as text", async () => {
- writeFileSync(join(workDir, "Makefile"), "all: build");
- const result = await readFileContent(join(workDir, "Makefile"));
- expect(result.isBinary).toBe(false);
- expect(result.content).toBe("all: build");
- });
-});
diff --git a/src/cli/daemon/workspace-files.ts b/src/cli/daemon/workspace-files.ts
deleted file mode 100644
index 7504319ca..000000000
--- a/src/cli/daemon/workspace-files.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { readdir, stat, readFile } from "fs/promises";
-import { join, resolve, extname, relative, sep } from "path";
-import type { WorkspaceFileEntry } from "@alook/shared";
-
-const SKIP_DIRS = new Set([".git", "node_modules", ".next", ".wrangler", "__pycache__", ".venv"]);
-
-const TEXT_EXTENSIONS = new Set([
- ".md", ".txt", ".json", ".js", ".ts", ".tsx", ".jsx",
- ".py", ".rb", ".go", ".rs", ".toml", ".yaml", ".yml",
- ".html", ".css", ".scss", ".sh", ".bash", ".zsh",
- ".env", ".cfg", ".ini", ".xml", ".svg", ".sql",
- ".jsonl", ".log", ".csv",
-]);
-
-const MAX_FILE_SIZE = 1_048_576; // 1MB
-
-export async function readDirectoryTree(
- dirPath: string,
- basePath: string,
-): Promise<WorkspaceFileEntry[]> {
- let entries;
- try {
- entries = await readdir(dirPath, { withFileTypes: true });
- } catch {
- return [];
- }
-
- entries.sort((a, b) => {
- if (a.isDirectory() && !b.isDirectory()) return -1;
- if (!a.isDirectory() && b.isDirectory()) return 1;
- return a.name.localeCompare(b.name);
- });
-
- const results: WorkspaceFileEntry[] = [];
- for (const entry of entries) {
- if (entry.name.startsWith(".")) continue;
- if (SKIP_DIRS.has(entry.name)) continue;
- if (!entry.isDirectory()) {
- const ext = extname(entry.name).toLowerCase();
- if (ext !== "" && !TEXT_EXTENSIONS.has(ext)) continue;
- }
-
- const fullPath = join(dirPath, entry.name);
- let info;
- try {
- info = await stat(fullPath);
- } catch {
- continue;
- }
-
- results.push({
- name: entry.name,
- path: relative(basePath, fullPath),
- isDirectory: entry.isDirectory(),
- size: entry.isDirectory() ? 0 : info.size,
- modifiedAt: info.mtime.toISOString(),
- });
- }
- return results;
-}
-
-export async function readFileContent(
- filePath: string,
-): Promise<{ content: string | null; isBinary: boolean }> {
- const info = await stat(filePath);
- if (info.isDirectory()) throw new Error("Cannot read a directory");
- if (info.size > MAX_FILE_SIZE) throw new Error("File too large (>1MB)");
-
- const ext = extname(filePath).toLowerCase();
- if (ext !== "" && !TEXT_EXTENSIONS.has(ext)) {
- return { content: null, isBinary: true };
- }
-
- const content = await readFile(filePath, "utf-8");
- return { content, isBinary: false };
-}
-
-export function validatePath(agentWorkdir: string, requestedPath: string): string | null {
- const resolved = resolve(agentWorkdir, requestedPath);
- if (resolved !== agentWorkdir && !resolved.startsWith(agentWorkdir + sep)) return null;
- return resolved;
-}
diff --git a/src/cli/daemon/ws-client.test.ts b/src/cli/daemon/ws-client.test.ts
deleted file mode 100644
index f6b2c79c8..000000000
--- a/src/cli/daemon/ws-client.test.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { DaemonWsClient } from "./ws-client.js";
-
-class MockWebSocket extends EventTarget {
- static OPEN = 1;
- static CLOSED = 3;
-
- readyState = MockWebSocket.OPEN;
- url: string;
- send = vi.fn();
-
- constructor(url: string) {
- super();
- this.url = url;
- }
-
- close() {
- this.readyState = MockWebSocket.CLOSED;
- this.dispatchEvent(new Event("close"));
- }
-
- simulateOpen() {
- this.dispatchEvent(new Event("open"));
- }
-
- simulateMessage(data: string) {
- this.dispatchEvent(new MessageEvent("message", { data }));
- }
-
- simulateClose() {
- this.readyState = MockWebSocket.CLOSED;
- this.dispatchEvent(new Event("close"));
- }
-}
-
-function makeClient(overrides: Partial<ConstructorParameters<typeof DaemonWsClient>[0]> = {}) {
- return new DaemonWsClient({
- serverURL: "https://alook.ai",
- daemonId: "my-host",
- machineToken: "al_test123",
- onMessage: vi.fn(),
- onConnected: vi.fn(),
- onDisconnected: vi.fn(),
- ...overrides,
- });
-}
-
-describe("DaemonWsClient", () => {
- let originalWebSocket: typeof globalThis.WebSocket;
-
- beforeEach(() => {
- vi.useFakeTimers();
- originalWebSocket = globalThis.WebSocket;
- (globalThis as any).WebSocket = MockWebSocket;
- });
-
- afterEach(() => {
- vi.useRealTimers();
- globalThis.WebSocket = originalWebSocket;
- });
-
- it("constructs production URL correctly", () => {
- const client = makeClient();
- expect(client.getUrl()).toBe("wss://alook.ai/api/ws/daemon?daemonId=my-host");
- });
-
- it("constructs local development URL correctly", () => {
- const client = makeClient({ serverURL: "http://localhost:3000" });
- expect(client.getUrl()).toBe("ws://localhost:8789/?daemonId=my-host");
- });
-
- it("reports disconnected initially", () => {
- const client = makeClient();
- expect(client.isConnected()).toBe(false);
- });
-
- it("sends auth message on open", () => {
- const client = makeClient();
- client.connect();
-
- const ws = (client as any).ws as MockWebSocket;
- ws.simulateOpen();
-
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({
- type: "auth",
- machineToken: "al_test123",
- daemonId: "my-host",
- }));
- });
-
- it("sets connected=true and calls onConnected after auth.ok", () => {
- const onConnected = vi.fn();
- const client = makeClient({ onConnected });
- client.connect();
-
- const ws = (client as any).ws as MockWebSocket;
- ws.simulateOpen();
- ws.simulateMessage(JSON.stringify({ type: "auth.ok" }));
-
- expect(client.isConnected()).toBe(true);
- expect(onConnected).toHaveBeenCalledTimes(1);
- });
-
- it("validates messages with DaemonPushMessageSchema — valid message calls onMessage", () => {
- const onMessage = vi.fn();
- const client = makeClient({ onMessage });
- client.connect();
-
- const ws = (client as any).ws as MockWebSocket;
- ws.simulateOpen();
- ws.simulateMessage(JSON.stringify({ type: "auth.ok" }));
- ws.simulateMessage(JSON.stringify({ type: "daemon.rescan" }));
-
- expect(onMessage).toHaveBeenCalledTimes(1);
- expect(onMessage).toHaveBeenCalledWith({ type: "daemon.rescan" });
- });
-
- it("AUTH_REJECTED frame triggers onAuthRejected (before schema parse) and not onMessage", () => {
- const onAuthRejected = vi.fn();
- const onMessage = vi.fn();
- const client = makeClient({ onAuthRejected, onMessage });
- client.connect();
-
- const ws = (client as any).ws as MockWebSocket;
- ws.simulateOpen();
- // The error frame is NOT in DaemonPushMessageSchema — it must be handled
- // before safeParse or it'd be dropped as "invalid push message".
- ws.simulateMessage(JSON.stringify({ type: "error", code: "AUTH_REJECTED", reason: "revoked" }));
-
- expect(onAuthRejected).toHaveBeenCalledTimes(1);
- expect(onAuthRejected).toHaveBeenCalledWith("revoked");
- expect(onMessage).not.toHaveBeenCalled();
- });
-
- it("invalid message (bad schema) does not call onMessage", () => {
- const onMessage = vi.fn();
- const client = makeClient({ onMessage });
- client.connect();
-
- const ws = (client as any).ws as MockWebSocket;
- ws.simulateOpen();
- ws.simulateMessage(JSON.stringify({ type: "auth.ok" }));
- ws.simulateMessage(JSON.stringify({ type: "unknown.garbage", foo: "bar" }));
-
- expect(onMessage).not.toHaveBeenCalled();
- });
-
- it("schedules reconnect on close (verify reconnectTimer is set)", () => {
- const client = makeClient();
- client.connect();
-
- const ws = (client as any).ws as MockWebSocket;
- ws.simulateOpen();
- ws.simulateClose();
-
- expect((client as any).reconnectTimer).not.toBeNull();
- });
-
- it("does not reconnect after close() is called", () => {
- const client = makeClient();
- client.connect();
-
- const ws = (client as any).ws as MockWebSocket;
- ws.simulateOpen();
-
- client.close();
-
- expect((client as any).reconnectTimer).toBeNull();
- expect((client as any).closed).toBe(true);
- });
-
- it("liveness timeout triggers ws.close() if no messages received", () => {
- const client = makeClient();
- client.connect();
-
- const ws = (client as any).ws as MockWebSocket;
- ws.simulateOpen();
-
- const closeSpy = vi.spyOn(ws, "close");
- vi.advanceTimersByTime(55_000);
-
- expect(closeSpy).toHaveBeenCalled();
- });
-
- it("calls onDisconnected when connection drops after being authenticated", () => {
- const onDisconnected = vi.fn();
- const client = makeClient({ onDisconnected });
- client.connect();
-
- const ws = (client as any).ws as MockWebSocket;
- ws.simulateOpen();
- ws.simulateMessage(JSON.stringify({ type: "auth.ok" }));
-
- expect(client.isConnected()).toBe(true);
- ws.simulateClose();
-
- expect(onDisconnected).toHaveBeenCalledTimes(1);
- expect(client.isConnected()).toBe(false);
- });
-});
diff --git a/src/cli/daemon/ws-client.ts b/src/cli/daemon/ws-client.ts
deleted file mode 100644
index 15b8e3912..000000000
--- a/src/cli/daemon/ws-client.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-import { createLogger } from "../lib/logger.js";
-import { DaemonPushMessageSchema, devWsDoPort } from "@alook/shared";
-import type { DaemonPushMessage } from "@alook/shared";
-
-const log = createLogger({ module: "ws-client" });
-
-const WS_RECONNECT_INIT = 1000;
-const WS_RECONNECT_MAX = 30_000;
-const WS_PING_INTERVAL = 25_000;
-const WS_LIVENESS_TIMEOUT = 50_000;
-const WS_DO_DEV_PORT = Number(process.env.ALOOK_WS_DO_PORT) || devWsDoPort();
-
-export interface DaemonWsClientOptions {
- serverURL: string;
- daemonId: string;
- machineToken: string;
- onMessage: (msg: DaemonPushMessage) => void;
- onConnected: () => void;
- onDisconnected: () => void;
- /**
- * Fired when the server sends an `AUTH_REJECTED` frame — the definitive
- * "this machine token is dead" signal. The daemon marks the workspace
- * auth-failed and rebuilds the WS with a different token. `reason` is
- * whatever the server attached (may be undefined).
- */
- onAuthRejected?: (reason?: string) => void;
-}
-
-export class DaemonWsClient {
- private ws: WebSocket | null = null;
- private reconnectDelay = WS_RECONNECT_INIT;
- private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
- private pingInterval: ReturnType<typeof setInterval> | null = null;
- private livenessInterval: ReturnType<typeof setInterval> | null = null;
- private lastMessageAt = 0;
- private connected = false;
- private closed = false;
-
- constructor(private opts: DaemonWsClientOptions) {}
-
- getUrl(): string {
- const url = new URL(this.opts.serverURL);
- const isLocal = url.hostname === "localhost" || url.hostname === "127.0.0.1";
- if (isLocal) {
- return `ws://localhost:${WS_DO_DEV_PORT}/?daemonId=${this.opts.daemonId}`;
- }
- const protocol = url.protocol === "https:" ? "wss:" : "ws:";
- return `${protocol}//${url.host}/api/ws/daemon?daemonId=${this.opts.daemonId}`;
- }
-
- isConnected(): boolean {
- return this.connected;
- }
-
- connect(): void {
- if (this.closed) return;
- this.cleanup();
-
- const wsUrl = this.getUrl();
- log.info("connecting", { url: wsUrl });
-
- try {
- this.ws = new WebSocket(wsUrl);
- } catch (err) {
- log.warn("ws creation failed", { err: String(err) });
- this.scheduleReconnect();
- return;
- }
-
- this.ws.addEventListener("open", () => {
- this.reconnectDelay = WS_RECONNECT_INIT;
- this.ws!.send(JSON.stringify({
- type: "auth",
- machineToken: this.opts.machineToken,
- daemonId: this.opts.daemonId,
- }));
- this.lastMessageAt = Date.now();
- this.startHeartbeat();
- });
-
- this.ws.addEventListener("message", (event) => {
- this.lastMessageAt = Date.now();
- const str = typeof event.data === "string" ? event.data : "";
- if (str === "pong") return;
-
- try {
- const msg = JSON.parse(str);
- if (msg.type === "auth.ok") {
- log.info("authenticated");
- this.connected = true;
- this.opts.onConnected();
- return;
- }
- // Must be checked BEFORE DaemonPushMessageSchema.safeParse —
- // the schema is a discriminatedUnion with no "error" member, so an
- // AUTH_REJECTED frame would otherwise be dropped as "invalid push".
- if (msg.type === "error" && msg.code === "AUTH_REJECTED") {
- log.warn("machine token rejected by server (AUTH_REJECTED)", { reason: msg.reason });
- this.opts.onAuthRejected?.(msg.reason);
- return;
- }
- const parsed = DaemonPushMessageSchema.safeParse(msg);
- if (!parsed.success) {
- log.warn("invalid push message", { err: parsed.error.message });
- return;
- }
- this.opts.onMessage(parsed.data);
- } catch (err) {
- log.debug("message parse error", { err: String(err) });
- }
- });
-
- this.ws.addEventListener("error", (event) => {
- const err = (event as unknown as { message?: string; error?: unknown });
- log.warn("ws error", { err: String(err?.message ?? err?.error ?? "unknown") });
- });
-
- this.ws.addEventListener("close", (event) => {
- const { code, reason } = event as unknown as { code?: number; reason?: string };
- const wasConnected = this.connected;
- this.connected = false;
- this.stopHeartbeat();
- // Surface close code/reason so a daemon stuck reconnecting is
- // diagnosable (auth-close 1008 vs transient 1011 vs network).
- log.info("ws closed", { code, reason, wasConnected });
- if (wasConnected) {
- this.opts.onDisconnected();
- }
- if (!this.closed) {
- this.scheduleReconnect();
- }
- });
- }
-
- close(): void {
- this.closed = true;
- this.cleanup();
- if (this.reconnectTimer) {
- clearTimeout(this.reconnectTimer);
- this.reconnectTimer = null;
- }
- }
-
- private cleanup(): void {
- this.stopHeartbeat();
- if (this.ws) {
- try { this.ws.close(); } catch {}
- this.ws = null;
- }
- this.connected = false;
- }
-
- private scheduleReconnect(): void {
- if (this.closed) return;
- const delay = Math.min(this.reconnectDelay, WS_RECONNECT_MAX);
- this.reconnectDelay = Math.min(delay * 2, WS_RECONNECT_MAX);
- const jitter = Math.random() * 500;
- log.info("reconnecting", { delayMs: Math.round(delay + jitter) });
- this.reconnectTimer = setTimeout(() => {
- this.reconnectTimer = null;
- this.connect();
- }, delay + jitter);
- }
-
- private startHeartbeat(): void {
- this.pingInterval = setInterval(() => {
- if (this.ws?.readyState === WebSocket.OPEN) {
- this.ws.send("ping");
- }
- }, WS_PING_INTERVAL);
-
- this.livenessInterval = setInterval(() => {
- if (Date.now() - this.lastMessageAt > WS_LIVENESS_TIMEOUT) {
- log.warn("liveness timeout, closing");
- this.ws?.close();
- }
- }, 5_000);
- }
-
- private stopHeartbeat(): void {
- if (this.pingInterval) { clearInterval(this.pingInterval); this.pingInterval = null; }
- if (this.livenessInterval) { clearInterval(this.livenessInterval); this.livenessInterval = null; }
- }
-}
diff --git a/src/cli/eslint.config.mjs b/src/cli/eslint.config.mjs
deleted file mode 100644
index e1bad3c11..000000000
--- a/src/cli/eslint.config.mjs
+++ /dev/null
@@ -1,17 +0,0 @@
-import { defineConfig, globalIgnores } from "eslint/config";
-import tseslint from "typescript-eslint";
-
-const eslintConfig = defineConfig([
- ...tseslint.configs.recommended,
- globalIgnores(["dist/**", "coverage/**"]),
- {
- files: ["**/*.test.ts"],
- rules: {
- "@typescript-eslint/no-explicit-any": "off",
- "@typescript-eslint/no-unused-vars": "off",
- "@typescript-eslint/no-require-imports": "off",
- },
- },
-]);
-
-export default eslintConfig;
diff --git a/src/cli/knip.json b/src/cli/knip.json
deleted file mode 100644
index 848f85954..000000000
--- a/src/cli/knip.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "$schema": "https://unpkg.com/knip@6/schema.json",
- "entry": [
- "daemon/session-runner.ts",
- "daemon/meeting-runner.ts",
- "commands/**/*.ts",
- "scripts/**/*.mjs"
- ],
- "project": ["src/**/*.ts", "commands/**/*.ts", "daemon/**/*.ts", "lib/**/*.ts"],
- "ignoreDependencies": [
- "citty"
- ],
- "ignoreBinaries": [
- "taskkill"
- ],
- "vitest": {
- "entry": ["**/*.test.ts"]
- },
- "eslint": {
- "entry": ["eslint.config.mjs"]
- }
-}
diff --git a/src/cli/lib/activate.ts b/src/cli/lib/activate.ts
deleted file mode 100644
index ba7c71689..000000000
--- a/src/cli/lib/activate.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import { hostname } from "os";
-import { spawn } from "child_process";
-import { openSync, closeSync, mkdirSync } from "fs";
-import { dirname } from "path";
-import { APIClient } from "./client.js";
-import { loadCLIConfigForProfile, saveCLIConfigForProfile, markWorkspaceActive } from "./config.js";
-import { cmdPrefix, isDev } from "./env.js";
-import { readDaemonPid, isProcessAlive } from "../daemon/pidfile.js";
-import { daemonLogFilePath } from "../daemon/config.js";
-import { startDaemon } from "../daemon/daemon.js";
-import { resolveLoginShellEnv } from "./shell-env.js";
-import { detectRuntimes } from "./runtimes.js";
-
-interface ActivateResponse {
- daemon_id: string;
- workspace_id: string;
- runtimes: { id: string; provider: string }[];
-}
-
-interface Workspace {
- id: string;
- name: string;
-}
-
-interface AgentListItem {
- id: string;
-}
-
-export interface ActivateResult {
- workspaceId: string;
- workspaceName: string;
- runtimeProviders: string[];
-}
-
-export async function activateAndSave(opts: {
- token: string;
- serverUrl: string;
- profile?: string;
-}): Promise<ActivateResult> {
- const { token, serverUrl, profile } = opts;
-
- console.log("Scanning for AI runtimes...");
- const runtimes = detectRuntimes();
- if (runtimes.length === 0) {
- console.error(
- "Error: no runtimes found. Install claude, codex, or opencode first.",
- );
- process.exit(1);
- }
- console.log(`Found: ${runtimes.map((r) => r.type).join(", ")}`);
-
- const host = hostname();
- console.log("Registering machine...");
- let activateResp: ActivateResponse;
- try {
- const res = await fetch(`${serverUrl}/api/machine-tokens/activate`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ token, hostname: host, runtimes }),
- });
- if (!res.ok) {
- const text = await res.text();
- console.error(`Error: registration failed (${res.status}): ${text}`);
- process.exit(1);
- }
- activateResp = await res.json() as ActivateResponse;
- } catch (err) {
- console.error(
- `Error: failed to activate: ${err instanceof Error ? err.message : err}`,
- );
- process.exit(1);
- }
-
- const client = new APIClient(serverUrl, token);
-
- let workspaces: Workspace[];
- try {
- workspaces = await client.getJSON<Workspace[]>("/api/workspaces");
- } catch (err) {
- console.error(
- `Error: failed to fetch workspaces: ${err instanceof Error ? err.message : err}`,
- );
- process.exit(1);
- }
-
- if (!workspaces.length) {
- console.error("Error: no workspaces found for this user");
- process.exit(1);
- }
-
- const ws = workspaces.find((w) => w.id === activateResp.workspace_id) || workspaces[0];
-
- const wsClient = new APIClient(serverUrl, token, ws.id);
- let agentIds: string[] = [];
- try {
- const agents = await wsClient.getJSON<AgentListItem[]>(`/api/agents?workspace_id=${ws.id}`);
- agentIds = agents.map((a) => a.id);
- } catch {
- // Non-fatal
- }
-
- const existing = loadCLIConfigForProfile(profile);
- const watched = markWorkspaceActive(existing.watched_workspaces || [], {
- id: ws.id,
- name: ws.name,
- token,
- agent_ids: agentIds,
- });
-
- saveCLIConfigForProfile(profile, {
- server_url: serverUrl,
- watched_workspaces: watched,
- });
-
- const daemonPid = readDaemonPid(profile);
- if (daemonPid && isProcessAlive(daemonPid)) {
- try {
- process.kill(daemonPid, "SIGHUP");
- console.log(`\nDaemon (pid ${daemonPid}) notified — workspace will be active shortly.`);
- } catch {
- console.log(`\nDaemon is running but could not be notified. Restart it to pick up the new workspace.`);
- }
- } else if (isDev() && process.stdout.isTTY) {
- console.log("\nStarting daemon in foreground...");
- await startDaemon(profile, serverUrl);
- } else {
- console.log("\nStarting daemon...");
- try {
- const entry = process.argv[1];
- const args = [entry];
- if (profile) args.push("--profile", profile);
- args.push("daemon", "start", "--foreground");
-
- const logPath = daemonLogFilePath();
- mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 });
- const logFd = openSync(logPath, "a", 0o600);
-
- const child = spawn(process.execPath, args, {
- detached: true,
- stdio: ["ignore", logFd, logFd],
- env: resolveLoginShellEnv(),
- });
- child.unref();
- closeSync(logFd);
- console.log("Daemon started in background.");
- console.log(`Logs: ${logPath}`);
- } catch {
- console.log(`Failed to auto-start daemon. Run '${cmdPrefix()} daemon start' manually.`);
- }
- }
-
- return {
- workspaceId: ws.id,
- workspaceName: ws.name,
- runtimeProviders: activateResp.runtimes.map((r) => r.provider),
- };
-}
diff --git a/src/cli/lib/client.ts b/src/cli/lib/client.ts
deleted file mode 100644
index efa9e1684..000000000
--- a/src/cli/lib/client.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-export class APIClient {
- constructor(
- private baseURL: string,
- private token: string,
- private workspaceId?: string,
- ) {}
-
- private async request<T>(
- method: string,
- path: string,
- body?: unknown,
- ): Promise<T> {
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- Authorization: `Bearer ${this.token}`,
- };
- if (this.workspaceId) headers["X-Workspace-ID"] = this.workspaceId;
-
- const res = await fetch(this.baseURL + path, {
- method,
- headers,
- body: body ? JSON.stringify(body) : undefined,
- });
- if (!res.ok) {
- const text = await res.text();
- throw new Error(`HTTP ${res.status}: ${text}`);
- }
- if (res.status === 204) return undefined as T;
- return res.json();
- }
-
- getJSON<T>(path: string): Promise<T> {
- return this.request("GET", path);
- }
-
- postJSON<T>(path: string, body?: unknown): Promise<T> {
- return this.request("POST", path, body);
- }
-
- deleteJSON<T>(path: string): Promise<T> {
- return this.request("DELETE", path);
- }
-
- patchJSON<T>(path: string, body?: unknown): Promise<T> {
- return this.request("PATCH", path, body);
- }
-
- putJSON<T>(path: string, body?: unknown): Promise<T> {
- return this.request("PUT", path, body);
- }
-
- async postMultipart<T>(path: string, form: FormData): Promise<T> {
- const headers: Record<string, string> = {
- Authorization: `Bearer ${this.token}`,
- };
- if (this.workspaceId) headers["X-Workspace-ID"] = this.workspaceId;
-
- const res = await fetch(this.baseURL + path, {
- method: "POST",
- headers,
- body: form,
- });
- if (!res.ok) {
- const text = await res.text();
- throw new Error(`HTTP ${res.status}: ${text}`);
- }
- if (res.status === 204) return undefined as T;
- return res.json();
- }
-
- async getText(path: string): Promise<string> {
- const headers: Record<string, string> = {
- Authorization: `Bearer ${this.token}`,
- };
- if (this.workspaceId) headers["X-Workspace-ID"] = this.workspaceId;
-
- const res = await fetch(this.baseURL + path, { method: "GET", headers });
- if (!res.ok) {
- const text = await res.text();
- throw new Error(`HTTP ${res.status}: ${text}`);
- }
- return res.text();
- }
-
- async healthCheck(): Promise<boolean> {
- try {
- await this.getJSON("/health");
- return true;
- } catch {
- return false;
- }
- }
-}
diff --git a/src/cli/lib/command-utils.test.ts b/src/cli/lib/command-utils.test.ts
deleted file mode 100644
index 4cb56cbf2..000000000
--- a/src/cli/lib/command-utils.test.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { getRootOpts } from "./command-utils.js";
-
-describe("getRootOpts", () => {
- it("returns opts from root command (no parent)", () => {
- const cmd = { parent: null, opts: () => ({ server: "https://x.com", profile: "dev" }) } as any;
- expect(getRootOpts(cmd)).toEqual({ server: "https://x.com", profile: "dev" });
- });
-
- it("traverses up to root from deeply nested command", () => {
- const root = { parent: null, opts: () => ({ server: "https://root.com" }) } as any;
- const mid = { parent: root, opts: () => ({ mid: true }) } as any;
- const leaf = { parent: mid, opts: () => ({ leaf: true }) } as any;
-
- expect(getRootOpts(leaf)).toEqual({ server: "https://root.com" });
- });
-
- it("returns empty object if root has no opts", () => {
- const root = { parent: null, opts: () => ({}) } as any;
- const child = { parent: root, opts: () => ({ something: true }) } as any;
-
- expect(getRootOpts(child)).toEqual({});
- });
-});
diff --git a/src/cli/lib/command-utils.ts b/src/cli/lib/command-utils.ts
deleted file mode 100644
index 689032bcc..000000000
--- a/src/cli/lib/command-utils.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { Command } from "commander";
-
-export function getRootOpts(command: Command): Record<string, unknown> {
- let root = command;
- while (root.parent) root = root.parent;
- return root.opts() || {};
-}
diff --git a/src/cli/lib/config.test.ts b/src/cli/lib/config.test.ts
deleted file mode 100644
index 6bf0c4a3a..000000000
--- a/src/cli/lib/config.test.ts
+++ /dev/null
@@ -1,299 +0,0 @@
-import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
-import { join } from "path";
-import { homedir } from "os";
-
-vi.mock("fs", () => ({
- readFileSync: vi.fn(),
- writeFileSync: vi.fn(),
- mkdirSync: vi.fn(),
-}));
-
-import { readFileSync, writeFileSync, mkdirSync } from "fs";
-import {
- configDir,
- configPath,
- loadCLIConfig,
- loadCLIConfigForProfile,
- saveCLIConfig,
- saveCLIConfigForProfile,
-} from "./config.js";
-
-const mockedReadFileSync = vi.mocked(readFileSync);
-const mockedWriteFileSync = vi.mocked(writeFileSync);
-const mockedMkdirSync = vi.mocked(mkdirSync);
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-afterEach(() => {
- delete process.env.ALOOK_SERVER_URL;
- delete process.env.ALOOK_PROJECT_ROOT;
-});
-
-describe("configDir — three ALOOK_PROJECT_ROOT scenarios", () => {
- it("production: returns ~/.alook (ALOOK_PROJECT_ROOT unset)", () => {
- delete process.env.ALOOK_PROJECT_ROOT;
- expect(configDir()).toBe(join(homedir(), ".alook"));
- });
-
- it("dev mode: returns ALOOK_PROJECT_ROOT directly", () => {
- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";
- expect(configDir()).toBe("/tmp/my-project/.alook");
- });
-
- it("app mode: returns ALOOK_PROJECT_ROOT when set to self-hosted dir", () => {
- process.env.ALOOK_PROJECT_ROOT = join(homedir(), ".alook", "self-hosted");
- expect(configDir()).toBe(join(homedir(), ".alook", "self-hosted"));
- });
-});
-
-describe("configPath", () => {
- it("returns ~/.alook/config.json by default", () => {
- expect(configPath()).toBe(join(homedir(), ".alook", "config.json"));
- });
-
- it("returns <ALOOK_PROJECT_ROOT>/config.json when set", () => {
- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";
- expect(configPath()).toBe(join("/tmp/my-project/.alook", "config.json"));
- });
-});
-
-describe("loadCLIConfig", () => {
- it("returns empty object when file doesn't exist", () => {
- mockedReadFileSync.mockImplementation(() => {
- throw new Error("ENOENT");
- });
- expect(loadCLIConfig()).toEqual({});
- });
-
- it("returns parsed JSON when file exists", () => {
- const cfg = { server_url: "http://example.com", watched_workspaces: [] };
- mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
- expect(loadCLIConfig()).toEqual(cfg);
- });
-});
-
-describe("loadCLIConfigForProfile", () => {
- it("returns profile config when profile specified", () => {
- const profileCfg = {
- server_url: "http://profile.example.com",
- watched_workspaces: [{ id: "w1", name: "Workspace 1", token: "ws-token" }],
- };
- const cfg = { profiles: { staging: profileCfg } };
- mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
-
- expect(loadCLIConfigForProfile("staging")).toEqual(profileCfg);
- });
-
- it("uses default_profile when no profile specified", () => {
- const profileCfg = {
- server_url: "http://default.example.com",
- watched_workspaces: [],
- };
- const cfg = { default_profile: "prod", profiles: { prod: profileCfg } };
- mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
-
- expect(loadCLIConfigForProfile()).toEqual(profileCfg);
- });
-
- it("falls back to root-level fields when profile not found", () => {
- const cfg = {
- server_url: "http://root.example.com",
- watched_workspaces: [{ id: "w2", name: "Root WS", token: "ws-token" }],
- };
- mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
-
- expect(loadCLIConfigForProfile()).toEqual({
- server_url: "http://root.example.com",
- watched_workspaces: [{ id: "w2", name: "Root WS", token: "ws-token", status: "active" }],
- });
- });
-
- it("returns empty defaults when no config exists", () => {
- mockedReadFileSync.mockImplementation(() => {
- throw new Error("ENOENT");
- });
-
- expect(loadCLIConfigForProfile()).toEqual({
- server_url: "",
- watched_workspaces: [],
- });
- });
-
- it("assigns deleted status to entries without id and no status", () => {
- const cfg = {
- server_url: "http://example.com",
- watched_workspaces: [{ id: null, name: null, token: "t1" }],
- };
- mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
-
- const result = loadCLIConfigForProfile();
- expect(result.watched_workspaces[0]).toMatchObject({ status: "deleted" });
- });
-
- it("does not duplicate if machine_token already in watched_workspaces", () => {
- const cfg = {
- server_url: "http://example.com",
- watched_workspaces: [{ id: null, name: null, token: "al_same", status: "registered" }],
- machine_token: "al_same",
- };
- mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
-
- const result = loadCLIConfigForProfile();
- expect(result.watched_workspaces).toHaveLength(1);
- expect(result.watched_workspaces[0].token).toBe("al_same");
- });
-
- it("defaults status to active for old entries with an id", () => {
- const cfg = {
- server_url: "http://example.com",
- watched_workspaces: [{ id: "w1", name: "WS1", token: "t1" }],
- };
- mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
-
- const result = loadCLIConfigForProfile();
- expect(result.watched_workspaces[0].status).toBe("active");
- });
-});
-
-describe("saveCLIConfig", () => {
- it("writes valid JSON with mode 0600 to ~/.alook in production", () => {
- const cfg = { server_url: "http://example.com", watched_workspaces: [] };
- saveCLIConfig(cfg);
-
- expect(mockedMkdirSync).toHaveBeenCalledWith(
- join(homedir(), ".alook"),
- { recursive: true, mode: 0o700 },
- );
- expect(mockedWriteFileSync).toHaveBeenCalledWith(
- join(homedir(), ".alook", "config.json"),
- JSON.stringify(cfg, null, 2),
- { mode: 0o600 },
- );
- });
-
- it("writes to ALOOK_PROJECT_ROOT when set", () => {
- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";
-
- const cfg = { server_url: "http://localhost:3000", watched_workspaces: [] };
- saveCLIConfig(cfg);
-
- expect(mockedMkdirSync).toHaveBeenCalledWith(
- "/tmp/my-project/.alook",
- { recursive: true, mode: 0o700 },
- );
- expect(mockedWriteFileSync).toHaveBeenCalledWith(
- join("/tmp/my-project/.alook", "config.json"),
- JSON.stringify(cfg, null, 2),
- { mode: 0o600 },
- );
- });
-});
-
-describe("saveCLIConfigForProfile", () => {
- it("updates specific profile", () => {
- const existing = { profiles: {} };
- mockedReadFileSync.mockReturnValue(JSON.stringify(existing));
-
- const profileCfg = {
- server_url: "http://new.example.com",
- watched_workspaces: [],
- };
- saveCLIConfigForProfile("staging", profileCfg);
-
- const written = JSON.parse(
- mockedWriteFileSync.mock.calls[0][1] as string,
- );
- expect(written.profiles.staging).toEqual(profileCfg);
- });
-
- it("updates root-level fields when no profile specified", () => {
- mockedReadFileSync.mockReturnValue(JSON.stringify({}));
-
- const profileCfg = {
- server_url: "http://root.example.com",
- watched_workspaces: [{ id: "w1", name: "WS", token: "ws-token" }],
- };
- saveCLIConfigForProfile(undefined, profileCfg);
-
- const written = JSON.parse(
- mockedWriteFileSync.mock.calls[0][1] as string,
- );
- expect(written.server_url).toBe("http://root.example.com");
- expect(written.watched_workspaces).toEqual([{ id: "w1", name: "WS", token: "ws-token" }]);
- });
-
- it("preserves multiple watched_workspaces when saving", () => {
- mockedReadFileSync.mockReturnValue(JSON.stringify({}));
-
- const profileCfg = {
- server_url: "http://example.com",
- watched_workspaces: [
- { id: "w1", name: "First", token: "t1", status: "active" as const },
- { id: "w2", name: "Second", token: "t2", status: "active" as const },
- { id: null, name: null, token: "t3", status: "registered" as const },
- ],
- };
- saveCLIConfigForProfile(undefined, profileCfg);
-
- const written = JSON.parse(
- mockedWriteFileSync.mock.calls[0][1] as string,
- );
- expect(written.watched_workspaces).toHaveLength(3);
- expect(written.watched_workspaces[0].id).toBe("w1");
- expect(written.watched_workspaces[2].status).toBe("registered");
- });
-
- it("removes legacy machine_token from config on save", () => {
- mockedReadFileSync.mockReturnValue(JSON.stringify({ machine_token: "al_old", server_url: "" }));
-
- saveCLIConfigForProfile(undefined, {
- server_url: "http://example.com",
- watched_workspaces: [{ id: null, name: null, token: "al_old", status: "registered" }],
- });
-
- const written = JSON.parse(
- mockedWriteFileSync.mock.calls[0][1] as string,
- );
- expect(written.machine_token).toBeUndefined();
- });
-});
-
-describe("loadCLIConfigForProfile — multiple workspaces", () => {
- it("returns all watched_workspaces from root config", () => {
- const cfg = {
- server_url: "http://example.com",
- watched_workspaces: [
- { id: "w1", name: "WS1", token: "t1" },
- { id: "w2", name: "WS2", token: "t2" },
- ],
- };
- mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
-
- const result = loadCLIConfigForProfile();
- expect(result.watched_workspaces).toHaveLength(2);
- expect(result.watched_workspaces[0].id).toBe("w1");
- expect(result.watched_workspaces[1].id).toBe("w2");
- });
-
- it("returns all watched_workspaces from profile config", () => {
- const cfg = {
- profiles: {
- prod: {
- server_url: "https://prod.example.com",
- watched_workspaces: [
- { id: "wp1", name: "Prod WS 1", token: "tp1" },
- { id: "wp2", name: "Prod WS 2", token: "tp2" },
- { id: "wp3", name: "Prod WS 3", token: "tp3" },
- ],
- },
- },
- };
- mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
-
- const result = loadCLIConfigForProfile("prod");
- expect(result.watched_workspaces).toHaveLength(3);
- expect(result.watched_workspaces.map((w: any) => w.id)).toEqual(["wp1", "wp2", "wp3"]);
- });
-});
diff --git a/src/cli/lib/config.ts b/src/cli/lib/config.ts
deleted file mode 100644
index 22d02d832..000000000
--- a/src/cli/lib/config.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { readFileSync, writeFileSync, mkdirSync } from "fs";
-import { join } from "path";
-import { homedir } from "os";
-
-interface WatchedWorkspace {
- id: string | null;
- name: string | null;
- token: string;
- status?: "active" | "deleted";
- agent_ids?: string[];
-}
-
-type ActiveWorkspace = WatchedWorkspace & { id: string };
-
-interface ProfileConfig {
- server_url: string;
- session_token?: string;
- watched_workspaces: WatchedWorkspace[];
-}
-
-interface CLIConfig {
- server_url?: string;
- session_token?: string;
- watched_workspaces?: WatchedWorkspace[];
- default_profile?: string;
- profiles?: Record<string, ProfileConfig>;
-}
-
-export type { CLIConfig, ProfileConfig, WatchedWorkspace, ActiveWorkspace };
-
-/**
- * Effective status of a workspace entry. Soft-deleted entries linger in config
- * but are dead; legacy entries without an explicit status inherit the same rule
- * `loadCLIConfigForProfile` normalizes with (id ⇒ active, no id ⇒ deleted).
- */
-function workspaceStatus(ws: WatchedWorkspace): "active" | "deleted" {
- return ws.status ?? (ws.id ? "active" : "deleted");
-}
-
-/**
- * The active workspaces are the only ones the daemon and CLI should ever act
- * on. All readers go through this so the "is this workspace live?" rule lives
- * in exactly one place — select the active entries, never scatter a
- * `status !== "deleted"` filter at each call site.
- */
-export function activeWorkspaces(
- workspaces: WatchedWorkspace[] | undefined,
-): ActiveWorkspace[] {
- return (workspaces || []).filter(
- (ws): ws is ActiveWorkspace => workspaceStatus(ws) === "active" && !!ws.id,
- );
-}
-
-/**
- * Mark a workspace live: upsert the entry, set `status="active"`, and refresh
- * name/token/agent_ids. Sole writer of the active transition — pairing,
- * re-login sync, and studio creation all funnel through here. Mutates `watched`
- * in place and returns it so the caller keeps ownership of load/save.
- */
-export function markWorkspaceActive(
- watched: WatchedWorkspace[],
- fields: { id: string; name: string | null; token?: string; agent_ids?: string[] },
-): WatchedWorkspace[] {
- const existing = watched.find((w) => w.id === fields.id);
- if (existing) {
- existing.status = "active";
- existing.name = fields.name;
- if (fields.token !== undefined) existing.token = fields.token;
- if (fields.agent_ids !== undefined) existing.agent_ids = fields.agent_ids;
- } else {
- watched.push({
- id: fields.id,
- name: fields.name,
- token: fields.token ?? "",
- status: "active",
- agent_ids: fields.agent_ids ?? [],
- });
- }
- return watched;
-}
-
-/**
- * Soft-delete a workspace by id: flip `status="deleted"` in place, leaving the
- * entry so the cause stays inspectable and re-pairing can revive it. Sole
- * writer of the deleted transition. No-op if the id is absent. Returns whether
- * an entry was found so the caller can decide to persist.
- */
-export function markWorkspaceDeletedInList(
- watched: WatchedWorkspace[],
- workspaceId: string,
-): boolean {
- const entry = watched.find((w) => w.id === workspaceId);
- if (!entry) return false;
- entry.status = "deleted";
- return true;
-}
-
-export function configDir(): string {
- return process.env.ALOOK_PROJECT_ROOT || join(homedir(), ".alook");
-}
-
-export function configPath(): string {
- return join(configDir(), "config.json");
-}
-
-export function loadCLIConfig(): CLIConfig {
- try {
- return JSON.parse(readFileSync(configPath(), "utf-8"));
- } catch {
- return {};
- }
-}
-
-export function loadCLIConfigForProfile(profile?: string): ProfileConfig {
- const cfg = loadCLIConfig();
- const profileName = profile || cfg.default_profile;
- if (profileName && cfg.profiles?.[profileName]) {
- return cfg.profiles[profileName];
- }
- const result: ProfileConfig = {
- server_url: cfg.server_url || "",
- session_token: cfg.session_token,
- watched_workspaces: cfg.watched_workspaces || [],
- };
-
- // Default status for old entries without it
- for (const ws of result.watched_workspaces) {
- if (!ws.status) ws.status = workspaceStatus(ws);
- }
-
- return result;
-}
-
-export function saveCLIConfig(cfg: CLIConfig): void {
- mkdirSync(configDir(), { recursive: true, mode: 0o700 });
- writeFileSync(configPath(), JSON.stringify(cfg, null, 2), { mode: 0o600 });
-}
-
-export function saveCLIConfigForProfile(
- profile: string | undefined,
- profileConfig: ProfileConfig,
-): void {
- const cfg = loadCLIConfig();
- if (profile) {
- if (!cfg.profiles) cfg.profiles = {};
- cfg.profiles[profile] = profileConfig;
- } else {
- cfg.server_url = profileConfig.server_url;
- cfg.session_token = profileConfig.session_token;
- cfg.watched_workspaces = profileConfig.watched_workspaces;
- // Remove legacy machine_token if present
- delete (cfg as Record<string, unknown>).machine_token;
- }
- saveCLIConfig(cfg);
-}
diff --git a/src/cli/lib/context-env.test.ts b/src/cli/lib/context-env.test.ts
deleted file mode 100644
index 53fe9622f..000000000
--- a/src/cli/lib/context-env.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach } from "vitest";
-import { gatherContextEnvVars } from "./context-env.js";
-
-describe("gatherContextEnvVars", () => {
- const envKeys = ["ALOOK_CONVERSATION_ID", "ALOOK_TRACE_ID", "ALOOK_TASK_ID"];
- const saved: Record<string, string | undefined> = {};
-
- beforeEach(() => {
- for (const k of envKeys) {
- saved[k] = process.env[k];
- delete process.env[k];
- }
- });
-
- afterEach(() => {
- for (const k of envKeys) {
- if (saved[k] !== undefined) process.env[k] = saved[k];
- else delete process.env[k];
- }
- });
-
- it("returns all env vars when set", () => {
- process.env.ALOOK_CONVERSATION_ID = "conv_123";
- process.env.ALOOK_TRACE_ID = "trace_456";
- process.env.ALOOK_TASK_ID = "task_789";
-
- const result = gatherContextEnvVars();
- expect(result).toEqual({
- conversationId: "conv_123",
- traceId: "trace_456",
- sourceTaskId: "task_789",
- });
- });
-
- it("returns undefined for unset vars", () => {
- const result = gatherContextEnvVars();
- expect(result.conversationId).toBeUndefined();
- expect(result.traceId).toBeUndefined();
- expect(result.sourceTaskId).toBeUndefined();
- });
-
- it("handles partial env vars", () => {
- process.env.ALOOK_CONVERSATION_ID = "conv_123";
-
- const result = gatherContextEnvVars();
- expect(result.conversationId).toBe("conv_123");
- expect(result.traceId).toBeUndefined();
- expect(result.sourceTaskId).toBeUndefined();
- });
-});
diff --git a/src/cli/lib/context-env.ts b/src/cli/lib/context-env.ts
deleted file mode 100644
index 2e93ad330..000000000
--- a/src/cli/lib/context-env.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-export interface ContextEnvVars {
- conversationId?: string;
- traceId?: string;
- sourceTaskId?: string;
-}
-
-export function gatherContextEnvVars(): ContextEnvVars {
- const conversationId = process.env.ALOOK_CONVERSATION_ID || undefined;
- const traceId = process.env.ALOOK_TRACE_ID || undefined;
- const sourceTaskId = process.env.ALOOK_TASK_ID || undefined;
- return { conversationId, traceId, sourceTaskId };
-}
diff --git a/src/cli/lib/env.test.ts b/src/cli/lib/env.test.ts
deleted file mode 100644
index 14df7747d..000000000
--- a/src/cli/lib/env.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { describe, it, expect, afterEach } from "vitest";
-import { isDev, cmdPrefix } from "./env.js";
-
-afterEach(() => {
- delete process.env.ALOOK_SERVER_URL;
- delete process.env.ALOOK_CMD_PREFIX;
-});
-
-describe("isDev", () => {
- it("returns false when ALOOK_SERVER_URL is not set", () => {
- expect(isDev()).toBe(false);
- });
-
- it("returns true when ALOOK_SERVER_URL is set", () => {
- process.env.ALOOK_SERVER_URL = "http://localhost:3000";
- expect(isDev()).toBe(true);
- });
-
- it("returns false when ALOOK_CMD_PREFIX is set (app mode)", () => {
- process.env.ALOOK_SERVER_URL = "http://localhost:3000";
- process.env.ALOOK_CMD_PREFIX = "npx @alook/app cli";
- expect(isDev()).toBe(false);
- });
-});
-
-describe("cmdPrefix", () => {
- it("returns 'npx @alook/cli' in production", () => {
- expect(cmdPrefix()).toBe("npx @alook/cli");
- });
-
- it("returns 'pnpm dev:cli' in dev", () => {
- process.env.ALOOK_SERVER_URL = "http://localhost:3000";
- expect(cmdPrefix()).toBe("pnpm dev:cli");
- });
-
- it("returns ALOOK_CMD_PREFIX when set", () => {
- process.env.ALOOK_SERVER_URL = "http://localhost:3000";
- process.env.ALOOK_CMD_PREFIX = "npx @alook/app cli";
- expect(cmdPrefix()).toBe("npx @alook/app cli");
- });
-});
diff --git a/src/cli/lib/env.ts b/src/cli/lib/env.ts
deleted file mode 100644
index 4e1652094..000000000
--- a/src/cli/lib/env.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { resolveMode, cliCommand, getBaseUrl } from "@alook/shared";
-
-export function getServerUrl(): string {
- return getBaseUrl({ serverUrl: process.env.ALOOK_SERVER_URL });
-}
-
-export function isDev(): boolean {
- return resolveMode({
- serverUrl: process.env.ALOOK_SERVER_URL,
- cmdPrefix: process.env.ALOOK_CMD_PREFIX,
- }) === "dev";
-}
-
-export function cmdPrefix(): string {
- return process.env.ALOOK_CMD_PREFIX || cliCommand(resolveMode({
- serverUrl: process.env.ALOOK_SERVER_URL,
- cmdPrefix: process.env.ALOOK_CMD_PREFIX,
- }));
-}
diff --git a/src/cli/lib/file-utils.test.ts b/src/cli/lib/file-utils.test.ts
deleted file mode 100644
index 5759e99f3..000000000
--- a/src/cli/lib/file-utils.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { guessContentType, contentToBuffer } from "./file-utils.js";
-
-describe("guessContentType", () => {
- it("returns correct MIME for known extensions", () => {
- expect(guessContentType("report.pdf")).toBe("application/pdf");
- expect(guessContentType("image.png")).toBe("image/png");
- expect(guessContentType("photo.jpg")).toBe("image/jpeg");
- expect(guessContentType("photo.jpeg")).toBe("image/jpeg");
- expect(guessContentType("anim.gif")).toBe("image/gif");
- expect(guessContentType("hero.webp")).toBe("image/webp");
- expect(guessContentType("icon.svg")).toBe("image/svg+xml");
- expect(guessContentType("readme.md")).toBe("text/markdown");
- expect(guessContentType("data.json")).toBe("application/json");
- expect(guessContentType("styles.css")).toBe("application/octet-stream");
- expect(guessContentType("index.html")).toBe("text/html");
- expect(guessContentType("page.htm")).toBe("text/html");
- expect(guessContentType("app.ts")).toBe("text/typescript");
- expect(guessContentType("app.js")).toBe("text/javascript");
- expect(guessContentType("config.yaml")).toBe("text/yaml");
- expect(guessContentType("config.yml")).toBe("text/yaml");
- expect(guessContentType("data.xml")).toBe("application/xml");
- expect(guessContentType("archive.zip")).toBe("application/zip");
- expect(guessContentType("data.csv")).toBe("text/csv");
- expect(guessContentType("notes.txt")).toBe("text/plain");
- });
-
- it("is case-insensitive for extensions", () => {
- expect(guessContentType("image.PNG")).toBe("image/png");
- expect(guessContentType("file.PDF")).toBe("application/pdf");
- });
-
- it("returns octet-stream for unknown extensions", () => {
- expect(guessContentType("file.xyz")).toBe("application/octet-stream");
- expect(guessContentType("file.wasm")).toBe("application/octet-stream");
- });
-
- it("returns octet-stream for files without extension", () => {
- expect(guessContentType("Makefile")).toBe("application/octet-stream");
- expect(guessContentType("noext")).toBe("application/octet-stream");
- });
-});
-
-describe("contentToBuffer", () => {
- it("handles base64 string input", () => {
- const base64 = Buffer.from("hello world").toString("base64");
- const result = contentToBuffer(base64);
- expect(result.toString()).toBe("hello world");
- });
-
- it("handles ArrayBuffer input", () => {
- const data = new TextEncoder().encode("test data");
- const arrayBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
- const result = contentToBuffer(arrayBuffer);
- expect(result.toString()).toBe("test data");
- });
-
- it("handles Uint8Array input", () => {
- const data = new Uint8Array([72, 101, 108, 108, 111]);
- const result = contentToBuffer(data);
- expect(result.toString()).toBe("Hello");
- });
-});
diff --git a/src/cli/lib/file-utils.ts b/src/cli/lib/file-utils.ts
deleted file mode 100644
index 56f32d138..000000000
--- a/src/cli/lib/file-utils.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { readFileSync, statSync } from "fs";
-import { basename } from "path";
-import { APIClient } from "./client.js";
-
-const MIME_BY_EXT: Record<string, string> = {
- ".pdf": "application/pdf",
- ".png": "image/png",
- ".jpg": "image/jpeg",
- ".jpeg": "image/jpeg",
- ".gif": "image/gif",
- ".webp": "image/webp",
- ".svg": "image/svg+xml",
- ".txt": "text/plain",
- ".html": "text/html",
- ".htm": "text/html",
- ".json": "application/json",
- ".csv": "text/csv",
- ".md": "text/markdown",
- ".ts": "text/typescript",
- ".js": "text/javascript",
- ".yaml": "text/yaml",
- ".yml": "text/yaml",
- ".xml": "application/xml",
- ".zip": "application/zip",
-};
-
-export function guessContentType(filename: string): string {
- const idx = filename.lastIndexOf(".");
- if (idx < 0) return "application/octet-stream";
- const ext = filename.slice(idx).toLowerCase();
- return MIME_BY_EXT[ext] ?? "application/octet-stream";
-}
-
-export function contentToBuffer(content: string | ArrayBuffer | Uint8Array): Buffer {
- if (typeof content === "string") {
- return Buffer.from(content, "base64");
- } else if (content instanceof ArrayBuffer) {
- return Buffer.from(new Uint8Array(content));
- }
- return Buffer.from(content as Uint8Array);
-}
-
-export interface UploadedFile {
- key: string;
- filename: string;
- size: number;
- contentType: string;
-}
-
-export async function uploadFile(
- client: APIClient,
- filePath: string,
- endpoint: string,
-): Promise<UploadedFile> {
- let bytes: Buffer;
- let size: number;
- try {
- bytes = readFileSync(filePath);
- size = statSync(filePath).size;
- } catch (err) {
- throw new Error(`cannot read file "${filePath}": ${err instanceof Error ? err.message : err}`);
- }
- const filename = basename(filePath);
- const contentType = guessContentType(filename);
- const form = new FormData();
- form.append(
- "file",
- new Blob([new Uint8Array(bytes)], { type: contentType }),
- filename,
- );
- const uploaded = await client.postMultipart<UploadedFile>(endpoint, form);
- return {
- key: uploaded.key,
- filename: uploaded.filename,
- size: uploaded.size ?? size,
- contentType: uploaded.contentType ?? contentType,
- };
-}
diff --git a/src/cli/lib/flags.test.ts b/src/cli/lib/flags.test.ts
deleted file mode 100644
index 534a6d275..000000000
--- a/src/cli/lib/flags.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { vi, describe, it, expect, afterEach, beforeEach } from "vitest";
-import { flagOrEnv, resolveAgentId } from "./flags.js";
-
-function makeCmd(opts: Record<string, string>) {
- return { opts: () => opts } as any;
-}
-
-afterEach(() => {
- delete process.env.TEST_FLAG_ENV;
-});
-
-describe("flagOrEnv", () => {
- it("returns flag value when set", () => {
- const cmd = makeCmd({ myFlag: "from-flag" });
- expect(flagOrEnv(cmd, "myFlag", "TEST_FLAG_ENV", "default")).toBe(
- "from-flag",
- );
- });
-
- it("returns env var when flag not set", () => {
- process.env.TEST_FLAG_ENV = "from-env";
- const cmd = makeCmd({});
- expect(flagOrEnv(cmd, "myFlag", "TEST_FLAG_ENV", "default")).toBe(
- "from-env",
- );
- });
-
- it("returns fallback when neither set", () => {
- const cmd = makeCmd({});
- expect(flagOrEnv(cmd, "myFlag", "TEST_FLAG_ENV", "default")).toBe(
- "default",
- );
- });
-
- it("flag takes priority over env var", () => {
- process.env.TEST_FLAG_ENV = "from-env";
- const cmd = makeCmd({ myFlag: "from-flag" });
- expect(flagOrEnv(cmd, "myFlag", "TEST_FLAG_ENV", "default")).toBe(
- "from-flag",
- );
- });
-});
-
-describe("resolveAgentId", () => {
- const originalEnv = process.env.ALOOK_AGENT_ID;
-
- beforeEach(() => {
- delete process.env.ALOOK_AGENT_ID;
- });
-
- afterEach(() => {
- if (originalEnv !== undefined) {
- process.env.ALOOK_AGENT_ID = originalEnv;
- } else {
- delete process.env.ALOOK_AGENT_ID;
- }
- });
-
- it("returns flag value when both flag and env are set (flag wins)", () => {
- process.env.ALOOK_AGENT_ID = "env_agent";
- expect(resolveAgentId({ agent_id: "flag_agent" })).toBe("flag_agent");
- });
-
- it("returns env value when only env is set", () => {
- process.env.ALOOK_AGENT_ID = "env_agent";
- expect(resolveAgentId({})).toBe("env_agent");
- });
-
- it("calls process.exit(1) when neither is provided", () => {
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
- throw new Error("__exit__");
- }) as never);
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
-
- expect(() => resolveAgentId({})).toThrow("__exit__");
- expect(exitSpy).toHaveBeenCalledWith(1);
- expect(errSpy).toHaveBeenCalledWith(
- "Error: --agent_id is required (or set ALOOK_AGENT_ID env var)",
- );
-
- exitSpy.mockRestore();
- errSpy.mockRestore();
- });
-});
diff --git a/src/cli/lib/flags.ts b/src/cli/lib/flags.ts
deleted file mode 100644
index bcb2a2ad2..000000000
--- a/src/cli/lib/flags.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { Command } from "commander";
-import { readFileSync } from "fs";
-
-export function flagOrEnv(
- cmd: Command,
- flagName: string,
- envKey: string,
- fallback: string,
-): string {
- const opts = cmd.opts();
- if (opts[flagName]) return opts[flagName];
- if (process.env[envKey]) return process.env[envKey]!;
- return fallback;
-}
-
-export function resolveAgentId(opts: { agent_id?: string }): string {
- const id = opts.agent_id || process.env.ALOOK_AGENT_ID;
- if (!id) {
- console.error("Error: --agent_id is required (or set ALOOK_AGENT_ID env var)");
- process.exit(1);
- }
- return id;
-}
-
-export function collectRepeated(value: string, previous: string[]): string[] {
- return previous.concat([value]);
-}
-
-export function readBody(opts: { body?: string; bodyFile?: string }): string {
- if (opts.body && opts.bodyFile) {
- console.error("Error: --body and --body-file are mutually exclusive");
- process.exit(1);
- }
- if (opts.bodyFile) return readFileSync(opts.bodyFile, "utf-8");
- return opts.body ?? "";
-}
diff --git a/src/cli/lib/logger.test.ts b/src/cli/lib/logger.test.ts
deleted file mode 100644
index 9c703b0ea..000000000
--- a/src/cli/lib/logger.test.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { Logger } from "./logger.js";
-
-let stdoutSpy: any;
-let stderrSpy: any;
-
-beforeEach(() => {
- stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
- stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
- process.env.NO_COLOR = "1";
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
- delete process.env.NO_COLOR;
-});
-
-describe("Logger", () => {
- it("filters messages below configured level", () => {
- const logger = new Logger({ level: "warn" });
- logger.debug("hidden");
- logger.info("hidden");
- logger.warn("visible");
- logger.error("visible");
-
- expect(stdoutSpy).toHaveBeenCalledTimes(1);
- expect(stderrSpy).toHaveBeenCalledTimes(1);
- });
-
- it("formats output with timestamp and level prefix", () => {
- const logger = new Logger({ level: "debug" });
- logger.info("hello world");
-
- const output = stdoutSpy.mock.calls[0][0] as string;
- expect(output).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} INFO hello world\n$/);
- });
-
- it("writes error level to stderr", () => {
- const logger = new Logger({ level: "error" });
- logger.error("something broke");
-
- expect(stderrSpy).toHaveBeenCalledTimes(1);
- expect(stdoutSpy).not.toHaveBeenCalled();
- const output = stderrSpy.mock.calls[0][0] as string;
- expect(output).toMatch(/ERROR something broke/);
- });
-
- it("writes debug/info/warn to stdout", () => {
- const logger = new Logger({ level: "debug" });
- logger.debug("d");
- logger.info("i");
- logger.warn("w");
-
- expect(stdoutSpy).toHaveBeenCalledTimes(3);
- expect(stderrSpy).not.toHaveBeenCalled();
- });
-
- it("respects NO_COLOR environment variable", () => {
- process.env.NO_COLOR = "1";
- const logger = new Logger({ level: "info" });
- logger.info("no colors");
-
- const output = stdoutSpy.mock.calls[0][0] as string;
- expect(output).not.toContain("\x1b[");
- });
-
- it("includes extra args on subsequent lines", () => {
- const logger = new Logger({ level: "error" });
- logger.error("failed", new Error("bad input"));
-
- expect(stderrSpy).toHaveBeenCalledTimes(2);
- const extra = stderrSpy.mock.calls[1][0] as string;
- expect(extra).toBe(" bad input\n");
- });
-
- it("silent level suppresses all output", () => {
- const logger = new Logger({ level: "silent" });
- logger.debug("nope");
- logger.info("nope");
- logger.warn("nope");
- logger.error("nope");
-
- expect(stdoutSpy).not.toHaveBeenCalled();
- expect(stderrSpy).not.toHaveBeenCalled();
- });
-
- it("setLevel changes level at runtime", () => {
- const logger = new Logger({ level: "error" });
- logger.info("hidden");
- expect(stdoutSpy).not.toHaveBeenCalled();
-
- logger.setLevel("debug");
- logger.info("visible");
- expect(stdoutSpy).toHaveBeenCalledTimes(1);
- });
-
- it("includes module prefix in output", () => {
- const logger = new Logger({ level: "info", module: "test-mod" });
- logger.info("hello");
-
- const output = stdoutSpy.mock.calls[0][0] as string;
- expect(output).toContain("[test-mod]");
- expect(output).toContain("hello");
- });
-
- it("child creates logger with module prefix", () => {
- const parent = new Logger({ level: "info" });
- const child = parent.child("child-mod");
- child.info("from child");
-
- const output = stdoutSpy.mock.calls[0][0] as string;
- expect(output).toContain("[child-mod]");
- });
-
- it("formats object args as key=value pairs", () => {
- const logger = new Logger({ level: "info" });
- logger.info("ctx test", { foo: "bar", num: 42 });
-
- expect(stdoutSpy).toHaveBeenCalledTimes(2);
- const extra = stdoutSpy.mock.calls[1][0] as string;
- expect(extra).toContain("foo=bar");
- expect(extra).toContain("num=42");
- });
-});
diff --git a/src/cli/lib/logger.ts b/src/cli/lib/logger.ts
deleted file mode 100644
index b7e83d2e6..000000000
--- a/src/cli/lib/logger.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-export type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
-
-const LEVELS: Record<LogLevel, number> = {
- debug: 0,
- info: 1,
- warn: 2,
- error: 3,
- silent: 4,
-};
-
-const LABELS: Record<Exclude<LogLevel, "silent">, string> = {
- debug: "DEBUG",
- info: "INFO ",
- warn: "WARN ",
- error: "ERROR",
-};
-
-const COLORS: Record<Exclude<LogLevel, "silent">, string> = {
- debug: "\x1b[90m", // gray
- info: "\x1b[36m", // cyan
- warn: "\x1b[33m", // yellow
- error: "\x1b[31m", // red
-};
-
-const RESET = "\x1b[0m";
-const DIM = "\x1b[2m";
-const BOLD = "\x1b[1m";
-
-function useColor(): boolean {
- if (process.env.NO_COLOR !== undefined) return false;
- if (process.env.FORCE_COLOR !== undefined) return true;
- return process.stdout.isTTY === true;
-}
-
-function timestamp(): string {
- const d = new Date();
- const Y = d.getFullYear();
- const M = String(d.getMonth() + 1).padStart(2, "0");
- const D = String(d.getDate()).padStart(2, "0");
- const h = String(d.getHours()).padStart(2, "0");
- const m = String(d.getMinutes()).padStart(2, "0");
- const s = String(d.getSeconds()).padStart(2, "0");
- return `${Y}-${M}-${D} ${h}:${m}:${s}`;
-}
-
-export interface LoggerOptions {
- level?: LogLevel;
- module?: string;
-}
-
-export class Logger {
- private level: number;
- private color: boolean;
- private module: string | undefined;
-
- constructor(opts: LoggerOptions = {}) {
- const envLevel = process.env.ALOOK_LOG_LEVEL as LogLevel | undefined;
- this.level = LEVELS[opts.level ?? envLevel ?? "info"];
- this.color = useColor();
- this.module = opts.module;
- }
-
- setLevel(level: LogLevel): void {
- this.level = LEVELS[level];
- }
-
- child(module: string): Logger {
- const child = new Logger({ level: this.levelName(), module });
- return child;
- }
-
- debug(msg: string, ...args: unknown[]): void {
- this.write("debug", msg, args);
- }
-
- info(msg: string, ...args: unknown[]): void {
- this.write("info", msg, args);
- }
-
- warn(msg: string, ...args: unknown[]): void {
- this.write("warn", msg, args);
- }
-
- error(msg: string, ...args: unknown[]): void {
- this.write("error", msg, args);
- }
-
- private levelName(): LogLevel {
- for (const [name, num] of Object.entries(LEVELS)) {
- if (num === this.level) return name as LogLevel;
- }
- return "info";
- }
-
- private write(
- level: Exclude<LogLevel, "silent">,
- msg: string,
- args: unknown[],
- ): void {
- if (LEVELS[level] < this.level) return;
-
- const ts = timestamp();
- const label = LABELS[level];
- const mod = this.module ? `[${this.module}]` : "";
- let line: string;
-
- if (this.color) {
- const c = COLORS[level];
- const modStr = mod ? ` ${BOLD}${mod}${RESET}` : "";
- line = `${DIM}${ts}${RESET} ${c}${label}${RESET}${modStr} ${msg}`;
- } else {
- const modStr = mod ? ` ${mod}` : "";
- line = `${ts} ${label}${modStr} ${msg}`;
- }
-
- const dest = level === "error" ? process.stderr : process.stdout;
- dest.write(line + "\n");
-
- for (const a of args) {
- if (a instanceof Error) {
- dest.write(` ${a.message}\n`);
- if (a.stack && this.level <= LEVELS.debug) {
- dest.write(` ${a.stack}\n`);
- }
- } else if (a !== null && typeof a === "object") {
- const pairs = Object.entries(a as Record<string, unknown>)
- .map(([k, v]) => `${k}=${typeof v === "object" ? JSON.stringify(v) : v}`)
- .join(" ");
- if (pairs) dest.write(` ${pairs}\n`);
- } else if (a !== undefined) {
- dest.write(` ${String(a)}\n`);
- }
- }
- }
-}
-
-export function createLogger(opts?: LoggerOptions): Logger {
- return new Logger(opts);
-}
-
-export const log = createLogger();
diff --git a/src/cli/lib/output.test.ts b/src/cli/lib/output.test.ts
deleted file mode 100644
index 4fe6f46b5..000000000
--- a/src/cli/lib/output.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { vi, describe, it, expect, beforeEach } from "vitest";
-import { printJSON, printTable } from "./output.js";
-
-let logSpy: ReturnType<typeof vi.spyOn>;
-
-beforeEach(() => {
- vi.restoreAllMocks();
- logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
-});
-
-describe("printJSON", () => {
- it("outputs pretty-printed JSON with 2-space indent", () => {
- const data = { name: "test", count: 42 };
- printJSON(data);
- expect(logSpy).toHaveBeenCalledWith(JSON.stringify(data, null, 2));
- });
-});
-
-describe("printTable", () => {
- it("prints aligned columns with headers and separator", () => {
- const headers = ["ID", "NAME", "STATUS"];
- const rows = [
- ["1", "alpha", "active"],
- ["22", "beta-long", "inactive"],
- ];
-
- printTable(headers, rows);
-
- const calls = logSpy.mock.calls.map((c: any) => c[0]);
-
- expect(calls[0]).toBe("ID NAME STATUS ");
- expect(calls[1]).toBe("-- --------- --------");
- expect(calls[2]).toBe("1 alpha active ");
- expect(calls[3]).toBe("22 beta-long inactive");
- });
-});
diff --git a/src/cli/lib/output.ts b/src/cli/lib/output.ts
deleted file mode 100644
index d7566634d..000000000
--- a/src/cli/lib/output.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-export function printTable(headers: string[], rows: string[][]): void {
- const widths = headers.map((h, i) =>
- Math.max(h.length, ...rows.map((r) => (r[i] || "").length)),
- );
- const header = headers
- .map((h, i) => h.padEnd(widths[i]))
- .join(" ");
- const separator = widths.map((w) => "-".repeat(w)).join(" ");
- console.log(header);
- console.log(separator);
- rows.forEach((r) =>
- console.log(
- r
- .map((c, i) => (c || "").padEnd(widths[i]))
- .join(" "),
- ),
- );
-}
-
-export function printJSON(data: unknown): void {
- console.log(JSON.stringify(data, null, 2));
-}
diff --git a/src/cli/lib/platform.test.ts b/src/cli/lib/platform.test.ts
deleted file mode 100644
index d4dbbe0a4..000000000
--- a/src/cli/lib/platform.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { tmpdir } from "os";
-import { join, sep } from "path";
-import { tempDir, isPathContained, isWindows } from "./platform.js";
-
-describe("platform", () => {
- describe("tempDir", () => {
- it("returns os tmpdir joined with subdir", () => {
- expect(tempDir("alook-test")).toBe(join(tmpdir(), "alook-test"));
- });
- });
-
- describe("isPathContained", () => {
- it("returns true for exact match", () => {
- expect(isPathContained("/a/b", "/a/b")).toBe(true);
- });
-
- it("returns true for child path", () => {
- expect(isPathContained(`/a/b`, `/a/b${sep}c`)).toBe(true);
- });
-
- it("returns false for sibling with shared prefix", () => {
- expect(isPathContained("/a/b", "/a/bc")).toBe(false);
- });
-
- it("returns false for parent path", () => {
- expect(isPathContained("/a/b/c", "/a/b")).toBe(false);
- });
- });
-
- describe("isWindows", () => {
- it("reflects current platform", () => {
- expect(isWindows).toBe(process.platform === "win32");
- });
- });
-});
diff --git a/src/cli/lib/platform.ts b/src/cli/lib/platform.ts
deleted file mode 100644
index 77c7bfc6a..000000000
--- a/src/cli/lib/platform.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { tmpdir } from "os";
-import { join, sep } from "path";
-
-export const isWindows = process.platform === "win32";
-
-export function tempDir(subdir: string): string {
- return join(tmpdir(), subdir);
-}
-
-export function isPathContained(parent: string, child: string): boolean {
- return child === parent || child.startsWith(parent + sep);
-}
diff --git a/src/cli/lib/resolve-client.test.ts b/src/cli/lib/resolve-client.test.ts
deleted file mode 100644
index 1542430f5..000000000
--- a/src/cli/lib/resolve-client.test.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
-
-vi.mock("./config.js", async (importActual) => ({
- ...(await importActual<typeof import("./config.js")>()),
- loadCLIConfigForProfile: vi.fn(),
-}));
-
-vi.mock("./env.js", () => ({
- cmdPrefix: () => "npx @alook/cli",
-}));
-
-import { resolveClientOpts } from "./resolve-client.js";
-import { loadCLIConfigForProfile } from "./config.js";
-
-const mockedLoadConfig = vi.mocked(loadCLIConfigForProfile);
-
-function makeCommand(opts: Record<string, unknown> = {}) {
- return { parent: null, opts: () => opts } as any;
-}
-
-function makeNestedCommand(rootOpts: Record<string, unknown> = {}) {
- const root = { parent: null, opts: () => rootOpts } as any;
- const child = { parent: root, opts: () => ({}) } as any;
- return { parent: child, opts: () => ({}) } as any;
-}
-
-describe("resolveClientOpts", () => {
- const envKeys = ["ALOOK_SERVER_URL", "ALOOK_WORKSPACE_ID", "ALOOK_TOKEN"];
- const savedEnv: Record<string, string | undefined> = {};
-
- beforeEach(() => {
- for (const k of envKeys) {
- savedEnv[k] = process.env[k];
- delete process.env[k];
- }
- mockedLoadConfig.mockReturnValue({
- server_url: "",
- watched_workspaces: [],
- });
- });
-
- afterEach(() => {
- for (const k of envKeys) {
- if (savedEnv[k] !== undefined) process.env[k] = savedEnv[k];
- else delete process.env[k];
- }
- });
-
- it("resolves from env vars when no config exists", () => {
- process.env.ALOOK_SERVER_URL = "https://self-hosted.example.com";
- process.env.ALOOK_WORKSPACE_ID = "ws_env";
- process.env.ALOOK_TOKEN = "tok_env";
-
- const result = resolveClientOpts(makeCommand(), { agentId: "ag1" });
-
- expect(result.serverUrl).toBe("https://self-hosted.example.com");
- expect(result.workspaceId).toBe("ws_env");
- expect(result.token).toBe("tok_env");
- });
-
- it("env token takes priority over config token", () => {
- process.env.ALOOK_TOKEN = "tok_env";
- mockedLoadConfig.mockReturnValue({
- server_url: "https://config.example.com",
- watched_workspaces: [
- { id: "ws1", name: "WS1", token: "tok_config", agent_ids: ["ag1"] },
- ],
- });
-
- const result = resolveClientOpts(makeCommand(), { agentId: "ag1" });
-
- expect(result.token).toBe("tok_env");
- expect(result.workspaceId).toBe("ws1");
- });
-
- it("flag > env > config for server URL", () => {
- process.env.ALOOK_SERVER_URL = "https://env.example.com";
- mockedLoadConfig.mockReturnValue({
- server_url: "https://config.example.com",
- watched_workspaces: [
- { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["ag1"] },
- ],
- });
-
- const result = resolveClientOpts(
- makeCommand({ server: "https://flag.example.com" }),
- { agentId: "ag1" },
- );
-
- expect(result.serverUrl).toBe("https://flag.example.com");
- });
-
- it("resolves workspace by agent_id from config", () => {
- mockedLoadConfig.mockReturnValue({
- server_url: "https://alook.ai",
- watched_workspaces: [
- { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["ag1"] },
- { id: "ws2", name: "WS2", token: "tok2", agent_ids: ["ag2"] },
- ],
- });
-
- const result = resolveClientOpts(makeCommand(), { agentId: "ag2" });
-
- expect(result.workspaceId).toBe("ws2");
- expect(result.token).toBe("tok2");
- });
-
- it("falls back to single workspace when agent not found", () => {
- mockedLoadConfig.mockReturnValue({
- server_url: "https://alook.ai",
- watched_workspaces: [
- { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["other"] },
- ],
- });
-
- const result = resolveClientOpts(makeCommand(), { agentId: "ag_unknown" });
-
- expect(result.workspaceId).toBe("ws1");
- expect(result.token).toBe("tok1");
- });
-
- it("resolves via env when agent_id not in config and no single fallback", () => {
- process.env.ALOOK_WORKSPACE_ID = "ws_env";
- process.env.ALOOK_TOKEN = "tok_env";
- mockedLoadConfig.mockReturnValue({
- server_url: "https://alook.ai",
- watched_workspaces: [
- { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["other1"] },
- { id: "ws2", name: "WS2", token: "tok2", agent_ids: ["other2"] },
- ],
- });
-
- const result = resolveClientOpts(makeCommand(), { agentId: "ag_self_hosted" });
-
- expect(result.workspaceId).toBe("ws_env");
- expect(result.token).toBe("tok_env");
- });
-
- it("exits with error when nothing available", () => {
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
- throw new Error("__exit__");
- }) as never);
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
-
- expect(() => resolveClientOpts(makeCommand(), { agentId: "ag1" })).toThrow("__exit__");
- expect(exitSpy).toHaveBeenCalledWith(1);
-
- exitSpy.mockRestore();
- errSpy.mockRestore();
- });
-
- it("traverses to root command for parent opts", () => {
- process.env.ALOOK_TOKEN = "tok_env";
- process.env.ALOOK_WORKSPACE_ID = "ws_env";
-
- const cmd = makeNestedCommand({ server: "https://from-root.example.com" });
- const result = resolveClientOpts(cmd, { agentId: "ag1" });
-
- expect(result.serverUrl).toBe("https://from-root.example.com");
- });
-
- it("workspace flag selects specific workspace from config", () => {
- mockedLoadConfig.mockReturnValue({
- server_url: "https://alook.ai",
- watched_workspaces: [
- { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["ag1"] },
- { id: "ws2", name: "WS2", token: "tok2", agent_ids: ["ag2"] },
- ],
- });
-
- const result = resolveClientOpts(makeCommand(), { workspace: "ws2", agentId: "ag1" });
-
- expect(result.workspaceId).toBe("ws2");
- expect(result.token).toBe("tok2");
- });
-
- it("errors with workspace guidance when token is set but workspace cannot be determined", () => {
- process.env.ALOOK_TOKEN = "tok_env";
- // No ALOOK_WORKSPACE_ID, no config match, multiple workspaces
- mockedLoadConfig.mockReturnValue({
- server_url: "https://alook.ai",
- watched_workspaces: [
- { id: "ws1", name: "WS1", token: "tok1", agent_ids: ["other1"] },
- { id: "ws2", name: "WS2", token: "tok2", agent_ids: ["other2"] },
- ],
- });
-
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
- throw new Error("__exit__");
- }) as never);
- const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
-
- expect(() => resolveClientOpts(makeCommand(), { agentId: "ag_missing" })).toThrow("__exit__");
- expect(errSpy).toHaveBeenCalledWith(
- "Error: cannot determine workspace. Set ALOOK_WORKSPACE_ID env var or use --workspace flag.",
- );
-
- exitSpy.mockRestore();
- errSpy.mockRestore();
- });
-});
diff --git a/src/cli/lib/resolve-client.ts b/src/cli/lib/resolve-client.ts
deleted file mode 100644
index 4119aadf4..000000000
--- a/src/cli/lib/resolve-client.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { Command } from "commander";
-import { loadCLIConfigForProfile, activeWorkspaces } from "./config.js";
-import { cmdPrefix } from "./env.js";
-import { getRootOpts } from "./command-utils.js";
-
-export interface ResolvedClient {
- serverUrl: string;
- token: string;
- workspaceId: string;
-}
-
-export interface ResolvedClientPartial {
- serverUrl: string;
- token: string;
- workspaceId?: string;
-}
-
-export interface ResolveClientOptions {
- workspace?: string;
- agentId?: string;
-}
-
-export function resolveClientOpts(command: Command, opts: ResolveClientOptions = {}): ResolvedClient {
- const result = resolveClientOptsPartial(command, opts);
- if (!result.workspaceId) {
- console.error(
- "Error: cannot determine workspace. Set ALOOK_WORKSPACE_ID env var or use --workspace flag.",
- );
- process.exit(1);
- }
- return result as ResolvedClient;
-}
-
-export function resolveClientOptsPartial(command: Command, opts: ResolveClientOptions = {}): ResolvedClientPartial {
- const parentOpts = getRootOpts(command) as { server?: string; profile?: string };
- const cfg = loadCLIConfigForProfile(parentOpts.profile);
-
- // Server URL: flag > env > config
- const serverUrl = parentOpts.server || process.env.ALOOK_SERVER_URL || cfg.server_url;
-
- if (!serverUrl) {
- console.error("Error: no server URL configured. Set ALOOK_SERVER_URL or run register.");
- process.exit(1);
- }
-
- const workspaces = activeWorkspaces(cfg.watched_workspaces);
-
- // Workspace resolution: flag > env > config lookup by agent_id > single workspace fallback
- let ws;
- const envWorkspaceId = process.env.ALOOK_WORKSPACE_ID;
-
- if (opts.workspace) {
- ws = workspaces.find((w) => w.id === opts.workspace);
- if (!ws) {
- if (envWorkspaceId === opts.workspace) {
- ws = undefined;
- } else {
- console.error(`Error: workspace ${opts.workspace} not found in config.`);
- process.exit(1);
- }
- }
- } else if (opts.agentId) {
- ws = workspaces.find((w) => w.agent_ids?.includes(opts.agentId!));
- if (!ws) {
- if (workspaces.length === 1) {
- ws = workspaces[0];
- }
- }
- } else if (workspaces.length === 1) {
- ws = workspaces[0];
- }
-
- // Token resolution: env > config > session_token
- const envToken = process.env.ALOOK_TOKEN;
- const token = envToken || ws?.token || cfg.session_token;
-
- if (!token) {
- console.error(
- `Error: not registered. Run '${cmdPrefix()} register --token <token>' first.`,
- );
- process.exit(1);
- }
-
- // Workspace ID resolution: ws from config > env > undefined (for partial)
- const workspaceId = ws?.id || envWorkspaceId || undefined;
-
- return { serverUrl, token, workspaceId };
-}
diff --git a/src/cli/lib/runtimes.test.ts b/src/cli/lib/runtimes.test.ts
deleted file mode 100644
index 3851efc34..000000000
--- a/src/cli/lib/runtimes.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
-
-vi.mock("child_process", () => ({
- execSync: vi.fn(),
-}));
-
-import { execSync } from "child_process";
-import { isCommandAvailable, detectRuntimes } from "./runtimes.js";
-
-const mockedExecSync = vi.mocked(execSync);
-const originalPlatform = process.platform;
-
-beforeEach(() => {
- vi.clearAllMocks();
- Object.defineProperty(process, "platform", { value: "linux" });
-});
-
-afterEach(() => {
- Object.defineProperty(process, "platform", { value: originalPlatform });
-});
-
-describe("isCommandAvailable", () => {
- it("returns true when command exists", () => {
- mockedExecSync.mockReturnValue("");
- expect(isCommandAvailable("claude")).toBe(true);
- });
-
- it("returns false when command does not exist", () => {
- mockedExecSync.mockImplementation(() => {
- throw new Error("not found");
- });
- expect(isCommandAvailable("nonexistent")).toBe(false);
- });
-
- it("uses 'which' on non-windows platforms", () => {
- mockedExecSync.mockReturnValue("");
- isCommandAvailable("claude");
- expect(mockedExecSync).toHaveBeenCalledWith("which claude", { stdio: "ignore" });
- });
-
- it("uses 'where' on windows", () => {
- Object.defineProperty(process, "platform", { value: "win32" });
- mockedExecSync.mockReturnValue("");
- isCommandAvailable("claude");
- expect(mockedExecSync).toHaveBeenCalledWith("where claude", { stdio: "ignore" });
- });
-});
-
-describe("detectRuntimes", () => {
- it("returns empty array when no runtimes found", () => {
- mockedExecSync.mockImplementation(() => {
- throw new Error("not found");
- });
- expect(detectRuntimes()).toEqual([]);
- });
-
- it("detects available runtimes with versions", () => {
- mockedExecSync.mockImplementation((cmd: string) => {
- if (cmd === "which claude") return "";
- if (cmd === "claude --version") return "1.0.0\n";
- if (cmd === "which codex") return "";
- if (cmd === "codex --version") return "2.0.0\n";
- if (cmd === "which opencode") return "";
- if (cmd === "opencode --version") return "3.0.0\n";
- throw new Error("not found");
- });
-
- const result = detectRuntimes();
- expect(result).toEqual([
- { type: "claude", version: "1.0.0" },
- { type: "codex", version: "2.0.0" },
- { type: "opencode", version: "3.0.0" },
- ]);
- });
-
- it("detects runtimes on windows using 'where'", () => {
- Object.defineProperty(process, "platform", { value: "win32" });
- mockedExecSync.mockImplementation((cmd: string) => {
- if (cmd === "where claude") return "";
- if (cmd === "claude --version") return "1.0.0\n";
- if (cmd === "where codex") return "";
- if (cmd === "codex --version") return "2.0.0\n";
- throw new Error("not found");
- });
-
- const result = detectRuntimes();
- expect(result).toEqual([
- { type: "claude", version: "1.0.0" },
- { type: "codex", version: "2.0.0" },
- ]);
- });
-
- it("includes runtime with empty version when --version fails", () => {
- mockedExecSync.mockImplementation((cmd: string) => {
- if (cmd === "which claude") return "";
- if (cmd === "claude --version") throw new Error("no version");
- throw new Error("not found");
- });
-
- const result = detectRuntimes();
- expect(result).toEqual([{ type: "claude", version: "" }]);
- });
-
- it("only checks claude, codex, opencode", () => {
- mockedExecSync.mockImplementation((cmd: string) => {
- if (cmd === "which claude") return "";
- if (cmd === "claude --version") return "1.0.0\n";
- throw new Error("not found");
- });
-
- const result = detectRuntimes();
- expect(result).toHaveLength(1);
- expect(result[0].type).toBe("claude");
- });
-});
diff --git a/src/cli/lib/runtimes.ts b/src/cli/lib/runtimes.ts
deleted file mode 100644
index 00b398fd0..000000000
--- a/src/cli/lib/runtimes.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { execSync } from "child_process";
-
-export function isCommandAvailable(cmd: string): boolean {
- try {
- const check = process.platform === "win32" ? `where ${cmd}` : `which ${cmd}`;
- execSync(check, { stdio: "ignore" });
- return true;
- } catch {
- return false;
- }
-}
-
-export function detectRuntimes(): { type: string; version: string }[] {
- const found: { type: string; version: string }[] = [];
- for (const type of ["claude", "codex", "opencode"]) {
- if (isCommandAvailable(type)) {
- let version = "";
- try {
- version = execSync(`${type} --version`, { encoding: "utf-8" }).trim();
- } catch {
- // version detection optional
- }
- found.push({ type, version });
- }
- }
- return found;
-}
diff --git a/src/cli/lib/sharp.d.ts b/src/cli/lib/sharp.d.ts
deleted file mode 100644
index 5a791755e..000000000
--- a/src/cli/lib/sharp.d.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-declare module "sharp" {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const sharp: any;
- export default sharp;
-}
diff --git a/src/cli/lib/shell-env.test.ts b/src/cli/lib/shell-env.test.ts
deleted file mode 100644
index ea6a597a2..000000000
--- a/src/cli/lib/shell-env.test.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { execSync } from "child_process";
-
-vi.mock("child_process", () => ({
- execSync: vi.fn(),
-}));
-
-vi.mock("./platform.js", () => ({
- isWindows: false,
-}));
-
-const mockedExecSync = vi.mocked(execSync);
-
-describe("resolveLoginShellEnv", () => {
- const originalEnv = process.env;
-
- beforeEach(() => {
- process.env = { ...originalEnv, SHELL: "/bin/zsh", PATH: "/usr/bin" };
- vi.resetModules();
- });
-
- afterEach(() => {
- process.env = originalEnv;
- });
-
- it("calls shell with -ilc flag to source .zshrc", async () => {
- mockedExecSync.mockReturnValue("PATH=/usr/bin:/new/path\nHOME=/Users/test\n");
- const { resolveLoginShellEnv } = await import("./shell-env.js");
- resolveLoginShellEnv();
- expect(mockedExecSync).toHaveBeenCalledWith(
- "/bin/zsh -ilc 'env'",
- expect.objectContaining({ encoding: "utf-8", timeout: 5000 }),
- );
- });
-
- it("uses interactive flag so .zshrc PATH additions are picked up", async () => {
- mockedExecSync.mockReturnValue(
- "HOME=/Users/test\nPATH=/usr/bin:/Users/test/.opencode/bin\nSHELL=/bin/zsh\n",
- );
- const { resolveLoginShellEnv } = await import("./shell-env.js");
- const env = resolveLoginShellEnv();
- expect(env.PATH).toContain("/Users/test/.opencode/bin");
- });
-
- it("falls back to process.env when shell command fails", async () => {
- mockedExecSync.mockImplementation(() => {
- throw new Error("command failed");
- });
- const { resolveLoginShellEnv } = await import("./shell-env.js");
- const env = resolveLoginShellEnv();
- expect(env.PATH).toBe("/usr/bin");
- });
-
- it("falls back to process.env when output has no PATH", async () => {
- mockedExecSync.mockReturnValue("HOME=/Users/test\nUSER=test\n");
- const { resolveLoginShellEnv } = await import("./shell-env.js");
- const env = resolveLoginShellEnv();
- expect(env.PATH).toBe("/usr/bin");
- });
-
- it("parses multiline env output correctly", async () => {
- mockedExecSync.mockReturnValue(
- "HOME=/Users/gener\nPATH=/opt/homebrew/bin:/usr/bin\nSHELL=/bin/zsh\nLANG=en_US.UTF-8\n",
- );
- const { resolveLoginShellEnv } = await import("./shell-env.js");
- const env = resolveLoginShellEnv();
- expect(env.HOME).toBe("/Users/gener");
- expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
- expect(env.LANG).toBe("en_US.UTF-8");
- });
-
- it("uses default /bin/zsh when SHELL is not set", async () => {
- delete process.env.SHELL;
- mockedExecSync.mockReturnValue("PATH=/usr/bin\n");
- const { resolveLoginShellEnv } = await import("./shell-env.js");
- resolveLoginShellEnv();
- expect(mockedExecSync).toHaveBeenCalledWith(
- "/bin/zsh -ilc 'env'",
- expect.anything(),
- );
- });
-
- it("respects custom SHELL env var", async () => {
- process.env.SHELL = "/bin/bash";
- mockedExecSync.mockReturnValue("PATH=/usr/bin\n");
- const { resolveLoginShellEnv } = await import("./shell-env.js");
- resolveLoginShellEnv();
- expect(mockedExecSync).toHaveBeenCalledWith(
- "/bin/bash -ilc 'env'",
- expect.anything(),
- );
- });
-});
-
-describe("resolveLoginShellEnv (windows)", () => {
- it("returns process.env copy on Windows", async () => {
- vi.doMock("./platform.js", () => ({ isWindows: true }));
- vi.resetModules();
- mockedExecSync.mockClear();
- const { resolveLoginShellEnv } = await import("./shell-env.js");
- const env = resolveLoginShellEnv();
- expect(env.PATH).toBe(process.env.PATH);
- expect(mockedExecSync).not.toHaveBeenCalled();
- });
-});
diff --git a/src/cli/lib/shell-env.ts b/src/cli/lib/shell-env.ts
deleted file mode 100644
index 14f430a9e..000000000
--- a/src/cli/lib/shell-env.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { execSync } from "child_process";
-import { isWindows } from "./platform.js";
-
-const PASSTHROUGH_VARS = ["ALOOK_PROJECT_ROOT", "ALOOK_SERVER_URL", "ALOOK_CMD_PREFIX", "ALOOK_HEALTH_PORT"];
-
-export function resolveLoginShellEnv(): NodeJS.ProcessEnv {
- if (isWindows) {
- return { ...process.env };
- }
-
- const shell = process.env.SHELL || "/bin/zsh";
- try {
- const output = execSync(`${shell} -ilc 'env'`, {
- encoding: "utf-8",
- timeout: 5000,
- stdio: ["ignore", "pipe", "ignore"],
- });
- const env: NodeJS.ProcessEnv = {};
- for (const line of output.split("\n")) {
- const idx = line.indexOf("=");
- if (idx > 0) {
- env[line.slice(0, idx)] = line.slice(idx + 1);
- }
- }
- if (env.PATH) {
- for (const key of PASSTHROUGH_VARS) {
- if (process.env[key]) env[key] = process.env[key];
- }
- return env;
- }
- } catch {
- // fall through
- }
- return { ...process.env };
-}
diff --git a/src/cli/lib/update.test.ts b/src/cli/lib/update.test.ts
deleted file mode 100644
index 69e4e0b0f..000000000
--- a/src/cli/lib/update.test.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-
-vi.mock("child_process", () => ({
- spawn: vi.fn(),
-}));
-
-import { spawn } from "child_process";
-import { getCurrentVersion, fetchLatestVersion, runNpmUpdate } from "./update";
-import { EventEmitter } from "events";
-
-const mockSpawn = vi.mocked(spawn);
-
-describe("getCurrentVersion", () => {
- it("returns a version string", () => {
- const v = getCurrentVersion();
- expect(v).toMatch(/^\d+\.\d+\.\d+$/);
- });
-});
-
-describe("fetchLatestVersion", () => {
- beforeEach(() => {
- vi.stubGlobal("fetch", vi.fn());
- });
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it("parses npm registry response correctly", async () => {
- (globalThis.fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
- ok: true,
- json: async () => ({ version: "1.2.3" }),
- });
- const v = await fetchLatestVersion();
- expect(v).toBe("1.2.3");
- });
-
- it("returns null on network error", async () => {
- (globalThis.fetch as unknown as ReturnType<typeof vi.fn>).mockRejectedValue(
- new Error("network error"),
- );
- const v = await fetchLatestVersion();
- expect(v).toBeNull();
- });
-
- it("returns null on non-ok response", async () => {
- (globalThis.fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
- ok: false,
- });
- const v = await fetchLatestVersion();
- expect(v).toBeNull();
- });
-});
-
-describe("runNpmUpdate", () => {
- it("spawns npm install -g with correct args", async () => {
- const child = new EventEmitter() as any;
- child.stdout = new EventEmitter();
- child.stderr = new EventEmitter();
- mockSpawn.mockReturnValue(child);
-
- const promise = runNpmUpdate("1.0.0");
- child.stdout.emit("data", Buffer.from("added 1 package"));
- child.emit("close", 0);
-
- const result = await promise;
- expect(mockSpawn).toHaveBeenCalledWith(
- "npm",
- ["install", "-g", "@alook/[email protected]"],
- expect.objectContaining({ stdio: ["ignore", "pipe", "pipe"] }),
- );
- expect(result.success).toBe(true);
- expect(result.output).toContain("added 1 package");
- });
-
- it("resolves with success: false on npm error", async () => {
- const child = new EventEmitter() as any;
- child.stdout = new EventEmitter();
- child.stderr = new EventEmitter();
- mockSpawn.mockReturnValue(child);
-
- const promise = runNpmUpdate("1.0.0");
- child.stderr.emit("data", Buffer.from("ERR! 404 Not Found"));
- child.emit("close", 1);
-
- const result = await promise;
- expect(result.success).toBe(false);
- expect(result.output).toContain("ERR! 404");
- });
-
- it("handles spawn error", async () => {
- const child = new EventEmitter() as any;
- child.stdout = new EventEmitter();
- child.stderr = new EventEmitter();
- mockSpawn.mockReturnValue(child);
-
- const promise = runNpmUpdate("1.0.0");
- child.emit("error", new Error("ENOENT"));
-
- const result = await promise;
- expect(result.success).toBe(false);
- expect(result.output).toContain("ENOENT");
- });
-});
diff --git a/src/cli/lib/update.ts b/src/cli/lib/update.ts
deleted file mode 100644
index 250e3caab..000000000
--- a/src/cli/lib/update.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { spawn } from "child_process";
-import { getCurrentVersion } from "./version.js";
-
-export { getCurrentVersion };
-
-export function fetchLatestVersion(): Promise<string | null> {
- return fetch("https://registry.npmjs.org/@alook/cli/latest")
- .then((res) => {
- if (!res.ok) return null;
- return res.json() as Promise<{ version?: string }>;
- })
- .then((data) => data?.version ?? null)
- .catch(() => null);
-}
-
-export function runNpmUpdate(
- targetVersion: string,
-): Promise<{ success: boolean; output: string }> {
- return new Promise((resolve) => {
- const chunks: Buffer[] = [];
- const child = spawn("npm", ["install", "-g", `@alook/cli@${targetVersion}`], {
- stdio: ["ignore", "pipe", "pipe"],
- });
- child.stdout?.on("data", (d: Buffer) => chunks.push(d));
- child.stderr?.on("data", (d: Buffer) => chunks.push(d));
- child.on("error", (err) => {
- resolve({ success: false, output: err.message });
- });
- child.on("close", (code) => {
- const output = Buffer.concat(chunks).toString();
- resolve({ success: code === 0, output });
- });
- });
-}
diff --git a/src/cli/lib/version.test.ts b/src/cli/lib/version.test.ts
deleted file mode 100644
index 5edd9f279..000000000
--- a/src/cli/lib/version.test.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { readFileSync } from "fs";
-import { join, dirname } from "path";
-import { fileURLToPath } from "url";
-import { getCurrentVersion } from "./version.js";
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-describe("getCurrentVersion", () => {
- it("returns the version declared in the CLI's package.json", () => {
- const pkg = JSON.parse(
- readFileSync(join(__dirname, "..", "package.json"), "utf-8"),
- );
- expect(getCurrentVersion()).toBe(pkg.version);
- });
-});
diff --git a/src/cli/lib/version.ts b/src/cli/lib/version.ts
deleted file mode 100644
index 5596c4087..000000000
--- a/src/cli/lib/version.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { readFileSync } from "fs";
-import { join, dirname } from "path";
-import { fileURLToPath } from "url";
-
-export function getCurrentVersion(): string {
- const __dirname = dirname(fileURLToPath(import.meta.url));
- const candidates = [
- join(__dirname, "..", "package.json"),
- join(__dirname, "..", "..", "package.json"),
- ];
- for (const candidate of candidates) {
- try {
- const pkg = JSON.parse(readFileSync(candidate, "utf-8"));
- if (typeof pkg.version === "string") return pkg.version;
- } catch {
- // try next candidate
- }
- }
- return "unknown";
-}
diff --git a/src/cli/package.json b/src/cli/package.json
deleted file mode 100644
index 984208ac5..000000000
--- a/src/cli/package.json
+++ /dev/null
@@ -1,65 +0,0 @@
-{
- "name": "@alook/cli",
- "version": "0.1.38",
- "description": "Alook CLI — Enable Your Person Colleague",
- "license": "Apache-2.0",
- "homepage": "https://github.com/alookai/alook#readme",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/alookai/alook.git",
- "directory": "src/cli"
- },
- "bugs": {
- "url": "https://github.com/alookai/alook/issues"
- },
- "keywords": [
- "alook",
- "cli",
- "ai",
- "agent",
- "daemon",
- "email"
- ],
- "type": "module",
- "bin": {
- "alook": "dist/index.js"
- },
- "main": "./dist/index.js",
- "files": [
- "dist",
- "README.md",
- "LICENSE"
- ],
- "engines": {
- "node": ">=20"
- },
- "publishConfig": {
- "access": "public"
- },
- "scripts": {
- "dev": "bun run src/index.ts",
- "build": "bun build src/index.ts --outdir dist --target node --format esm --external citty --external commander --external postal-mime --external playwright-core --external sharp && bun build daemon/session-runner.ts --outdir dist --target node --format esm --external citty --external commander --external postal-mime && bun build daemon/meeting-runner.ts --outdir dist --target node --format esm --external playwright-core && node scripts/prepare-dist.mjs",
- "prepack": "pnpm run build",
- "knip": "knip",
- "test": "vitest run",
- "test:integration": "vitest run --config ../../tests/integration/cli/vitest.config.ts --passWithNoTests",
- "lint": "eslint .",
- "typecheck": "tsc --noEmit -p tsconfig.build.json"
- },
- "dependencies": {
- "citty": "^0.2.2",
- "commander": "^14.0.3",
- "playwright-core": "^1.62.1",
- "postal-mime": "^2.7.6",
- "sharp": "^0.35.4"
- },
- "devDependencies": {
- "@alook/shared": "workspace:*",
- "@types/bun": "^1.4.0",
- "eslint": "^9.39.5",
- "knip": "^6.32.2",
- "typescript": "^6.0.3",
- "typescript-eslint": "^8.69.0",
- "vitest": "4.1.11"
- }
-}
diff --git a/src/cli/scripts/prepare-dist.mjs b/src/cli/scripts/prepare-dist.mjs
deleted file mode 100644
index 5e3a0f53e..000000000
--- a/src/cli/scripts/prepare-dist.mjs
+++ /dev/null
@@ -1,16 +0,0 @@
-import { readFileSync, writeFileSync, chmodSync, copyFileSync } from "node:fs";
-import { resolve } from "node:path";
-
-const entry = resolve("dist/index.js");
-const src = readFileSync(entry, "utf8");
-const shebang = "#!/usr/bin/env node\n";
-if (!src.startsWith(shebang)) {
- writeFileSync(entry, shebang + src);
-}
-chmodSync(entry, 0o755);
-console.log("prepared", entry);
-
-const rootLicense = resolve("../../LICENSE");
-const packageLicense = resolve("LICENSE");
-copyFileSync(rootLicense, packageLicense);
-console.log("copied", rootLicense, "->", packageLicense);
diff --git a/src/cli/src/index.ts b/src/cli/src/index.ts
deleted file mode 100644
index 380f21db7..000000000
--- a/src/cli/src/index.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/usr/bin/env node
-import { Command } from "commander";
-import { registerCommand } from "../commands/register.js";
-import { loginCommand } from "../commands/login.js";
-import { statusCommand } from "../commands/status.js";
-import { daemonCommand } from "../commands/daemon.js";
-import { configCommand } from "../commands/config.js";
-import { emailCommand } from "../commands/email.js";
-import { calendarCommand } from "../commands/calendar.js";
-import { issueCommand } from "../commands/issue.js";
-import { agentCommand } from "../commands/agent.js";
-import { versionCommand } from "../commands/version.js";
-import { updateCommand } from "../commands/update.js";
-import { syncCommand } from "../commands/sync.js";
-import { workspaceCommand } from "../commands/workspace.js";
-
-const program = new Command();
-
-program
- .name("alook")
- .description("Alook CLI")
- .option("--server <url>", "Server URL")
- .option("--profile <name>", "Profile name");
-
-program.addCommand(registerCommand());
-program.addCommand(loginCommand());
-program.addCommand(statusCommand());
-program.addCommand(daemonCommand());
-program.addCommand(emailCommand());
-program.addCommand(calendarCommand());
-program.addCommand(issueCommand());
-program.addCommand(agentCommand());
-program.addCommand(configCommand());
-program.addCommand(versionCommand());
-program.addCommand(updateCommand());
-program.addCommand(syncCommand());
-program.addCommand(workspaceCommand());
-
-program.parse();
diff --git a/src/cli/tsconfig.build.json b/src/cli/tsconfig.build.json
deleted file mode 100644
index 0a104bc79..000000000
--- a/src/cli/tsconfig.build.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "types": ["bun"]
- },
- "include": ["src", "commands", "daemon", "lib"],
- "exclude": ["**/__tests__", "**/*.test.ts"]
-}
diff --git a/src/cli/tsconfig.json b/src/cli/tsconfig.json
deleted file mode 100644
index b3e4828ee..000000000
--- a/src/cli/tsconfig.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "ESNext",
- "moduleResolution": "bundler",
- "strict": true,
- "skipLibCheck": true,
- "types": ["bun", "vitest/globals"]
- },
- "include": ["src", "commands", "daemon", "lib", "**/*.test.ts", "**/__tests__/**/*.ts"]
-}
diff --git a/src/cli/vitest.config.ts b/src/cli/vitest.config.ts
deleted file mode 100644
index b8b015634..000000000
--- a/src/cli/vitest.config.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { defineConfig, mergeConfig } from "vitest/config"
-import shared from "../../vitest.shared"
-
-export default mergeConfig(shared, defineConfig({
- test: {
- include: ["**/*.test.ts"],
- },
-}))
diff --git a/tests/integration/cli/community-rate-limit.test.ts b/src/web/src/test/e2e/community-rate-limit.test.ts
similarity index 100%
rename from tests/integration/cli/community-rate-limit.test.ts
rename to src/web/src/test/e2e/community-rate-limit.test.ts
diff --git a/tests/integration/cli/register-poll-complete.test.ts b/tests/integration/cli/register-poll-complete.test.ts
deleted file mode 100644
index 373cfff34..000000000
--- a/tests/integration/cli/register-poll-complete.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { describe, it, expect, beforeAll, afterAll } from "vitest"
-import { randomUUID } from "crypto"
-import {
- seedTestData,
- cleanupTestData,
- type TestSeed,
- sqlRun,
- sqlQuery,
-} from "@alook/test-utils"
-import { DaemonClient } from "../../../src/cli/daemon/client"
-import {
- RegisterResponseSchema,
- PollResponseSchema,
- TaskApiBaseSchema,
-} from "@alook/shared"
-
-const APP_URL = process.env.APP_URL ?? "http://localhost:3000"
-const client = new DaemonClient(APP_URL)
-
-let seed: TestSeed
-const daemonId = `daemon_integ_${randomUUID().slice(0, 8)}`
-let registeredRuntimeId: string
-let conversationId: string
-let taskId: string
-
-beforeAll(() => {
- seed = seedTestData()
-})
-afterAll(() => cleanupTestData(seed))
-
-describe("register → poll → start → messages → complete lifecycle", () => {
- it("register returns runtimes matching RegisterResponseSchema", async () => {
- const result = await client.register(seed.machineToken, {
- workspace_id: seed.workspaceId,
- daemon_id: daemonId,
- device_name: "integ-test-machine",
- cli_version: "0.1.0-integ",
- runtimes: [{ provider: "claude", runtime_mode: "local", version: "4.0" }],
- })
-
- const parsed = RegisterResponseSchema.safeParse(result)
- expect(parsed.success).toBe(true)
- expect(result.runtimes).toHaveLength(1)
- expect(result.runtimes[0].id).toBeTruthy()
- registeredRuntimeId = result.runtimes[0].id
- })
-
- it("poll with no queued tasks returns empty array matching PollResponseSchema", async () => {
- const result = await client.poll(seed.machineToken, daemonId, 1, "0.1.0-integ")
- const parsed = PollResponseSchema.safeParse({
- tasks: result.tasks,
- evicted: result.evicted,
- pending_update: result.pending_update,
- pending_rescan: result.pending_rescan,
- file_requests: result.file_requests,
- meetings: result.meetings,
- })
- expect(parsed.success).toBe(true)
- expect(result.tasks).toEqual([])
- expect(result.evicted).toBe(false)
- })
-
- it("poll claims a queued task", async () => {
- const now = new Date().toISOString()
- conversationId = `conv_${randomUUID().slice(0, 8)}`
- taskId = `task_${randomUUID().slice(0, 8)}`
-
- sqlRun(`INSERT INTO conversation (id, workspace_id, agent_id, user_id, title, created_at) VALUES (?, ?, ?, ?, ?, ?)`, conversationId, seed.workspaceId, seed.agentId, seed.userId, 'integ test', now)
- sqlRun(`INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, status, type, priority, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?)`, taskId, seed.agentId, registeredRuntimeId, seed.workspaceId, conversationId, 'Hello integration test', 'queued', 'user_dm_message', now)
-
- const result = await client.poll(seed.machineToken, daemonId, 1, "0.1.0-integ")
- expect(result.tasks).toHaveLength(1)
-
- const task = result.tasks[0]
- expect(task.id).toBe(taskId)
- expect(task.prompt).toBe("Hello integration test")
- expect(task.status).toBe("dispatched")
- expect(task.workspace_id).toBe(seed.workspaceId)
- })
-
- it("start task transitions status to running and returns TaskApiBase shape", async () => {
- const result = await client.startTask(seed.machineToken, taskId) as Record<string, unknown>
- const parsed = TaskApiBaseSchema.safeParse(result)
- expect(parsed.success).toBe(true)
- expect(result.status).toBe("running")
- expect(result.started_at).toBeTruthy()
- })
-
- it("report messages stores them in DB", async () => {
- await client.reportMessages(seed.machineToken, taskId, [
- { seq: 1, type: "assistant", content: "Working on it..." },
- { seq: 2, type: "assistant", content: "Done!" },
- ])
-
- const rows = sqlQuery<{ seq: number; type: string; content: string }>(
- `SELECT seq, type, content FROM task_message WHERE task_id = ? ORDER BY seq`, taskId
- )
- expect(rows).toHaveLength(2)
- expect(rows[0].content).toBe("Working on it...")
- expect(rows[1].content).toBe("Done!")
- })
-
- it("complete task transitions status and returns TaskApiBase shape", async () => {
- const result = await client.completeTask(seed.machineToken, taskId, {
- output: "Task completed successfully",
- session_id: "sess_integ_test",
- }) as Record<string, unknown>
-
- const parsed = TaskApiBaseSchema.safeParse(result)
- expect(parsed.success).toBe(true)
- expect(result.status).toBe("completed")
- expect(result.completed_at).toBeTruthy()
- })
-
- it("DB reflects final state after completion", () => {
- const rows = sqlQuery<{ status: string; session_id: string | null; result: string | null }>(
- `SELECT status, session_id, result FROM agent_task_queue WHERE id = ?`, taskId
- )
- expect(rows).toHaveLength(1)
- expect(rows[0].status).toBe("completed")
- expect(rows[0].session_id).toBe("sess_integ_test")
- expect(rows[0].result).toContain("Task completed successfully")
- })
-
- afterAll(() => {
- try {
- sqlRun(`DELETE FROM task_message WHERE task_id = ?`, taskId)
- sqlRun(`DELETE FROM agent_task_queue WHERE id = ?`, taskId)
- sqlRun(`DELETE FROM conversation WHERE id = ?`, conversationId)
- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = ?`, daemonId)
- sqlRun(`DELETE FROM machine WHERE daemon_id = ?`, daemonId)
- } catch { /* ignore */ }
- })
-})
diff --git a/tests/integration/cli/session-resume.test.ts b/tests/integration/cli/session-resume.test.ts
deleted file mode 100644
index 10b48f2b8..000000000
--- a/tests/integration/cli/session-resume.test.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import { describe, it, expect, beforeAll, afterAll } from "vitest"
-import { randomUUID } from "crypto"
-import {
- seedTestData,
- cleanupTestData,
- type TestSeed,
- sqlRun,
- sqlQuery,
-} from "@alook/test-utils"
-import { DaemonClient } from "../../../src/cli/daemon/client"
-
-const APP_URL = process.env.APP_URL ?? "http://localhost:3000"
-const client = new DaemonClient(APP_URL)
-
-let seed: TestSeed
-const daemonId = `daemon_sess_${randomUUID().slice(0, 8)}`
-let runtimeId: string
-
-beforeAll(async () => {
- seed = seedTestData()
-
- const reg = await client.register(seed.machineToken, {
- workspace_id: seed.workspaceId,
- daemon_id: daemonId,
- device_name: "session-test-machine",
- cli_version: "0.1.0-integ",
- runtimes: [{ provider: "claude", runtime_mode: "local", version: "4.0" }],
- })
- runtimeId = reg.runtimes[0].id
-})
-afterAll(() => cleanupTestData(seed))
-
-describe("session resume via context_key", () => {
- const contextKey = `ctx_${randomUUID().slice(0, 8)}`
- const differentContextKey = `ctx_${randomUUID().slice(0, 8)}`
- let firstConversationId: string
- let firstTaskId: string
- let secondTaskId: string
- let thirdConversationId: string
- let thirdTaskId: string
-
- it("first task with context_key creates a new conversation", async () => {
- const now = new Date().toISOString()
- firstConversationId = `conv_${randomUUID().slice(0, 8)}`
- firstTaskId = `task_${randomUUID().slice(0, 8)}`
-
- sqlRun(`INSERT INTO conversation (id, workspace_id, agent_id, user_id, title, created_at) VALUES (?, ?, ?, ?, ?, ?)`, firstConversationId, seed.workspaceId, seed.agentId, seed.userId, 'session resume test', now)
- sqlRun(`INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, status, type, context_key, priority, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)`, firstTaskId, seed.agentId, runtimeId, seed.workspaceId, firstConversationId, 'First message', 'queued', 'user_dm_message', contextKey, now)
-
- const result = await client.poll(seed.machineToken, daemonId, 1, "0.1.0-integ")
- expect(result.tasks).toHaveLength(1)
- expect(result.tasks[0].id).toBe(firstTaskId)
- expect(result.tasks[0].context_key).toBe(contextKey)
- expect(result.tasks[0].conversation_id).toBe(firstConversationId)
-
- // Complete the first task with a session_id
- await client.startTask(seed.machineToken, firstTaskId)
- await client.completeTask(seed.machineToken, firstTaskId, {
- output: "First task done",
- session_id: "sess_first",
- })
- })
-
- it("second task with same context_key uses same conversation", async () => {
- const now = new Date().toISOString()
- secondTaskId = `task_${randomUUID().slice(0, 8)}`
-
- sqlRun(`INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, status, type, context_key, priority, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)`, secondTaskId, seed.agentId, runtimeId, seed.workspaceId, firstConversationId, 'Second message same context', 'queued', 'user_dm_message', contextKey, now)
-
- const result = await client.poll(seed.machineToken, daemonId, 1, "0.1.0-integ")
- expect(result.tasks).toHaveLength(1)
- expect(result.tasks[0].id).toBe(secondTaskId)
- expect(result.tasks[0].context_key).toBe(contextKey)
- expect(result.tasks[0].conversation_id).toBe(firstConversationId)
-
- await client.startTask(seed.machineToken, secondTaskId)
- await client.completeTask(seed.machineToken, secondTaskId, {
- output: "Second task done",
- session_id: "sess_first",
- })
- })
-
- it("task with different context_key uses a different conversation", async () => {
- const now = new Date().toISOString()
- thirdConversationId = `conv_${randomUUID().slice(0, 8)}`
- thirdTaskId = `task_${randomUUID().slice(0, 8)}`
-
- sqlRun(`INSERT INTO conversation (id, workspace_id, agent_id, user_id, title, created_at) VALUES (?, ?, ?, ?, ?, ?)`, thirdConversationId, seed.workspaceId, seed.agentId, seed.userId, 'different context', now)
- sqlRun(`INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, status, type, context_key, priority, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)`, thirdTaskId, seed.agentId, runtimeId, seed.workspaceId, thirdConversationId, 'Different context message', 'queued', 'user_dm_message', differentContextKey, now)
-
- const result = await client.poll(seed.machineToken, daemonId, 1, "0.1.0-integ")
- expect(result.tasks).toHaveLength(1)
- expect(result.tasks[0].id).toBe(thirdTaskId)
- expect(result.tasks[0].context_key).toBe(differentContextKey)
- expect(result.tasks[0].conversation_id).toBe(thirdConversationId)
- expect(result.tasks[0].conversation_id).not.toBe(firstConversationId)
- })
-
- it("DB shows different session_ids for different context_keys", async () => {
- await client.startTask(seed.machineToken, thirdTaskId)
- await client.completeTask(seed.machineToken, thirdTaskId, {
- output: "Third task done",
- session_id: "sess_different",
- })
-
- const rows = sqlQuery<{ id: string; context_key: string | null; session_id: string | null; conversation_id: string }>(
- `SELECT id, context_key, session_id, conversation_id FROM agent_task_queue WHERE id IN (?, ?, ?) ORDER BY created_at`, firstTaskId, secondTaskId, thirdTaskId
- )
- expect(rows).toHaveLength(3)
-
- // First two tasks share conversation and context_key
- expect(rows[0].context_key).toBe(contextKey)
- expect(rows[1].context_key).toBe(contextKey)
- expect(rows[0].conversation_id).toBe(rows[1].conversation_id)
- expect(rows[0].session_id).toBe("sess_first")
- expect(rows[1].session_id).toBe("sess_first")
-
- // Third task has different context_key and conversation
- expect(rows[2].context_key).toBe(differentContextKey)
- expect(rows[2].conversation_id).not.toBe(rows[0].conversation_id)
- expect(rows[2].session_id).toBe("sess_different")
- })
-
- afterAll(() => {
- try {
- sqlRun(`DELETE FROM agent_task_queue WHERE id IN (?, ?, ?)`, firstTaskId, secondTaskId, thirdTaskId)
- sqlRun(`DELETE FROM conversation WHERE id IN (?, ?)`, firstConversationId, thirdConversationId)
- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = ?`, daemonId)
- sqlRun(`DELETE FROM machine WHERE daemon_id = ?`, daemonId)
- } catch { /* ignore */ }
- })
-})
diff --git a/tests/integration/cli/setup.ts b/tests/integration/cli/setup.ts
deleted file mode 100644
index 5402b42a4..000000000
--- a/tests/integration/cli/setup.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-if (!process.env.APP_URL) {
- process.env.APP_URL = "http://localhost:3000"
-}
diff --git a/tests/integration/cli/skill-sync.test.ts b/tests/integration/cli/skill-sync.test.ts
deleted file mode 100644
index 2a6062be9..000000000
--- a/tests/integration/cli/skill-sync.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { describe, it, expect, beforeAll, afterAll } from "vitest"
-import { randomUUID } from "crypto"
-import {
- seedTestData,
- cleanupTestData,
- type TestSeed,
- sqlQuery,
-} from "@alook/test-utils"
-import { DaemonClient } from "../../../src/cli/daemon/client"
-
-const APP_URL = process.env.APP_URL ?? "http://localhost:3000"
-const client = new DaemonClient(APP_URL)
-
-let seed: TestSeed
-const daemonId = `daemon_skill_${randomUUID().slice(0, 8)}`
-
-beforeAll(async () => {
- seed = seedTestData()
-
- await client.register(seed.machineToken, {
- workspace_id: seed.workspaceId,
- daemon_id: daemonId,
- device_name: "skill-test-machine",
- cli_version: "0.1.0-integ",
- runtimes: [{ provider: "claude", runtime_mode: "local", version: "4.0" }],
- })
-})
-afterAll(() => cleanupTestData(seed))
-
-describe("skill sync", () => {
- const skills = [
- { name: "test-skill-alpha", description: "Alpha skill for testing" },
- { name: "test-skill-beta", description: "Beta skill for testing" },
- ]
-
- it("POST /api/daemon/skills/sync (global scope) stores skills in DB", async () => {
- await client.syncSkills(seed.machineToken, {
- scope: "global",
- daemon_id: daemonId,
- runtime: "claude",
- skills,
- })
-
- const rows = sqlQuery<{ name: string; description: string; runtime: string; daemon_id: string | null }>(
- `SELECT name, description, runtime, daemon_id FROM agent_skill WHERE workspace_id = '${seed.workspaceId}' AND runtime = 'claude' AND daemon_id = '${daemonId}' ORDER BY name`
- )
- expect(rows.length).toBeGreaterThanOrEqual(2)
- const alpha = rows.find(r => r.name === "test-skill-alpha")
- const beta = rows.find(r => r.name === "test-skill-beta")
- expect(alpha).toBeDefined()
- expect(alpha!.description).toBe("Alpha skill for testing")
- expect(beta).toBeDefined()
- expect(beta!.description).toBe("Beta skill for testing")
- })
-
- it("re-sync replaces old skills (stale removal)", async () => {
- await client.syncSkills(seed.machineToken, {
- scope: "global",
- daemon_id: daemonId,
- runtime: "claude",
- skills: [{ name: "test-skill-gamma", description: "Gamma replaces all" }],
- })
-
- const rows = sqlQuery<{ name: string }>(
- `SELECT name FROM agent_skill WHERE workspace_id = '${seed.workspaceId}' AND runtime = 'claude' AND daemon_id = '${daemonId}'`
- )
- expect(rows).toHaveLength(1)
- expect(rows[0].name).toBe("test-skill-gamma")
- })
-
- it("POST /api/daemon/skills/sync (agent scope) scopes to agent", async () => {
- await client.syncSkills(seed.machineToken, {
- scope: "agent",
- agent_id: seed.agentId,
- runtime: "claude",
- skills: [{ name: "agent-specific-skill", description: "Agent scoped" }],
- })
-
- const rows = sqlQuery<{ name: string; agent_id: string | null }>(
- `SELECT name, agent_id FROM agent_skill WHERE workspace_id = '${seed.workspaceId}' AND agent_id = '${seed.agentId}' AND runtime = 'claude'`
- )
- expect(rows).toHaveLength(1)
- expect(rows[0].name).toBe("agent-specific-skill")
- expect(rows[0].agent_id).toBe(seed.agentId)
- })
-
-})
diff --git a/tests/integration/cli/vitest.config.ts b/tests/integration/cli/vitest.config.ts
deleted file mode 100644
index 76fea948a..000000000
--- a/tests/integration/cli/vitest.config.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { defineConfig, mergeConfig } from "vitest/config"
-import { resolve } from "path"
-import shared from "../../../vitest.shared"
-
-const dir = resolve(import.meta.dirname)
-const root = resolve(dir, "../../../")
-
-export default mergeConfig(shared, defineConfig({
- resolve: {
- alias: {
- "@alook/shared/community-cli-contract": resolve(root, "src/shared/src/community-cli-contract.ts"),
- "@alook/shared/lib/discriminator": resolve(root, "src/shared/src/lib/discriminator.ts"),
- "@alook/test-utils": resolve(root, "tests/utils/src/index.ts"),
- "@alook/shared": resolve(root, "src/shared/src/index.ts"),
- },
- },
- test: {
- testTimeout: 30_000,
- hookTimeout: 30_000,
- include: [`${dir}/**/*.test.ts`],
- setupFiles: [`${dir}/setup.ts`],
- fileParallelism: false,
- },
-}))
diff --git a/tests/integration/cli/ws-push-poll.test.ts b/tests/integration/cli/ws-push-poll.test.ts
deleted file mode 100644
index 47802f6d7..000000000
--- a/tests/integration/cli/ws-push-poll.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { describe, it, expect, beforeAll, afterAll } from "vitest"
-import { randomUUID } from "crypto"
-import {
- seedTestData,
- cleanupTestData,
- type TestSeed,
- sqlRun,
-} from "@alook/test-utils"
-import { DaemonClient } from "../../../src/cli/daemon/client"
-import { DaemonPushMessageSchema, DEV_WEB_URL, DEV_WS_DO_URL } from "@alook/shared"
-
-const APP_URL = process.env.APP_URL ?? DEV_WEB_URL
-const WS_DO_URL = process.env.WS_DO_URL ?? DEV_WS_DO_URL
-const client = new DaemonClient(APP_URL)
-
-let seed: TestSeed
-const daemonId = `daemon_ws_${randomUUID().slice(0, 8)}`
-let runtimeId: string
-let wsAvailable = false
-
-beforeAll(async () => {
- seed = seedTestData()
-
- // Check if WS-DO is available
- try {
- const res = await fetch(WS_DO_URL, { signal: AbortSignal.timeout(2000) })
- wsAvailable = res.status !== 0
- } catch {
- wsAvailable = false
- }
-
- const reg = await client.register(seed.machineToken, {
- workspace_id: seed.workspaceId,
- daemon_id: daemonId,
- device_name: "ws-test-machine",
- cli_version: "0.1.0-integ",
- runtimes: [{ provider: "claude", runtime_mode: "local", version: "4.0" }],
- })
- runtimeId = reg.runtimes[0].id
-})
-afterAll(() => cleanupTestData(seed))
-
-describe("WebSocket push → poll", () => {
- it.skipIf(!wsAvailable)("daemon.tasks push triggers immediate poll with correct task", async () => {
- const now = new Date().toISOString()
- const conversationId = `conv_ws_${randomUUID().slice(0, 8)}`
- const taskId = `task_ws_${randomUUID().slice(0, 8)}`
-
- sqlRun(`INSERT INTO conversation (id, workspace_id, agent_id, user_id, title, created_at) VALUES (?, ?, ?, ?, ?, ?)`, conversationId, seed.workspaceId, seed.agentId, seed.userId, 'ws push test', now)
- sqlRun(`INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, status, type, priority, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?)`, taskId, seed.agentId, runtimeId, seed.workspaceId, conversationId, 'WS push test prompt', 'queued', 'user_dm_message', now)
-
- // Connect WebSocket and wait for push message
- const wsUrl = `${WS_DO_URL.replace("http", "ws")}/ws/daemon?token=${seed.machineToken}&daemon_id=${daemonId}`
- const ws = new WebSocket(wsUrl)
-
- const pushMessage = await new Promise<unknown>((resolve, reject) => {
- const timeout = setTimeout(() => {
- ws.close()
- reject(new Error("WebSocket push timeout — no daemon.tasks message received within 10s"))
- }, 10_000)
-
- ws.onmessage = (event) => {
- try {
- const data = JSON.parse(event.data as string)
- if (data.type === "daemon.tasks") {
- clearTimeout(timeout)
- ws.close()
- resolve(data)
- }
- } catch { /* ignore non-JSON frames */ }
- }
- ws.onerror = (err) => {
- clearTimeout(timeout)
- reject(err)
- }
- })
-
- const parsed = DaemonPushMessageSchema.safeParse(pushMessage)
- expect(parsed.success).toBe(true)
- if (parsed.success && parsed.data.type === "daemon.tasks") {
- expect(parsed.data.tasks.length).toBeGreaterThanOrEqual(1)
- const pushed = parsed.data.tasks.find((t) => t.id === taskId)
- expect(pushed).toBeDefined()
- }
-
- // Poll should also return the task
- const pollResult = await client.poll(seed.machineToken, daemonId, 1)
- expect(pollResult.tasks.length).toBeGreaterThanOrEqual(1)
-
- // Cleanup
- sqlRun(`DELETE FROM agent_task_queue WHERE id = ?`, taskId)
- sqlRun(`DELETE FROM conversation WHERE id = ?`, conversationId)
- })
-
- afterAll(() => {
- try {
- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = ?`, daemonId)
- sqlRun(`DELETE FROM machine WHERE daemon_id = ?`, daemonId)
- } catch { /* ignore */ }
- })
-})
diff --git a/vitest.config.ts b/vitest.config.ts
index 52958055a..3ebff90be 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -7,7 +7,6 @@ export default defineConfig({
"src/web",
"src/web/auth/vitest.config.ts",
"src/web/auth/vitest.runtime.config.mts",
- "src/cli",
"src/daemon",
"src/daemon/agent-driver",
"src/email-worker",
@@ -41,7 +40,6 @@ export default defineConfig({
"**/react-dom-setup.ts",
"**/*.d.ts",
"**/test-runtime/**",
- "src/cli/src/index.ts",
"src/web/scripts/**",
"src/web/readme-capture/**",
"src/web/src/**/*.tsx",