diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b7b90907..f1c47885 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,21 +22,27 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version-file: .nvmrc cache: npm + cache-dependency-path: | + package-lock.json + web/package-lock.json + + - name: Verify runtime contract + run: npm run check:runtime - name: Install dependencies - run: npm ci + run: npm ci --no-audit --no-fund - - name: Install WebUI dependencies - run: npm --prefix web ci + - name: Format check + run: npm run format:check - - name: Verify runtime contract - run: npm run check:runtime + - name: Install WebUI dependencies + run: npm --prefix web ci --no-audit --no-fund - name: Build SDK workspace run: npm run build -w packages/sdk @@ -56,9 +62,6 @@ jobs: - name: WebUI lint and tests run: npm --prefix web run lint && npm --prefix web test - - name: Format check - run: npm run format:check - - name: Dead code check run: npm run knip @@ -79,10 +82,10 @@ jobs: matrix: node-version: ["22.23.4", "24.22.1", "26.12.1"] steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: ${{ matrix.node-version }} cache: npm @@ -91,18 +94,30 @@ jobs: web/package-lock.json - name: Install dependencies - run: npm ci + run: npm ci --no-audit --no-fund - name: Install WebUI dependencies - run: cd web && npm ci + run: npm --prefix web ci --no-audit --no-fund + + - name: Read build runtime + id: runtime + run: | + build_version=$(node -p "require('node:fs').readFileSync('.nvmrc', 'utf8').trim()") + echo "version=$build_version" >> "$GITHUB_OUTPUT" - name: Build run: npm run build - name: Test with coverage + if: matrix.node-version == steps.runtime.outputs.version run: npm run test:coverage + - name: Test + if: matrix.node-version != steps.runtime.outputs.version + run: npm test + - name: Enforce SDK coverage + if: matrix.node-version == steps.runtime.outputs.version run: npm run test:sdk:coverage - name: CLI smoke test @@ -113,23 +128,26 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: docker/setup-buildx-action@v4 + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4 - - uses: docker/build-push-action@v7 + - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7 with: context: . push: false + cache-from: type=gha,scope=teleton-image-linux-amd64 + cache-to: ${{ github.event_name == 'push' && 'type=gha,mode=max,scope=teleton-image-linux-amd64,ignore-error=true' || '' }} # ---- Telegram notification (one summary per push, pushes only) ---- notify: needs: [checks, test, docker] - if: always() && github.event_name == 'push' + if: always() && !cancelled() && github.event_name == 'push' + continue-on-error: true runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: fetch-depth: 0 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bac42357..1ace5f5b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,9 +15,9 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 25 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version-file: .nvmrc cache: npm @@ -36,8 +36,8 @@ jobs: test "$GITHUB_REF_NAME" = "v$VERSION" grep -Fq "## [$VERSION]" CHANGELOG.md - - run: npm ci - - run: cd web && npm ci + - run: npm ci --no-audit --no-fund + - run: npm --prefix web ci --no-audit --no-fund - run: npm run build - run: node scripts/check-sdk-package.mjs - run: npm run typecheck @@ -54,14 +54,15 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: docker/setup-buildx-action@v4 + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4 - - uses: docker/build-push-action@v7 + - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7 with: context: . push: false + cache-from: type=gha,scope=teleton-image-linux-amd64 # ---- Publish to npm ---- publish-npm: @@ -72,9 +73,9 @@ jobs: contents: read id-token: write # npm provenance steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version-file: .nvmrc registry-url: https://registry.npmjs.org @@ -95,9 +96,9 @@ jobs: echo "publish=false" >> "$GITHUB_OUTPUT" fi - - run: npm ci + - run: npm ci --no-audit --no-fund if: steps.check.outputs.publish == 'true' - - run: cd web && npm ci + - run: npm --prefix web ci --no-audit --no-fund if: steps.check.outputs.publish == 'true' - run: npm publish --provenance --access public @@ -114,9 +115,9 @@ jobs: contents: read id-token: write # npm provenance steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version-file: .nvmrc registry-url: https://registry.npmjs.org @@ -136,7 +137,7 @@ jobs: - name: Install dependencies if: steps.check.outputs.publish == 'true' - run: npm ci + run: npm ci --no-audit --no-fund - name: Build and publish SDK if: steps.check.outputs.publish == 'true' @@ -153,13 +154,13 @@ jobs: contents: read packages: write # push to ghcr.io steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - name: Set up Buildx - uses: docker/setup-buildx-action@v4 + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4 - name: Log in to GitHub Container Registry - uses: docker/login-action@v4 + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4 with: registry: ghcr.io username: ${{ github.actor }} @@ -187,11 +188,13 @@ jobs: - name: Build and push Docker image if: steps.image.outputs.exists == 'false' - uses: docker/build-push-action@v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7 with: context: . push: true - cache-from: type=registry,ref=ghcr.io/${{ steps.meta.outputs.repo }}:latest + cache-from: | + type=gha,scope=teleton-image-linux-amd64 + type=registry,ref=ghcr.io/${{ steps.meta.outputs.repo }}:latest cache-to: type=inline tags: | ghcr.io/${{ steps.meta.outputs.repo }}:${{ steps.meta.outputs.version }} @@ -205,7 +208,7 @@ jobs: permissions: contents: write # create the GitHub release steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: fetch-depth: 0 @@ -240,7 +243,7 @@ jobs: - name: Create GitHub Release if: steps.check.outputs.exists == 'false' - uses: softprops/action-gh-release@v3 + uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 with: generate_release_notes: true body: | diff --git a/.github/workflows/telegram-notify.yml b/.github/workflows/telegram-notify.yml index bd16d894..ed02ad1a 100644 --- a/.github/workflows/telegram-notify.yml +++ b/.github/workflows/telegram-notify.yml @@ -16,7 +16,7 @@ jobs: && github.event.workflow_run.conclusion == 'success' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: fetch-depth: 0 @@ -35,7 +35,7 @@ jobs: - name: Send release to Telegram if: steps.ver.outputs.found == 'true' - uses: appleboy/telegram-action@v1.0.1 + uses: appleboy/telegram-action@221e6b684967abe813051ee4a37dd61770a83ad3 # v1.0.1 with: to: ${{ secrets.TELEGRAM_CHAT_ID }} token: ${{ secrets.TELEGRAM_BOT_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 130d62b5..b35d391c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.11.8] - 2026-11-03 + +### Added + +- Add GPT-6.1 Terra to OpenAI, Codex, and OpenRouter, plus Terra Pro on OpenRouter. +- Add Kimi K3.1 Pro and Highspeed on Kimi Coding, Kimi K3.1 Pro on OpenRouter, Mistral Large 4.0.8, DeepSeek V4.1 Flash 1017 and GLM-5.3 Flash on Mistral, and MiniMax M3.1 Flash on HuggingFace. +- Identify Teleton Agent in provider requests. + +### Changed + +- Update pi-ai to 1.5.0 and GramJS to Telegram Layer 232. +- Remove deprecated Mistral Large 3 and unavailable HuggingFace Step 3.7 Flash from model pickers while preserving configured model resolution. +- Cache Docker build layers, calculate coverage on the primary Node.js runtime while retaining tests across all supported runtimes, and separate backend and SDK coverage reports. +- Pin GitHub Actions to immutable revisions and keep Telegram notification failures from failing CI. +- Use pi-ai 1.5 JSON Schema argument validation while retaining TypeBox tool schemas. + +### Fixed + +- Stop aborted or truncated model responses before executing their tool calls, and prevent context-overflow recovery from replaying actions already performed in the turn. +- Preserve conversation history when summarization fails, reject truncated summaries, and retain all text blocks and tool details during compaction. +- Correct usage estimates after compaction and bound output and thinking budgets to model, context, and API limits. +- Map supported reasoning levels and budgets for MiniMax, Grok, Google, and Mistral models. +- Respect configured endpoints for utility calls and retain the utility model compatibility export. +- Filter thinking from streamed drafts without losing public text that follows it. +- Recognize retryable provider errors and respect provider retry delays. + +### Security + +- Update vulnerable runtime dependencies, including follow-redirects to 1.16.2. + ## [0.11.7] - 2026-10-23 ### Added diff --git a/Dockerfile b/Dockerfile index 01c984d3..9b077fec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,6 +12,7 @@ RUN apt-get update && apt-get install -y \ # Copy dependency files and SDK workspace (needed for workspace resolution) COPY package.json package-lock.json ./ +COPY patches/ patches/ COPY packages/sdk/package.json packages/sdk/ # Install all deps (including devDependencies for build + SDK workspace) @@ -37,6 +38,7 @@ WORKDIR /app # Copy package files and install production deps only. # Keep a toolchain available during installation for native addons, then purge it. COPY package.json package-lock.json ./ +COPY patches/ patches/ RUN apt-get update \ && apt-get install -y --no-install-recommends python3 make g++ \ && npm pkg delete scripts.prepare \ diff --git a/package-lock.json b/package-lock.json index 81b8ee9f..7628ffc6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,19 +1,25 @@ { "name": "teleton", - "version": "0.11.7", + "version": "0.11.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "teleton", - "version": "0.11.7", + "version": "0.11.8", + "bundleDependencies": [ + "@ton/core", + "@ton/crypto", + "@ton/ton" + ], + "hasInstallScript": true, "license": "MIT", "workspaces": [ "packages/*" ], "dependencies": { "@dedust/sdk": "^0.8.7", - "@earendil-works/pi-ai": "^1.4.0", + "@earendil-works/pi-ai": "^1.5.0", "@hono/node-server": "^2.1.5", "@huggingface/transformers": "^4.3.1", "@inquirer/prompts": "^8.7.4", @@ -33,12 +39,13 @@ "hono-rate-limiter": "^0.5.4", "mediainfo.js": "^0.3.8", "ora": "^9.4.1", + "patch-package": "8.0.1", "pino": "^10.4.0", "pino-pretty": "^13.2.0", "qrcode-terminal": "^0.12.0", "selfsigned": "^5.5.0", "sqlite-vec": "^0.1.7", - "telegram": "github:TONresistor/gramjs#5ad36509a9561cd26ab6acce9511dcdd6ce4c535", + "telegram": "github:TONresistor/gramjs#1564a010b264f381045aaf7f9d44740d08bc6d1f", "yaml": "^2.9.1", "zod": "^4.6.7" }, @@ -570,21 +577,21 @@ } }, "node_modules/@earendil-works/pi-ai": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.4.0.tgz", - "integrity": "sha512-hQM/C4+1w8rHYACzDDf+0vQMnEnpzIop1tptIERVgR3ZeT/hHSzBNG8PaWPgxWQjqSeKCyBZSyp8uTT6eKK1pQ==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.5.0.tgz", + "integrity": "sha512-VeWxNqTHSqRCf8AcY/6kvNwh+neRL6MPxZPePVztIQy6qqK9MR/YoCSN/ZgDnIyCD3pqEXgRyQbzk4KV4uvjbg==", "license": "MIT", "dependencies": { "@anthropic-ai/sdk": "0.129.0", "@aws-sdk/client-bedrock-runtime": "3.1127.0", - "@earendil-works/pi-telemetry": "1.4.0", + "@earendil-works/pi-schema": "1.5.0", + "@earendil-works/pi-telemetry": "1.5.0", "@google/genai": "2.21.0", "@smithy/node-http-handler": "4.12.1", "http-proxy-agent": "9.1.0", "https-proxy-agent": "9.1.0", "openai": "7.19.0", - "partial-json": "0.1.7", - "typebox": "1.3.27" + "partial-json": "0.1.7" }, "bin": { "pi-ai": "dist/cli.js" @@ -616,10 +623,19 @@ "node": ">= 20" } }, + "node_modules/@earendil-works/pi-schema": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-schema/-/pi-schema-1.5.0.tgz", + "integrity": "sha512-RW0MbT2tR65OY6xMsgB/yVBb7m/RTNwA+9hurSN1vVXfHZRVmVnXbruBPrx/PzbrQnW5yLVlMRWxErGDQtF1Hg==", + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, "node_modules/@earendil-works/pi-telemetry": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.4.0.tgz", - "integrity": "sha512-MLIfowwUYIY65jSjMX82paZOrX/NTvLk6D08h+3Jq42a99RzUOewzuCR0zOlPul3D6UBfddat76VT6LvsHEs1w==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.5.0.tgz", + "integrity": "sha512-VW3tcVdnNfl/Vk8wHPTzZdKkxcsCOM12ppiO4DXnd9wMxUCmOfLt/wvUnWeKWbTVlVSRg0uqKtnnhE2UCsG2Bw==", "license": "MIT", "engines": { "node": ">=22.19.0" @@ -3914,6 +3930,7 @@ "version": "0.63.1", "resolved": "https://registry.npmjs.org/@ton/core/-/core-0.63.1.tgz", "integrity": "sha512-hDWMjlKzc18W2E4OeV3hUP8ohRJNHPD4Wd1+AQJj8zshZyCRT0usrvnExgbNUTo/vntDqCGMzgYWbXxyaA+L4g==", + "inBundle": true, "license": "MIT", "peerDependencies": { "@ton/crypto": ">=3.2.0" @@ -3923,6 +3940,7 @@ "version": "3.3.0", "resolved": "https://registry.npmjs.org/@ton/crypto/-/crypto-3.3.0.tgz", "integrity": "sha512-/A6CYGgA/H36OZ9BbTaGerKtzWp50rg67ZCH2oIjV1NcrBaCK9Z343M+CxedvM7Haf3f/Ee9EhxyeTp0GKMUpA==", + "inBundle": true, "license": "MIT", "dependencies": { "@ton/crypto-primitives": "2.1.0", @@ -3934,6 +3952,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/@ton/crypto-primitives/-/crypto-primitives-2.1.0.tgz", "integrity": "sha512-PQesoyPgqyI6vzYtCXw4/ZzevePc4VGcJtFwf08v10OevVJHVfW238KBdpj1kEDQkxWLeuNHEpTECNFKnP6tow==", + "inBundle": true, "license": "MIT", "dependencies": { "jssha": "3.2.0" @@ -3943,6 +3962,7 @@ "version": "16.3.0", "resolved": "https://registry.npmjs.org/@ton/ton/-/ton-16.3.0.tgz", "integrity": "sha512-iafYCLYVD2+ZrqbnJA7CvuZ13hUVQSmmOAxx8Ozo2pgl0HHjj004hdoHzrdE0XCHdj7AOZB3zcZaHBVJxQOh9Q==", + "inBundle": true, "license": "MIT", "dependencies": { "axios": "^1.15.0", @@ -3954,15 +3974,6 @@ "@ton/crypto": ">=3.2.0" } }, - "node_modules/@ton/ton/node_modules/zod": { - "version": "3.25.76", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", - "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, "node_modules/@tonconnect/isomorphic-eventsource": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/@tonconnect/isomorphic-eventsource/-/isomorphic-eventsource-0.0.2.tgz", @@ -4595,6 +4606,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@yarnpkg/lockfile": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", + "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", + "license": "BSD-2-Clause" + }, "node_modules/abort-controller": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", @@ -4803,6 +4820,7 @@ "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "inBundle": true, "license": "MIT" }, "node_modules/atomic-sleep": { @@ -4842,6 +4860,7 @@ "version": "1.20.0", "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", "integrity": "sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==", + "inBundle": true, "license": "MIT", "dependencies": { "follow-redirects": "^1.16.0", @@ -4854,6 +4873,7 @@ "version": "6.0.2", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "inBundle": true, "license": "MIT", "dependencies": { "debug": "4" @@ -4866,6 +4886,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "inBundle": true, "license": "MIT", "dependencies": { "agent-base": "6", @@ -4948,18 +4969,18 @@ } }, "node_modules/body-parser": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", - "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", - "content-type": "^2.0.0", + "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", - "iconv-lite": "^0.7.2", + "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", - "qs": "^6.15.2", + "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" }, @@ -4972,9 +4993,9 @@ } }, "node_modules/body-parser/node_modules/content-type": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", - "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "license": "MIT", "engines": { "node": ">=18" @@ -5003,6 +5024,18 @@ "node": "20 || >=22" } }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/buffer": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", @@ -5105,10 +5138,29 @@ "qified": "^0.10.1" } }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/call-bind-apply-helpers": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "inBundle": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -5209,6 +5261,21 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/ci-info": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", + "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/cli-cursor": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", @@ -5331,7 +5398,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, "license": "MIT", "dependencies": { "color-name": "~1.1.4" @@ -5344,7 +5410,6 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, "license": "MIT" }, "node_modules/colorette": { @@ -5357,6 +5422,7 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "inBundle": true, "license": "MIT", "dependencies": { "delayed-stream": "~1.0.0" @@ -5495,6 +5561,7 @@ "version": "2.2.3", "resolved": "https://registry.npmjs.org/dataloader/-/dataloader-2.2.3.tgz", "integrity": "sha512-y2krtASINtPFS1rSDjacrFgn1dcUuoREVabwlOGOe4SdxenREqwjwjElAdwvbGM7kgZz9a3KVicWR7vcz8rnzA==", + "inBundle": true, "license": "MIT" }, "node_modules/dateformat": { @@ -5510,6 +5577,7 @@ "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "inBundle": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -5649,6 +5717,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "inBundle": true, "license": "MIT", "engines": { "node": ">=0.4.0" @@ -5918,6 +5987,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "inBundle": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.1", @@ -6006,6 +6076,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "inBundle": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -6015,6 +6086,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "inBundle": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -6031,6 +6103,7 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "inBundle": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0" @@ -6043,6 +6116,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "inBundle": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -6653,9 +6727,9 @@ } }, "node_modules/fast-uri": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", - "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "funding": [ { "type": "github", @@ -6811,6 +6885,18 @@ "node": ">=18" } }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/finalhandler": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", @@ -6849,6 +6935,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/find-yarn-workspace-root": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/find-yarn-workspace-root/-/find-yarn-workspace-root-2.0.0.tgz", + "integrity": "sha512-1IMnbjt4KzsQfnhnzNd8wUEgXZ44IzZaZmnLYx7D5FZlaHt2gW20Cri8Q+E/t5tIj4+epTBub+2Zxu/vNILzqQ==", + "license": "Apache-2.0", + "dependencies": { + "micromatch": "^4.0.2" + } + }, "node_modules/fix-dts-default-cjs-exports": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz", @@ -6887,15 +6982,16 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.16.1", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz", - "integrity": "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==", + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.2.tgz", + "integrity": "sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==", "funding": [ { "type": "individual", "url": "https://github.com/sponsors/RubenVerborgh" } ], + "inBundle": true, "license": "MIT", "engines": { "node": ">=4.0" @@ -6910,6 +7006,7 @@ "version": "4.0.6", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "inBundle": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", @@ -6926,6 +7023,7 @@ "version": "1.52.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "inBundle": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -6935,6 +7033,7 @@ "version": "2.1.35", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "inBundle": true, "license": "MIT", "dependencies": { "mime-db": "1.52.0" @@ -6997,6 +7096,20 @@ "dev": true, "license": "MIT" }, + "node_modules/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -7016,6 +7129,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "inBundle": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -7106,6 +7220,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "inBundle": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -7137,6 +7252,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "inBundle": true, "license": "MIT", "dependencies": { "dunder-proto": "^1.0.1", @@ -7249,6 +7365,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "inBundle": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -7288,7 +7405,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -7310,6 +7426,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "inBundle": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -7322,6 +7439,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "inBundle": true, "license": "MIT", "dependencies": { "has-symbols": "^1.0.3" @@ -7350,6 +7468,7 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "inBundle": true, "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -7496,9 +7615,9 @@ } }, "node_modules/iconv-lite": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", - "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -7564,9 +7683,9 @@ "license": "ISC" }, "node_modules/ip-address": { - "version": "10.7.1", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.1.tgz", - "integrity": "sha512-4OUAqU9Z1i3vCnS05hzGiFnEMDpQ+62pAD/MVQOp83fYyNC8GleCqaS0QikQBmcWCrKFiUs/B8ztRRiYOAXuCA==", + "version": "10.7.4", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz", + "integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==", "license": "MIT", "engines": { "node": ">= 12" @@ -7597,6 +7716,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -7632,6 +7766,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, "node_modules/is-obj": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", @@ -7683,6 +7826,24 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -7912,6 +8073,25 @@ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", "license": "BSD-2-Clause" }, + "node_modules/json-stable-stringify": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.3.0.tgz", + "integrity": "sha512-qtYiSSFlwot9XHtF9bD9c7rwKjr+RecWT//ZnPvSmEjpV5mmPOCN4j8UjY5hbjNkOwZ/jQv3J6R1/pL7RwgMsg==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "isarray": "^2.0.5", + "jsonify": "^0.0.1", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", @@ -7932,6 +8112,27 @@ "node": ">=6" } }, + "node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonify": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.1.tgz", + "integrity": "sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg==", + "license": "Public Domain", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/jsonparse": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", @@ -7963,6 +8164,7 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/jssha/-/jssha-3.2.0.tgz", "integrity": "sha512-QuruyBENDWdN4tZwJbQq7/eAK85FqrI4oDbXjy5IBhYD+2pTJyBUWZe8ctWaCkrV0gy6AaelgOZZBMeswEa/6Q==", + "inBundle": true, "license": "BSD-3-Clause", "engines": { "node": "*" @@ -7999,6 +8201,15 @@ "@keyv/serialize": "^1.1.1" } }, + "node_modules/klaw-sync": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/klaw-sync/-/klaw-sync-6.0.0.tgz", + "integrity": "sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.11" + } + }, "node_modules/knip": { "version": "6.42.1", "resolved": "https://registry.npmjs.org/knip/-/knip-6.42.1.tgz", @@ -8693,6 +8904,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "inBundle": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -8813,6 +9025,31 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/mime": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", @@ -8959,6 +9196,7 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "inBundle": true, "license": "MIT" }, "node_modules/mute-stream": { @@ -9260,6 +9498,22 @@ "integrity": "sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==", "license": "MIT" }, + "node_modules/open": { + "version": "7.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-7.4.2.tgz", + "integrity": "sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==", + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0", + "is-wsl": "^2.1.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/openai": { "version": "7.19.0", "resolved": "https://registry.npmjs.org/openai/-/openai-7.19.0.tgz", @@ -9516,6 +9770,66 @@ "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==", "license": "MIT" }, + "node_modules/patch-package": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/patch-package/-/patch-package-8.0.1.tgz", + "integrity": "sha512-VsKRIA8f5uqHQ7NGhwIna6Bx6D9s/1iXlA1hthBVBEbkq+t4kXD0HHt+rJhf/Z+Ci0F/HCB2hvn0qLdLG+Qxlw==", + "license": "MIT", + "dependencies": { + "@yarnpkg/lockfile": "^1.1.0", + "chalk": "^4.1.2", + "ci-info": "^3.7.0", + "cross-spawn": "^7.0.3", + "find-yarn-workspace-root": "^2.0.0", + "fs-extra": "^10.0.0", + "json-stable-stringify": "^1.0.2", + "klaw-sync": "^6.0.0", + "minimist": "^1.2.6", + "open": "^7.4.2", + "semver": "^7.5.3", + "slash": "^2.0.0", + "tmp": "^0.2.4", + "yaml": "^2.2.2" + }, + "bin": { + "patch-package": "index.js" + }, + "engines": { + "node": ">=14", + "npm": ">5" + } + }, + "node_modules/patch-package/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/patch-package/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, "node_modules/path-browserify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", @@ -9996,6 +10310,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "inBundle": true, "license": "MIT", "engines": { "node": ">=10" @@ -10068,9 +10383,9 @@ } }, "node_modules/qs": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", - "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "version": "6.16.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz", + "integrity": "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", @@ -10649,6 +10964,23 @@ "url": "https://opencollective.com/express" } }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -10809,6 +11141,15 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/slide": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz", @@ -11248,7 +11589,6 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, "license": "MIT", "dependencies": { "has-flag": "^4.0.0" @@ -11285,9 +11625,9 @@ } }, "node_modules/telegram": { - "version": "2.34.0", - "resolved": "git+ssh://git@github.com/TONresistor/gramjs.git#5ad36509a9561cd26ab6acce9511dcdd6ce4c535", - "integrity": "sha512-PJvV7hjw+Bfa4LNOH0VssPn/tdOrjxZIB6D6iUP+XkNr1YYlw/rbDTgpRuljnczeNcUDfmzMSeOIkJSKoBEElA==", + "version": "2.35.0", + "resolved": "git+ssh://git@github.com/TONresistor/gramjs.git#1564a010b264f381045aaf7f9d44740d08bc6d1f", + "integrity": "sha512-PnZlFDm2Ze4GNUSHYd2r3IThEFC6NFYh5h96szYrhX2LB0XTzI4qW79VB0KD41GAodawpL84KjGA1OSOxTsrbQ==", "license": "MIT", "dependencies": { "@cryptography/aes": "^0.1.1", @@ -11436,6 +11776,27 @@ "node": ">=14.0.0" } }, + "node_modules/tmp": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, "node_modules/toidentifier": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", @@ -11684,6 +12045,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "inBundle": true, "license": "Unlicense" }, "node_modules/tweetnacl-util": { @@ -11756,12 +12118,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/typebox": { - "version": "1.3.27", - "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.3.27.tgz", - "integrity": "sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==", - "license": "MIT" - }, "node_modules/typedarray-to-buffer": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", @@ -11808,6 +12164,15 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "license": "MIT" }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", @@ -12338,6 +12703,7 @@ "version": "4.6.7", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "inBundle": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/package.json b/package.json index b1a0ab47..681ca1ca 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "teleton", - "version": "0.11.7", + "version": "0.11.8", "workspaces": [ "packages/*" ], @@ -32,6 +32,7 @@ "files": [ "dist/", "bin/", + "patches/", "src/templates/" ], "scripts": { @@ -64,11 +65,12 @@ "audit:web": "npm --prefix web audit --audit-level=high", "check:runtime": "node scripts/check-runtime-contract.mjs", "prepublishOnly": "npm run build", + "postinstall": "patch-package --error-on-fail", "prepare": "husky" }, "dependencies": { "@dedust/sdk": "^0.8.7", - "@earendil-works/pi-ai": "^1.4.0", + "@earendil-works/pi-ai": "^1.5.0", "@hono/node-server": "^2.1.5", "@huggingface/transformers": "^4.3.1", "@inquirer/prompts": "^8.7.4", @@ -88,23 +90,33 @@ "hono-rate-limiter": "^0.5.4", "mediainfo.js": "^0.3.8", "ora": "^9.4.1", + "patch-package": "8.0.1", "pino": "^10.4.0", "pino-pretty": "^13.2.0", "qrcode-terminal": "^0.12.0", "selfsigned": "^5.5.0", "sqlite-vec": "^0.1.7", - "telegram": "github:TONresistor/gramjs#5ad36509a9561cd26ab6acce9511dcdd6ce4c535", + "telegram": "github:TONresistor/gramjs#1564a010b264f381045aaf7f9d44740d08bc6d1f", "yaml": "^2.9.1", "zod": "^4.6.7" }, + "bundleDependencies": [ + "@ton/core", + "@ton/crypto", + "@ton/ton" + ], "overrides": { "@aws-sdk/xml-builder": "3.972.19", + "@ton/ton": { + "zod": "$zod" + }, "fast-xml-parser": "5.7.1", "axios": "1.20.0", + "body-parser": "2.4.0", "brace-expansion": "5.0.12", "esbuild": "0.28.1", - "fast-uri": "3.1.8", - "ip-address": "10.7.1", + "fast-uri": "3.1.9", + "ip-address": "10.7.4", "nanoid": "3.3.18", "sharp": "0.35.5" }, diff --git a/patches/@ton+ton+16.3.0.patch b/patches/@ton+ton+16.3.0.patch new file mode 100644 index 00000000..c1093198 --- /dev/null +++ b/patches/@ton+ton+16.3.0.patch @@ -0,0 +1,26 @@ +diff --git a/node_modules/@ton/ton/dist/client/api/HttpApi.js b/node_modules/@ton/ton/dist/client/api/HttpApi.js +index 1efb591..dca96d9 100644 +--- a/node_modules/@ton/ton/dist/client/api/HttpApi.js ++++ b/node_modules/@ton/ton/dist/client/api/HttpApi.js +@@ -103,7 +103,7 @@ const transaction = zod_1.z.object({ + fee: zod_1.z.string(), + storage_fee: zod_1.z.string(), + other_fee: zod_1.z.string(), +- in_msg: zod_1.z.union([zod_1.z.undefined(), message]), ++ in_msg: zod_1.z.union([zod_1.z.undefined(), message]).optional(), + out_msgs: zod_1.z.array(message), + }); + const getTransactions = zod_1.z.array(transaction); +diff --git a/node_modules/@ton/ton/package.json b/node_modules/@ton/ton/package.json +index b9078fc..7a80eb5 100644 +--- a/node_modules/@ton/ton/package.json ++++ b/node_modules/@ton/ton/package.json +@@ -41,7 +41,7 @@ + "dependencies": { + "axios": "^1.15.0", + "dataloader": "^2.0.0", +- "zod": "^3.21.4" ++ "zod": "^4.6.7" + }, + "peerDependencies": { + "@ton/core": ">=0.63.0 <1.0.0", diff --git a/src/agent/__tests__/client-openrouter-cost.test.ts b/src/agent/__tests__/client-openrouter-cost.test.ts index 16fda2bf..cadd2fde 100644 --- a/src/agent/__tests__/client-openrouter-cost.test.ts +++ b/src/agent/__tests__/client-openrouter-cost.test.ts @@ -11,12 +11,12 @@ vi.mock("../../session/transcript.js", () => ({ readTranscript: () => [], })); -function response(cost: unknown = 0.02) { +function response(cost: unknown = 0.02, fragments = ["Hello"]) { const chunks = [ - { + ...fragments.map((content) => ({ id: "gen-test", - choices: [{ index: 0, delta: { role: "assistant", content: "Hello" }, finish_reason: null }], - }, + choices: [{ index: 0, delta: { role: "assistant", content }, finish_reason: null }], + })), { id: "gen-test", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], @@ -144,4 +144,47 @@ describe("OpenRouter reported cost", () => { expect(text).toBe("Hello"); expect((await stream.result).message.usage.cost.total).toBe(0.02); }); + it("captures error Retry-After through the billing fetch and clears it on success", async () => { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce( + new Response(JSON.stringify({ error: { message: "Too many requests" } }), { + status: 429, + headers: { "Content-Type": "application/json", "Retry-After": "30" }, + }) + ) + .mockImplementationOnce(async () => response()) + ); + const limited = await chatWithContext(config, { context }); + expect(limited.message.stopReason).toBe("error"); + expect(limited.retryAfterMs).toBeGreaterThan(29000); + const success = await chatWithContext(config, { context }); + expect(success.retryAfterMs).toBeUndefined(); + expect(success.message.usage.cost.total).toBe(0.02); + }); + it.each([false, true])( + "preserves public suffixes through the real adapter and transcript (stream: %s)", + async (streaming) => { + vi.stubGlobal( + "fetch", + vi.fn(async () => response(0.02, ["public secret operator <"])) + ); + const options = { context, sessionId: "real-suffix", persistTranscript: true }; + let result; + if (streaming) { + const stream = streamWithContext(config, options); + let draft = ""; + for await (const delta of stream.textStream) draft += delta; + expect(draft).toBe("public operator <"); + result = await stream.result; + } else result = await chatWithContext(config, options); + expect(result.text).toBe("public operator <"); + expect(mocks.appendToTranscript).toHaveBeenCalledWith( + "real-suffix", + expect.objectContaining({ content: [{ type: "text", text: "public operator <" }] }) + ); + } + ); }); diff --git a/src/agent/__tests__/client-telegram-tools.test.ts b/src/agent/__tests__/client-telegram-tools.test.ts index 551f9f44..cef75f10 100644 --- a/src/agent/__tests__/client-telegram-tools.test.ts +++ b/src/agent/__tests__/client-telegram-tools.test.ts @@ -3,6 +3,7 @@ import type { Tool } from "@earendil-works/pi-ai/compat"; import { AgentConfigSchema } from "../../config/schema.js"; const mocks = vi.hoisted(() => ({ + appendToTranscript: vi.fn(), complete: vi.fn(), stream: vi.fn(), })); @@ -18,6 +19,11 @@ vi.mock("@earendil-works/pi-ai/compat", async () => { }; }); +vi.mock("../../session/transcript.js", () => ({ + appendToTranscript: mocks.appendToTranscript, + readTranscript: () => [], +})); + import { chatWithContext, streamWithContext } from "../client.js"; const config = AgentConfigSchema.parse({ @@ -93,6 +99,54 @@ describe("Telegram tool preparation", () => { expectPreparedTools(mocks.complete.mock.calls[0][1]); }); + it.each([false, true])("returns every text block in order (streaming: %s)", async (streaming) => { + const message = assistantMessage(); + message.content = [ + { type: "text", text: "First block" }, + { type: "text", text: "Second block" }, + ]; + mocks.complete.mockResolvedValue(message); + mocks.stream.mockReturnValue({ + async *[Symbol.asyncIterator]() {}, + result: vi.fn().mockResolvedValue(message), + }); + const options = { context: { messages: [] } }; + const response = streaming + ? await streamWithContext(config, options).result + : await chatWithContext(config, options); + + expect(response.text).toBe("First block\nSecond block"); + }); + + it("does not persist tool calls from a truncated response", async () => { + mocks.appendToTranscript.mockClear(); + mocks.complete.mockResolvedValue({ + ...assistantMessage(), + stopReason: "length", + content: [{ type: "toolCall", id: "partial", name: "send", arguments: {} }], + }); + await chatWithContext(config, { + context: { messages: [] }, + sessionId: "test", + persistTranscript: true, + }); + expect(mocks.appendToTranscript).not.toHaveBeenCalled(); + }); + + it.each([false, true])( + "returns local overflow without a provider request (stream: %s)", + async (streaming) => { + const options = { context: { systemPrompt: "system ".repeat(150000), messages: [] } }; + const response = streaming + ? await streamWithContext(config, options).result + : await chatWithContext(config, options); + expect(response.message.stopReason).toBe("error"); + expect(response.message.errorMessage).toContain("Context length exceeded"); + expect(mocks.complete).not.toHaveBeenCalled(); + expect(mocks.stream).not.toHaveBeenCalled(); + } + ); + it("applies the same guard to streaming calls", async () => { mocks.stream.mockReturnValue({ async *[Symbol.asyncIterator]() {}, @@ -108,3 +162,102 @@ describe("Telegram tool preparation", () => { expectPreparedTools(mocks.stream.mock.calls[0][1]); }); }); + +describe("streamed think filtering", () => { + it.each([ + [["public secret after"], "public after"], + [["oneAtwoB"], "AB"], + [["beforenever closed"], "before"], + [["before", "secret"], ""], + ])("filters split and interrupted tags: %j", async (chunks, expected) => { + const message = assistantMessage(); + message.content = [{ type: "text", text: chunks.join("") }]; + mocks.stream.mockReturnValue({ + async *[Symbol.asyncIterator]() { + for (const delta of chunks) yield { type: "text_delta", delta }; + }, + result: async () => message, + }); + const streamed = streamWithContext(config, { context: { messages: [] } }); + let text = ""; + for await (const delta of streamed.textStream) text += delta; + expect(text).toBe(expected); + expect((await streamed.result).text).toBe(expected); + }); + + it("keeps filter state isolated between requests", async () => { + const { createThinkFilter } = await import("../../utils/pi-message.js"); + const first = createThinkFilter(); + const second = createThinkFilter(); + expect(first.push("secret")).toBe(""); + expect(second.push("public")).toBe("public"); + expect(first.push("first")).toBe("first"); + }); + it.each([false, true])( + "preserves ordered public suffixes in the final reply and transcript (stream: %s)", + async (streaming) => { + const message = assistantMessage(); + message.content = [ + { type: "text", text: "operator <" }, + { type: "text", text: "literal message, + }); + const options = { context: { messages: [] }, sessionId: "suffix", persistTranscript: true }; + let draft = ""; + let result; + if (streaming) { + const stream = streamWithContext(config, options); + for await (const delta of stream.textStream) draft += delta; + result = await stream.result; + expect(draft).toBe("operator <\nliteral secret message, + }); + const stream = streamWithContext(config, { context: { messages: [] } }); + let draft = ""; + for await (const delta of stream.textStream) draft += delta; + expect(draft).toBe("public "); + expect((await stream.result).text).toBe("public "); + expect(mocks.appendToTranscript).not.toHaveBeenCalled(); + } + ); +}); diff --git a/src/agent/__tests__/harness-integration.test.ts b/src/agent/__tests__/harness-integration.test.ts index fd8f0ae5..c9d395ea 100644 --- a/src/agent/__tests__/harness-integration.test.ts +++ b/src/agent/__tests__/harness-integration.test.ts @@ -31,6 +31,11 @@ import { } from "../../session/transcript.js"; import { CompactionManager } from "../../memory/compaction.js"; import { prepareTurn } from "../../agent/turn-preparation.js"; +import { + summarizeViaClaude, + summarizeInChunks, + summarizeWithFallback, +} from "../../memory/ai-summarization.js"; const usage = { input: 1, @@ -104,6 +109,178 @@ afterEach(async () => { }); describe("Minimal harness regressions", () => { + it("uses the fallback immediately when the primary quota is exhausted", async () => { + const cfg = config(); + cfg.agent.fallbacks = [{ provider: "openai", model: "gpt-4.1", api_key: "fallback-key" }]; + mocks.complete + .mockResolvedValueOnce({ ...answer("", "error"), errorMessage: "429 insufficient_quota" }) + .mockResolvedValueOnce(answer("Fallback answer")); + + const result = await new AgentRuntime(cfg, "test").processMessage({ + chatId: "quota-test", + userMessage: "answer this", + }); + + expect(result.content).toBe("Fallback answer"); + expect(mocks.complete).toHaveBeenCalledTimes(2); + expect(mocks.complete.mock.calls[1][0]).toMatchObject({ provider: "openai", id: "gpt-4.1" }); + }); + + it.each([false, true])( + "rejects an aborted response before tools run (tools: %s)", + async (withTools) => { + const { runtime, effect } = runtimeWithAction(); + const interrupted = answer( + "Partial answer", + "aborted", + withTools ? toolAnswer().content : undefined + ); + mocks.complete.mockResolvedValue(interrupted); + + await expect( + runtime.processMessage({ + chatId: "abort-test", + userMessage: "perform action", + toolContext: { bridge: bridge(), db: mocks.db, config: config(), senderId: 1 }, + }) + ).rejects.toThrow("Model response was aborted"); + + expect(effect).not.toHaveBeenCalled(); + expect(mocks.complete).toHaveBeenCalledOnce(); + await flushAllTranscripts(); + const session = getOrCreateSession("abort-test"); + const rows = readFileSync(getTranscriptPath(session.sessionId), "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + expect(rows.filter((row) => row.role === "assistant")).toEqual([]); + expect( + mocks.db.prepare("SELECT status FROM agent_turn_traces WHERE chat_id = ?").get("abort-test") + ).toEqual({ status: "error" }); + } + ); + + it("clears an aborted streaming draft without publishing partial text", async () => { + const interrupted = answer("Partial answer", "aborted"); + mocks.stream.mockReturnValue({ + result: async () => interrupted, + async *[Symbol.asyncIterator]() { + yield { type: "text_delta", delta: "Partial answer" }; + }, + }); + const b = bridge(); + await expect( + new AgentRuntime(config(), "test").processMessage({ + chatId: "1", + userMessage: "write response", + streamToChat: { chatId: "1", bridge: b, mode: "replace" }, + }) + ).rejects.toThrow("Model response was aborted"); + + expect(b.bot.api.sendMessage).not.toHaveBeenCalled(); + expect(b.activeDraftIds.size).toBe(0); + expect(b.bot.api.sendMessageDraft).toHaveBeenLastCalledWith(1, expect.any(Number), " "); + expect(mocks.complete).not.toHaveBeenCalled(); + }); + + it.each(["error", "aborted", "empty"])( + "rejects a failed summary response: %s", + async (failure) => { + mocks.complete.mockResolvedValue({ + ...answer( + failure === "empty" ? " " : "Partial summary", + failure === "empty" ? "stop" : failure + ), + errorMessage: failure === "error" ? "401 Invalid API key" : undefined, + }); + await expect( + summarizeViaClaude({ + messages: [{ role: "user", content: "Preserve this fact", timestamp: 1 }], + apiKey: "simulated", + }) + ).rejects.toThrow(); + } + ); + + it.each(["error", "aborted", "empty"])("rejects a failed summary merge: %s", async (failure) => { + mocks.complete + .mockResolvedValueOnce(answer("First summary")) + .mockResolvedValueOnce(answer("Second summary")) + .mockResolvedValueOnce( + answer(failure === "empty" ? " " : "Partial merge", failure === "empty" ? "stop" : failure) + ); + await expect( + summarizeInChunks({ + messages: [ + { role: "user", content: "First fact", timestamp: 1 }, + { role: "user", content: "Second fact", timestamp: 2 }, + ], + apiKey: "simulated", + maxChunkTokens: 1, + }) + ).rejects.toThrow(); + expect(mocks.complete).toHaveBeenCalledTimes(3); + }); + + it("does not return a placeholder when every summary attempt fails", async () => { + mocks.complete.mockResolvedValue({ + ...answer("", "error"), + errorMessage: "401 Invalid API key", + }); + await expect( + summarizeWithFallback({ + messages: [{ role: "user", content: "Keep this fact", timestamp: 1 }], + apiKey: "simulated", + contextWindow: 128000, + }) + ).rejects.toThrow("AI summarization failed for all fallback attempts"); + }); + + it("preserves the current transcript and inbound message when actual summary calls fail", async () => { + const session = getOrCreateSession("failed-compaction"); + appendToTranscript(session.sessionId, { role: "user", content: "KEEP_OLD_FACT", timestamp: 1 }); + appendToTranscript(session.sessionId, answer("Previous answer") as any); + mocks.complete.mockResolvedValue({ + ...answer("", "error"), + errorMessage: "401 Invalid API key", + }); + const result = await prepareTurn( + { chatId: "failed-compaction", userMessage: "CURRENT_ONCE" }, + Date.now(), + { + config: config(), + soul: "test", + compactionManager: new CompactionManager({ + enabled: true, + maxMessages: 3, + keepRecentMessages: 1, + memoryFlushEnabled: false, + }), + contextBuilder: null, + embedder: null, + toolRegistry: null, + getMemoryStats: () => ({ totalMessages: 0, totalChats: 0, knowledgeChunks: 0 }), + } + ); + expect(result.kind).toBe("ready"); + if (result.kind !== "ready") return; + expect(result.turn.session.sessionId).toBe(session.sessionId); + expect( + result.turn.context.messages.some( + (msg) => msg.role === "user" && msg.content === "KEEP_OLD_FACT" + ) + ).toBe(true); + await flushAllTranscripts(); + const rows = readFileSync(getTranscriptPath(session.sessionId), "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + expect( + rows.filter((row) => typeof row.content === "string" && row.content.includes("CURRENT_ONCE")) + ).toHaveLength(1); + expect(rows.some((row) => row.content === "KEEP_OLD_FACT")).toBe(true); + }); + it("C03: distinct Telegram triggers of one running task execute only once", async () => { const { runtime, effect } = runtimeWithAction(); let release!: () => void; diff --git a/src/agent/__tests__/model-request.test.ts b/src/agent/__tests__/model-request.test.ts index 1a8167a6..f4422061 100644 --- a/src/agent/__tests__/model-request.test.ts +++ b/src/agent/__tests__/model-request.test.ts @@ -3,7 +3,171 @@ import { complete } from "@earendil-works/pi-ai/compat"; import { AgentConfigSchema } from "../../config/schema.js"; import { prepareModelRequest } from "../model-request.js"; +vi.mock("../../providers/codex-credentials.js", () => ({ + getCodexApiKey: (fallback: string) => fallback, + refreshCodexApiKey: async () => null, +})); + describe("model request preparation", () => { + it.each([ + ["openai", "gpt-6.1-terra", "none", "none", "reasoning.effort"], + ["codex", "gpt-6.1-terra", "max", "max", "reasoning.effort"], + ["openrouter", "openai/gpt-6.1-terra", "low", "low", "reasoning.effort"], + ["openrouter", "openai/gpt-6.1-terra-pro", "max", "max", "reasoning.effort"], + ["openrouter", "moonshotai/kimi-k3.1-pro", "max", "max", "reasoning.effort"], + ["moonshot", "k3.1-pro", "none", "low", "reasoning_effort"], + ["moonshot", "k3.1-pro-highspeed", "max", "max", "reasoning_effort"], + ["mistral", "mistral-large-4-0-8", "low", "low", "reasoningEffort"], + ["mistral", "deepseek-v4-1-flash-1017", "none", "none", "reasoningEffort"], + ["mistral", "zai-glm-5-3-flash", "max", "max", "reasoningEffort"], + ["anthropic", "claude-sonnet-5-5", "low", "low", "messages.1.output_config.effort"], + ["anthropic", "claude-sonnet-5-5", "max", "max", "messages.1.output_config.effort"], + ["anthropic", "claude-sonnet-5-5", "none", "low", "messages.1.output_config.effort"], + ["anthropic", "claude-opus-4-6", "minimal", "low", "output_config.effort"], + ["openrouter", "anthropic/claude-sonnet-5.5", "max", "max", "messages.1.output_config.effort"], + ["openrouter", "openai/gpt-6-sol", "low", "low", "reasoning.effort"], + ["openrouter", "openai/gpt-6-sol", "max", "max", "reasoning.effort"], + ["openrouter", "openai/gpt-6-sol", "none", "none", "reasoning.effort"], + ["moonshot", "k3", "none", "low", "reasoning_effort"], + ["moonshot", "k3", "medium", "high", "reasoning_effort"], + ["moonshot", "k3", "max", "max", "reasoning_effort"], + ["groq", "openai/gpt-oss-120b", "low", "low", "reasoning_effort"], + ["groq", "openai/gpt-oss-120b", "max", "high", "reasoning_effort"], + ] as const)( + "sends supported effort for %s/%s (%s → %s)", + async (provider, model, reasoning_effort, expected, path) => { + const request = prepareModelRequest( + AgentConfigSchema.parse({ + provider, + model, + api_key: + provider === "codex" + ? `test.${Buffer.from(JSON.stringify({ "https://api.openai.com/auth": { chatgpt_account_id: "fixture" } })).toString("base64url")}.test` + : "test-key", + reasoning_effort, + }), + { context: { messages: [{ role: "user", content: "test", timestamp: 1 }] } } + ); + let payload: unknown; + const fetch = vi.fn().mockRejectedValue(new Error("Network disabled in test")); + await complete(request.model, request.context, { + ...request.options, + fetch, + onPayload(value) { + payload = value; + throw new Error("Stop before network request"); + }, + }); + + expect(fetch).not.toHaveBeenCalled(); + expect(payload).toHaveProperty(path, expected); + } + ); + + it("allows optional adaptive thinking to be disabled", async () => { + const request = prepareModelRequest( + AgentConfigSchema.parse({ + provider: "anthropic", + model: "claude-opus-4-6", + api_key: "test-key", + reasoning_effort: "none", + }), + { context: { messages: [{ role: "user", content: "test", timestamp: 1 }] } } + ); + let payload: unknown; + await complete(request.model, request.context, { + ...request.options, + onPayload(value) { + payload = value; + throw new Error("Stop before network request"); + }, + }); + expect(payload).toHaveProperty("thinking.type", "disabled"); + expect(payload).not.toHaveProperty("output_config.effort"); + }); + it.each([ + ["none", "low"], + ["minimal", "low"], + ["low", "low"], + ["medium", "medium"], + ["high", "high"], + ["xhigh", "xhigh"], + ["max", "max"], + ] as const)("sends MiniMax M3.1 Flash effort %s as %s", async (reasoning_effort, expected) => { + const request = prepareModelRequest( + AgentConfigSchema.parse({ + provider: "minimax", + model: "MiniMax-M3.1-Flash", + api_key: "test-key", + reasoning_effort, + }), + { context: { messages: [{ role: "user", content: "test", timestamp: 1 }] } } + ); + let payload: unknown; + await complete(request.model, request.context, { + ...request.options, + onPayload(value) { + payload = value; + throw new Error("Stop before network request"); + }, + }); + + expect(payload).toHaveProperty("thinking.type", "adaptive"); + expect(payload).toHaveProperty("output_config.effort", expected); + expect(payload).not.toHaveProperty("reasoning_effort"); + expect(payload).not.toHaveProperty("temperature"); + }); + + it.each(["grok-4.3", "grok-4.5"])("sends supported reasoning efforts for %s", async (model) => { + for (const [reasoning_effort, expected] of [ + ["none", "low"], + ["medium", "medium"], + ["xhigh", "xhigh"], + ["max", "xhigh"], + ] as const) { + const request = prepareModelRequest( + AgentConfigSchema.parse({ provider: "xai", model, api_key: "test-key", reasoning_effort }), + { context: { messages: [{ role: "user", content: "test", timestamp: 1 }] } } + ); + let payload: unknown; + await complete(request.model, request.context, { + ...request.options, + onPayload(value) { + payload = value; + throw new Error("Stop before network request"); + }, + }); + + expect(payload).toHaveProperty( + "reasoning.effort", + reasoning_effort === "none" && model === "grok-4.3" ? "none" : expected + ); + } + }); + + it("identifies teleton-agent in OpenRouter request headers", async () => { + const request = prepareModelRequest( + AgentConfigSchema.parse({ + provider: "openrouter", + model: "example/brand-new", + api_key: "test-key", + }), + { context: { messages: [{ role: "user", content: "test", timestamp: 1 }] } } + ); + const fetch = vi + .fn() + .mockResolvedValue( + new Response("data: [DONE]\n\n", { headers: { "Content-Type": "text/event-stream" } }) + ); + await complete(request.model, request.context, { ...request.options, fetch }); + + expect(fetch).toHaveBeenCalledOnce(); + const headers = new Headers(fetch.mock.calls[0]?.[1]?.headers); + expect(headers.get("User-Agent")).toBe("teleton-agent"); + expect(headers.get("X-OpenRouter-Title")).toBe("teleton-agent"); + expect(headers.get("HTTP-Referer")).toBe("https://github.com/TONresistor/teleton-agent"); + }); + it("forwards custom OpenRouter IDs and tools without optional sampling parameters", async () => { const request = prepareModelRequest( AgentConfigSchema.parse({ @@ -130,7 +294,8 @@ describe("model request preparation", () => { expect(request.options).toMatchObject({ apiKey: "sk-test-key", maxTokens: 8192, - temperature: 0.4, + thinkingEnabled: true, + thinkingBudgetTokens: 2048, sessionId: "session-1", cacheRetention: "long", }); @@ -378,3 +543,296 @@ describe("model request preparation", () => { } ); }); + +describe("output budget", () => { + it("caps output at the model ceiling", () => { + const request = prepareModelRequest( + AgentConfigSchema.parse({ api_key: "test-key", max_tokens: 100000 }), + { context: { messages: [] } } + ); + expect(request.options.maxTokens).toBe(request.model.maxTokens); + }); + + it("counts the system and tool schemas without double-counting a measured prefix", async () => { + const { getOutputTokenBudget } = await import("../../providers/model-resolver.js"); + const request = prepareModelRequest(AgentConfigSchema.parse({ api_key: "test-key" }), { + context: { messages: [] }, + }); + const model = { ...request.model, contextWindow: 10000, maxTokens: 10000 }; + expect( + getOutputTokenBudget(model, { systemPrompt: "s".repeat(3500), messages: [] }, 10000) + ).toBe(4904); + const measured = { + role: "assistant" as const, + content: [], + api: model.api, + provider: model.provider, + model: model.id, + stopReason: "stop" as const, + timestamp: 1, + usage: { + input: 2000, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 2000, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }; + expect( + getOutputTokenBudget(model, { systemPrompt: "s".repeat(3500), messages: [measured] }, 10000) + ).toBe(3904); + expect( + getOutputTokenBudget( + model, + { + messages: [measured], + tools: [{ name: "large", description: "x".repeat(35000), parameters: {} }], + }, + 10000 + ) + ).toBe(0); + }); +}); + +describe("budget and Google reasoning payloads", () => { + it.each(["none", "low", "high", "max"] as const)( + "uses Anthropic budget thinking for %s without increasing output", + async (reasoning_effort) => { + const request = prepareModelRequest( + AgentConfigSchema.parse({ api_key: "test-key", reasoning_effort }), + { context: { messages: [{ role: "user", content: "test", timestamp: 1 }] } } + ); + let payload: unknown; + await complete(request.model, request.context, { + ...request.options, + onPayload(value) { + payload = value; + throw new Error("capture"); + }, + }); + expect(payload).toHaveProperty("max_tokens", 4096); + expect(payload).toHaveProperty( + "thinking.type", + reasoning_effort === "none" ? "disabled" : "enabled" + ); + if (reasoning_effort !== "none") { + expect(payload).toHaveProperty( + "thinking.budget_tokens", + reasoning_effort === "low" ? 2048 : 3072 + ); + expect(payload).not.toHaveProperty("temperature"); + } + } + ); + + it.each(["none", "low", "high", "max"] as const)( + "uses Google native thinking for %s", + async (reasoning_effort) => { + const request = prepareModelRequest( + AgentConfigSchema.parse({ + provider: "google", + model: "gemini-3.5-flash", + api_key: "test-key", + reasoning_effort, + }), + { context: { messages: [{ role: "user", content: "test", timestamp: 1 }] } } + ); + let payload: unknown; + await complete(request.model, request.context, { + ...request.options, + onPayload(value) { + payload = value; + throw new Error("capture"); + }, + }); + expect(payload).toHaveProperty("config.maxOutputTokens", 4096); + if (reasoning_effort === "none") expect(payload).toHaveProperty("config.thinkingConfig"); + else + expect(payload).toHaveProperty( + "config.thinkingConfig.thinkingLevel", + reasoning_effort === "low" ? "LOW" : "HIGH" + ); + } + ); + + it("disables optional budget thinking when the answer ceiling is too small", () => { + const request = prepareModelRequest( + AgentConfigSchema.parse({ api_key: "test-key", max_tokens: 1024, reasoning_effort: "high" }), + { context: { messages: [] } } + ); + expect(request.options).toMatchObject({ maxTokens: 1024, thinkingEnabled: false }); + }); +}); + +describe("effective Responses output minimum", () => { + it.each([1, 8])( + "rejects requested budget %s locally instead of reporting overflow", + async (max_tokens) => { + const { chatWithContext, streamWithContext } = await import("../client.js"); + const fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Network disabled")); + const config = AgentConfigSchema.parse({ + provider: "openai", + model: "gpt-6-sol", + api_key: "sk-test-only", + max_tokens, + }); + try { + await expect(chatWithContext(config, { context: { messages: [] } })).rejects.toThrow( + "at least 16 tokens" + ); + expect(() => streamWithContext(config, { context: { messages: [] } })).toThrow( + "at least 16 tokens" + ); + expect(fetch).not.toHaveBeenCalled(); + } finally { + fetch.mockRestore(); + } + } + ); + + it.each([16, 4096])( + "preserves requested budget %s in the real Responses payload", + async (max_tokens) => { + const request = prepareModelRequest( + AgentConfigSchema.parse({ + provider: "openai", + model: "gpt-6-sol", + api_key: "sk-test-only", + max_tokens, + }), + { context: { messages: [{ role: "user", content: "test", timestamp: 1 }] } } + ); + let payload: unknown; + await complete(request.model, request.context, { + ...request.options, + onPayload(value) { + payload = value; + throw new Error("Stop before network"); + }, + }); + expect(request.options.maxTokens).toBe(max_tokens); + expect(payload).toHaveProperty("max_output_tokens", max_tokens); + } + ); + + it.each([false, true])( + "reports real context exhaustion when available output falls below 16 (stream: %s)", + async (streaming) => { + const { chatWithContext, streamWithContext } = await import("../client.js"); + const { getProviderModel } = await import("../../providers/model-resolver.js"); + const config = AgentConfigSchema.parse({ + provider: "openai", + model: "gpt-6-sol", + api_key: "sk-test-only", + max_tokens: 4096, + }); + const model = getProviderModel("openai", config.model); + const tokens = model.contextWindow - 4096 - 8; + const context = { + messages: [ + { + role: "assistant" as const, + content: [], + api: model.api, + provider: model.provider, + model: model.id, + stopReason: "stop" as const, + timestamp: 1, + usage: { + input: tokens, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: tokens, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }, + ], + }; + const fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Network disabled")); + try { + expect(prepareModelRequest(config, { context }).options.maxTokens).toBe(0); + const response = streaming + ? await streamWithContext(config, { context }).result + : await chatWithContext(config, { context }); + expect(response.message.stopReason).toBe("error"); + expect(response.message.errorMessage).toContain("Context length exceeded"); + expect(fetch).not.toHaveBeenCalled(); + } finally { + fetch.mockRestore(); + } + } + ); + + it.each(["codex", "anthropic", "google", "groq"] as const)( + "does not impose the Responses minimum on %s's other transport", + async (provider) => { + const models = { + codex: "gpt-5.6-terra", + anthropic: "claude-haiku-4-5-20251001", + google: "gemini-3.5-flash", + groq: "openai/gpt-oss-20b", + }; + const key = + provider === "codex" + ? `header.${Buffer.from(JSON.stringify({ "https://api.openai.com/auth": { chatgpt_account_id: "test-account" } })).toString("base64")}.signature` + : "sk-test-only"; + const request = prepareModelRequest( + AgentConfigSchema.parse({ + provider, + model: models[provider], + api_key: key, + max_tokens: 1, + reasoning_effort: "none", + }), + { context: { messages: [{ role: "user", content: "test", timestamp: 1 }] } } + ); + let payload: unknown; + await complete(request.model, request.context, { + ...request.options, + onPayload(value) { + payload = value; + throw new Error("Stop before network"); + }, + }); + expect(request.options.maxTokens).toBe(1); + expect(payload).toBeDefined(); + if (provider === "codex") expect(payload).not.toHaveProperty("max_output_tokens"); + } + ); + + it("does not impose a minimum when the Responses adapter omits the output field", async () => { + const { getProviderModel, getOutputTokenBudget } = + await import("../../providers/model-resolver.js"); + const model = getProviderModel("openai", "gpt-6-sol"); + expect( + getOutputTokenBudget( + { ...model, compat: { ...model.compat, supportsMaxOutputTokens: false } }, + { messages: [] }, + 1, + "sk-test-only" + ) + ).toBe(1); + const request = prepareModelRequest( + AgentConfigSchema.parse({ + provider: "openai", + model: model.id, + api_key: "fake-sign-in-token", + max_tokens: 1, + }), + { context: { messages: [] } } + ); + let payload: unknown; + await complete(request.model, request.context, { + ...request.options, + onPayload(value) { + payload = value; + throw new Error("Stop before network"); + }, + }); + expect(request.options.maxTokens).toBe(1); + expect(payload).toBeDefined(); + expect(payload).not.toHaveProperty("max_output_tokens"); + }); +}); diff --git a/src/agent/__tests__/runtime-characterization.test.ts b/src/agent/__tests__/runtime-characterization.test.ts index dcaa0105..92cbf0aa 100644 --- a/src/agent/__tests__/runtime-characterization.test.ts +++ b/src/agent/__tests__/runtime-characterization.test.ts @@ -206,6 +206,7 @@ const toolContext = { describe("AgentRuntime characterization", () => { beforeEach(() => { vi.clearAllMocks(); + vi.mocked(registry.getToolCategory).mockReturnValue("data-bearing"); mocks.session.messageCount = 0; mocks.selectTools.mockResolvedValue(undefined); mocks.resolveProviderFallback.mockReturnValue(null); @@ -319,4 +320,127 @@ describe("AgentRuntime characterization", () => { expect.any(String) ); }); + + it.each([ + ["data-bearing", true], + ["action", false], + ] as const)("allows overflow recovery after %s (attempted: %s)", async (category, attempted) => { + vi.mocked(registry.getToolCategory).mockReturnValue(category); + const toolCall = { type: "toolCall" as const, id: "read-1", name: "lookup", arguments: {} }; + mocks.runModelIteration + .mockResolvedValueOnce(iteration(assistantMessage([toolCall], "toolUse"))) + .mockResolvedValueOnce( + iteration(assistantMessage([], "error", undefined, "maximum context length exceeded")) + ) + .mockResolvedValueOnce( + iteration(assistantMessage([{ type: "text", text: "recovered" }]), "recovered") + ); + mocks.executeToolBatch.mockResolvedValue({ toolPlans: [], execResults: [] }); + mocks.recordToolResults.mockImplementation(async (_r, _p, _e, sink) => { + sink.totalToolCalls.push({ + name: "lookup", + input: {}, + attempted, + result: { success: attempted }, + }); + return []; + }); + mocks.recoverLlmError.mockResolvedValueOnce({ + session: mocks.session, + context: { messages: [] }, + }); + const result = await new AgentRuntime(config(), "", registry).processMessage({ + chatId: "chat-1", + userMessage: "lookup", + toolContext, + }); + expect(result.content).toBe("recovered"); + expect(mocks.recoverLlmError).toHaveBeenCalledOnce(); + }); + + it.each([true, false])( + "stops overflow after an action (success: %s) without resetting", + async (success) => { + vi.mocked(registry.getToolCategory).mockReturnValue("action"); + const toolCall = { type: "toolCall" as const, id: "action-1", name: "send", arguments: {} }; + mocks.runModelIteration + .mockResolvedValueOnce(iteration(assistantMessage([toolCall], "toolUse"))) + .mockResolvedValueOnce( + iteration(assistantMessage([], "error", undefined, "maximum context length exceeded")) + ); + mocks.executeToolBatch.mockResolvedValue({ toolPlans: [], execResults: [] }); + mocks.recordToolResults.mockImplementation(async (_r, _p, _e, sink) => { + sink.totalToolCalls.push({ name: "send", input: {}, attempted: true, result: { success } }); + return [ + { + role: "toolResult", + toolCallId: "action-1", + toolName: "send", + content: [{ type: "text", text: "recorded receipt or uncertain outcome" }], + isError: !success, + timestamp: 3, + }, + ]; + }); + const result = await new AgentRuntime(config(), "", registry).processMessage({ + chatId: "chat-1", + userMessage: "send", + toolContext, + }); + expect(result.content).toContain("will not retry"); + expect(result.toolCalls).toHaveLength(1); + expect(mocks.runModelIteration).toHaveBeenCalledTimes(2); + expect(mocks.recoverLlmError).not.toHaveBeenCalled(); + expect(mocks.traceFinish).toHaveBeenCalledWith( + expect.objectContaining({ status: "error", stopReason: "context_overflow_after_action" }) + ); + } + ); + + it("still recovers overflow before any action", async () => { + mocks.runModelIteration + .mockResolvedValueOnce( + iteration(assistantMessage([], "error", undefined, "maximum context length exceeded")) + ) + .mockResolvedValueOnce( + iteration(assistantMessage([{ type: "text", text: "recovered" }]), "recovered") + ); + mocks.recoverLlmError.mockResolvedValueOnce({ + session: mocks.session, + context: { messages: [] }, + }); + const result = await new AgentRuntime(config()).processMessage({ + chatId: "chat-1", + userMessage: "read", + }); + expect(result.content).toBe("recovered"); + expect(mocks.recoverLlmError).toHaveBeenCalledOnce(); + }); + it.each([false, true])( + "does not execute or complete a truncated response (tools: %s)", + async (withTool) => { + const message = assistantMessage( + [ + { type: "text", text: "partial answer" }, + ...(withTool + ? [{ type: "toolCall" as const, name: "send", id: "partial", arguments: {} }] + : []), + ], + "length" + ); + mocks.runModelIteration.mockResolvedValueOnce(iteration(message, "partial answer")); + const result = await new AgentRuntime(config(), "", registry).processMessage({ + chatId: "chat-1", + userMessage: "send", + toolContext, + }); + expect(result.content).toContain("partial answer"); + expect(result.content).toContain("truncated"); + expect(mocks.executeToolBatch).not.toHaveBeenCalled(); + expect(mocks.runModelIteration).toHaveBeenCalledOnce(); + expect(mocks.traceFinish).toHaveBeenCalledWith( + expect.objectContaining({ status: "budget_exhausted", stopReason: "output_budget" }) + ); + } + ); }); diff --git a/src/agent/__tests__/runtime-utils.test.ts b/src/agent/__tests__/runtime-utils.test.ts index 330df58c..06f8a47c 100644 --- a/src/agent/__tests__/runtime-utils.test.ts +++ b/src/agent/__tests__/runtime-utils.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { classifyLlmError, + parseRetryAfterMs, isContextOverflowError, isTrivialMessage, } from "../../agent/runtime-utils.js"; @@ -117,6 +118,24 @@ describe("isTrivialMessage", () => { }); describe("LLM error classification", () => { + it.each([ + "upstream_stream_read_error", + "upstream_request_failed", + "stream disconnected before completion: stream closed before response.completed", + "HTTP/2 stream failed", + "fetch failed", + "504 Gateway Timeout", + "529 overloaded", + ])("classifies transient transport failures: %s", (message) => { + expect(classifyLlmError(message).kind).toBe("server_error"); + }); + + it.each(["Invalid request req_011CU503xyz", "Invalid request req_500_abc", "5242880 bytes"])( + "does not treat request IDs or byte counts as status codes: %s", + (message) => { + expect(classifyLlmError(message).kind).toBe("unknown"); + } + ); it.each([ "429 rate limit", "usage limit reached", @@ -133,3 +152,54 @@ describe("LLM error classification", () => { } ); }); + +describe("HTTP retry metadata and cancellation", () => { + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + it.each([ + [{ "retry-after": "30" }, 30000], + [{ "retry-after": "Mon, 26 Oct 2026 12:00:30 GMT" }, 30000], + [{ "retry-after-ms": "1250", "retry-after": "30" }, 1250], + [{ "retry-after": "invalid" }, undefined], + ])("captures retry headers %j without retaining previous attempts", async (headers, expected) => { + const { createRetryAfterTracker } = await import("../../utils/fetch.js"); + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-10-26T12:00:00Z")); + const fetcher = vi + .fn() + .mockResolvedValueOnce(new Response("limited", { status: 429, headers })) + .mockResolvedValueOnce(new Response("ok")); + const tracker = createRetryAfterTracker(fetcher); + await tracker.fetch("https://test.invalid"); + expect(tracker.retryAfterMs()).toBe(expected); + await tracker.fetch("https://test.invalid"); + expect(tracker.retryAfterMs()).toBeUndefined(); + }); + it("waits the full delay, refuses insufficient budget, and aborts promptly", async () => { + const { waitForRetry } = await import("../../utils/fetch.js"); + vi.useFakeTimers(); + let done = false; + const pending = waitForRetry(30000, undefined, Date.now() + 60000).then(() => { + done = true; + }); + await vi.advanceTimersByTimeAsync(29999); + expect(done).toBe(false); + await vi.advanceTimersByTimeAsync(1); + await pending; + expect(done).toBe(true); + await expect(waitForRetry(30000, undefined, Date.now() + 10000)).rejects.toThrow( + "remaining turn budget" + ); + const controller = new AbortController(); + const cancelled = waitForRetry(30000, controller.signal).catch((error: unknown) => error); + controller.abort(new Error("cancelled")); + expect(await cancelled).toMatchObject({ message: "cancelled" }); + expect(vi.getTimerCount()).toBe(0); + }); +}); + +it("uses structured Google retry info when its adapter cannot expose HTTP headers", () => { + expect(parseRetryAfterMs('{"details":[{"retryDelay":"30.5s"}]}')).toBe(30500); +}); diff --git a/src/agent/client.ts b/src/agent/client.ts index e0aba872..26483442 100644 --- a/src/agent/client.ts +++ b/src/agent/client.ts @@ -4,6 +4,7 @@ import { type Context, type AssistantMessage, type Message, + type TextContent, } from "@earendil-works/pi-ai/compat"; import type { AgentConfig } from "../config/schema.js"; import { appendToTranscript, readTranscript } from "../session/transcript.js"; @@ -17,6 +18,7 @@ import { type PreparedModelRequest, } from "./model-request.js"; import { isSilentReply } from "../constants/tokens.js"; +import { createThinkFilter, extractText } from "../utils/pi-message.js"; // Model resolution + provider model registration live in the neutral providers/ // layer so non-agent consumers (e.g. memory) can resolve models without importing @@ -51,10 +53,9 @@ export interface ChatResponse { message: AssistantMessage; text: string; context: Context; + retryAfterMs?: number; } -const THINK_RE = /[\s\S]*?<\/think>/g; - /** * Shared post-processing for both complete() and stream() responses: strip * blocks (Mistral, local models, etc.), persist the transcript, extract the @@ -65,19 +66,29 @@ function finalizeResponse( context: Context, options: ChatOptions ): ChatResponse { + const filter = createThinkFilter(); + let lastText: TextContent | undefined; for (const block of response.content) { - if (block.type === "text" && block.text.includes("")) { - block.text = block.text.replace(THINK_RE, "").trim(); + if (block.type === "text") { + if (lastText) lastText.text += filter.flushPublic(); + block.text = filter.push(block.text); + lastText = block; } } + const suffix = filter.end(response.stopReason === "stop" || response.stopReason === "toolUse"); + if (lastText) lastText.text += suffix; - const textContent = response.content.find((block) => block.type === "text"); - const text = textContent?.type === "text" ? textContent.text : ""; + const text = extractText(response); if ( options.persistTranscript && options.sessionId && response.stopReason !== "error" && + response.stopReason !== "aborted" && + !( + response.stopReason === "length" && + response.content.some((block) => block.type === "toolCall") + ) && !isSilentReply(text) ) { appendToTranscript(options.sessionId, response); @@ -108,15 +119,42 @@ async function retryAfterCredentialRefresh( return complete(request.model, request.context, request.options); } +function contextOverflowResponse(request: PreparedModelRequest): AssistantMessage { + return { + role: "assistant", + content: [], + api: request.model.api, + provider: request.model.provider, + model: request.model.id, + timestamp: Date.now(), + stopReason: "error", + errorMessage: "Context length exceeded: no safe output budget remains", + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }; +} + export async function chatWithContext( config: AgentConfig, options: ChatOptions ): Promise { const request = prepareModelRequest(config, options); - const initialResponse = await complete(request.model, request.context, request.options); + const initialResponse = + request.options.maxTokens === 0 + ? contextOverflowResponse(request) + : await complete(request.model, request.context, request.options); const response = await retryAfterCredentialRefresh(request, initialResponse); request.finalizeUsage?.(response); - return finalizeResponse(response, request.context, options); + return { + ...finalizeResponse(response, request.context, options), + retryAfterMs: request.retryAfterMs?.(), + }; } export interface StreamResult { @@ -126,19 +164,38 @@ export interface StreamResult { export function streamWithContext(config: AgentConfig, options: ChatOptions): StreamResult { const request = prepareModelRequest(config, options); + if (request.options.maxTokens === 0) { + return { + textStream: (async function* () {})(), + result: Promise.resolve( + finalizeResponse(contextOverflowResponse(request), request.context, options) + ), + }; + } const eventStream = stream(request.model, request.context, request.options); // Transform event stream into a simple text delta async iterable async function* textDeltas(): AsyncIterable { + const filter = createThinkFilter(); + let textBlocks = 0; for await (const event of eventStream) { + if (event.type === "text_start" && textBlocks++ > 0) { + const suffix = filter.flushPublic(); + if (suffix) yield suffix; + yield "\n"; + } if (event.type === "text_delta" && event.delta) { - yield event.delta; + const visible = filter.push(event.delta); + if (visible) yield visible; } // Stop yielding text when tool calls start — the response needs full processing if (event.type === "toolcall_start") { - return; + break; } } + const terminal = await eventStream.result(); + const suffix = filter.end(terminal.stopReason === "stop" || terminal.stopReason === "toolUse"); + if (suffix) yield suffix; } // Result promise: wait for the stream to complete and build ChatResponse @@ -146,7 +203,10 @@ export function streamWithContext(config: AgentConfig, options: ChatOptions): St const initialResponse = await eventStream.result(); const response = await retryAfterCredentialRefresh(request, initialResponse); request.finalizeUsage?.(response); - return finalizeResponse(response, request.context, options); + return { + ...finalizeResponse(response, request.context, options), + retryAfterMs: request.retryAfterMs?.(), + }; })(); return { textStream: textDeltas(), result: resultPromise }; diff --git a/src/agent/loop/executor.ts b/src/agent/loop/executor.ts index 57014d6e..11fc031b 100644 --- a/src/agent/loop/executor.ts +++ b/src/agent/loop/executor.ts @@ -8,7 +8,7 @@ import { isBotBridge } from "../../telegram/bridge-guards.js"; import { createLogger } from "../../utils/logger.js"; import { resolveModelTarget } from "../model-target.js"; import { resolveProviderFallback } from "../provider-fallback.js"; -import { addUsage } from "../runtime-utils.js"; +import { addUsage, isContextOverflowError } from "../runtime-utils.js"; import type { CompletedToolCall } from "../telegram-send-state.js"; import { enforceProviderToolLimit } from "../tool-selector.js"; import type { AgentTurnTraceRecorder } from "../turn-trace.js"; @@ -102,6 +102,51 @@ export async function executeAgentLoop( const iterUsage = response.message.usage; if (iterUsage) addUsage(accumulatedUsage, iterUsage); + if (assistantMsg.stopReason === "aborted") { + trace.progress(totalToolCalls, iteration, accumulatedUsage); + if (opts.streamToChat && isBotBridge(opts.streamToChat.bridge)) { + await opts.streamToChat.bridge.clearDraft(opts.streamToChat.chatId); + } + throw new Error(assistantMsg.errorMessage || "Model response was aborted before completion"); + } + + if (assistantMsg.stopReason === "length") { + stopReason = "output_budget"; + const partialText = [...accumulatedTexts, response.text].filter(Boolean).join("\n"); + forcedContent = + (partialText ? partialText + "\n\n" : "") + + "The model response was truncated at its output limit. " + + "No tools from this incomplete response were executed. Send a follow-up to continue."; + finalResponse = { + ...response, + message: { + ...assistantMsg, + content: assistantMsg.content.filter((block) => block.type === "text"), + }, + }; + wasStreamed = streamed; + break; + } + + const actionAlreadyAttempted = totalToolCalls.some( + (call) => + call.attempted !== false && deps.toolRegistry?.getToolCategory(call.name) !== "data-bearing" + ); + if ( + assistantMsg.stopReason === "error" && + isContextOverflowError(assistantMsg.errorMessage) && + actionAlreadyAttempted + ) { + stopReason = "context_overflow_after_action"; + forcedContent = + "I stopped because the context limit was reached after an action was attempted. " + + "Its recorded result is preserved; I will not retry the action automatically. " + + "Check the action's outcome before continuing."; + finalResponse = response; + wasStreamed = streamed; + break; + } + if (assistantMsg.stopReason === "error") { try { const recovered = await recoverLlmError( @@ -118,6 +163,9 @@ export async function executeAgentLoop( provider: activeProvider, processStartTime, userMsg, + retryAfterMs: response.retryAfterMs, + signal: providerSignal, + deadline: processStartTime + maxDurationMs, } ); session = recovered.session; @@ -125,11 +173,7 @@ export async function executeAgentLoop( iteration--; continue; } catch (error) { - const actionAlreadyAttempted = totalToolCalls.some( - (call) => - call.attempted !== false && - deps.toolRegistry?.getToolCategory(call.name) !== "data-bearing" - ); + if (providerSignal.aborted || Date.now() - processStartTime >= maxDurationMs) throw error; const previousProvider = activeProvider; const previousModel = activeAgentConfig.model; const fallback = resolveProviderFallback( @@ -254,7 +298,11 @@ export async function executeAgentLoop( } } - if (finalResponse && !context.messages.includes(finalResponse.message)) { + if ( + finalResponse && + finalResponse.message.stopReason !== "error" && + !context.messages.includes(finalResponse.message) + ) { context.messages.push(finalResponse.message); } diff --git a/src/agent/loop/llm-iteration.ts b/src/agent/loop/llm-iteration.ts index c4bf34ab..fe577b46 100644 --- a/src/agent/loop/llm-iteration.ts +++ b/src/agent/loop/llm-iteration.ts @@ -1,9 +1,11 @@ +import { waitForRetry } from "../../utils/fetch.js"; import type { AssistantMessage, Context, Tool as PiAiTool, UserMessage, } from "@earendil-works/pi-ai"; +import { isRetryableAssistantError } from "@earendil-works/pi-ai"; import type { Config } from "../../config/schema.js"; import type { SupportedProvider } from "../../config/providers.js"; import { @@ -125,6 +127,9 @@ export interface LlmErrorContext { provider: SupportedProvider; processStartTime: number; userMsg: UserMessage; + retryAfterMs?: number; + signal?: AbortSignal; + deadline?: number; } /** Classify an LLM failure and either recover its context or throw a terminal error. */ @@ -178,14 +183,18 @@ export async function recoverLlmError( } if (errorClass.kind === "rate_limit") { + if (!isRetryableAssistantError(assistantMsg)) { + throw new Error(`API quota or usage limit reached: ${errorMsg}`); + } retry.rateLimitRetries++; if (retry.rateLimitRetries <= RATE_LIMIT_MAX_RETRIES) { - const base = parseRetryAfterMs(errorMsg) ?? 1000 * 2 ** (retry.rateLimitRetries - 1); + const base = + ctx.retryAfterMs ?? parseRetryAfterMs(errorMsg) ?? 1000 * 2 ** (retry.rateLimitRetries - 1); const delay = base + Math.floor(Math.random() * 500); log.warn( `Rate limited, retrying in ${delay}ms (attempt ${retry.rateLimitRetries}/${RATE_LIMIT_MAX_RETRIES})...` ); - await new Promise((resolve) => setTimeout(resolve, delay)); + await waitForRetry(delay, ctx.signal, ctx.deadline); return { session, context }; } log.error(`Rate limited after ${RATE_LIMIT_MAX_RETRIES} retries: ${errorMsg}`); @@ -197,11 +206,13 @@ export async function recoverLlmError( if (errorClass.kind === "server_error") { retry.serverErrorRetries++; if (retry.serverErrorRetries <= SERVER_ERROR_MAX_RETRIES) { - const delay = 2000 * 2 ** (retry.serverErrorRetries - 1) + Math.floor(Math.random() * 500); + const delay = + (ctx.retryAfterMs ?? 2000 * 2 ** (retry.serverErrorRetries - 1)) + + Math.floor(Math.random() * 500); log.warn( `Server error, retrying in ${delay}ms (attempt ${retry.serverErrorRetries}/${SERVER_ERROR_MAX_RETRIES})...` ); - await new Promise((resolve) => setTimeout(resolve, delay)); + await waitForRetry(delay, ctx.signal, ctx.deadline); return { session, context }; } log.error(`Server error after ${SERVER_ERROR_MAX_RETRIES} retries: ${errorMsg}`); diff --git a/src/agent/model-request.ts b/src/agent/model-request.ts index 3983dd2d..4ddc7267 100644 --- a/src/agent/model-request.ts +++ b/src/agent/model-request.ts @@ -1,3 +1,10 @@ +import { createRetryAfterTracker } from "../utils/fetch.js"; +import { thinkingBudgetForLevel } from "@earendil-works/pi-ai/api/simple-options"; +import { + usesGoogleThinkingLevel, + resolveGoogleThinkingLevel, + toGoogleThinkingLevel, +} from "@earendil-works/pi-ai/api/google-shared"; import { clampThinkingLevel, hasApi, @@ -12,7 +19,11 @@ import type { AgentConfig } from "../config/schema.js"; import type { SupportedProvider } from "../config/providers.js"; import { getCodexApiKey } from "../providers/codex-credentials.js"; import { getGrokBuildApiKey } from "../providers/grok-build-credentials.js"; -import { getProviderModel, isCustomOpenRouterModel } from "../providers/model-resolver.js"; +import { + getProviderModel, + getOutputTokenBudget, + isCustomOpenRouterModel, +} from "../providers/model-resolver.js"; import { createOpenRouterUsageTracker } from "../providers/openrouter-usage.js"; import { TELEGRAM_SEND_TOOLS } from "../constants/tools.js"; import { sanitizeToolsForGemini } from "./schema-sanitizer.js"; @@ -34,6 +45,7 @@ export interface PreparedModelRequest { context: Context; options: ProviderStreamOptions; finalizeUsage?: (message: AssistantMessage) => void; + retryAfterMs?: () => number | undefined; } /** Resolve the effective API key for a provider (local/gocoon need no real key). */ @@ -86,14 +98,57 @@ function getCacheRetention(provider: SupportedProvider): "none" | "long" { function getReasoningOptions( provider: SupportedProvider, model: Model, - reasoningEffort: AgentConfig["reasoning_effort"] + reasoningEffort: AgentConfig["reasoning_effort"], + maxTokens: number ): Record { + if (!model.reasoning) return {}; const requiresZaiThinking = provider === "zai" && model.thinkingLevelMap?.off === null; - if ((provider !== "codex" && provider !== "openai" && !requiresZaiThinking) || !model.reasoning) { - return {}; - } + const adaptiveThinking = + hasApi(model, "anthropic-messages") && model.compat?.forceAdaptiveThinking === true; + const openAiThinking = + hasApi(model, "openai-responses") || + hasApi(model, "openai-codex-responses") || + (hasApi(model, "openai-completions") && + (model.compat?.supportsReasoningEffort !== false || requiresZaiThinking)); const level = clampThinkingLevel(model, reasoningEffort === "none" ? "off" : reasoningEffort); + if (hasApi(model, "anthropic-messages") && !adaptiveThinking) { + if (level === "off") return { thinkingEnabled: false }; + const budget = Math.min(thinkingBudgetForLevel(level), Math.max(0, maxTokens - 1024)); + if (budget < 1024) { + if (model.thinkingLevelMap?.off === null) + throw new Error("Output budget cannot fit required thinking and an answer"); + return { thinkingEnabled: false }; + } + return { thinkingEnabled: true, thinkingBudgetTokens: budget }; + } + if (hasApi(model, "google-generative-ai")) { + if (level === "off") return { thinking: { enabled: false } }; + if (usesGoogleThinkingLevel(model)) + return { + thinking: { + enabled: true, + level: toGoogleThinkingLevel(resolveGoogleThinkingLevel(model, level)), + }, + }; + const minimum = model.id.includes("flash-lite") ? 512 : 128; + const budget = Math.min(thinkingBudgetForLevel(level), Math.max(0, maxTokens - 1024)); + return { + thinking: { enabled: budget >= minimum, ...(budget >= minimum && { budgetTokens: budget }) }, + }; + } + if (hasApi(model, "mistral-conversations")) { + const mapped = model.thinkingLevelMap?.[level]; + return model.thinkingLevelMap + ? { reasoningEffort: mapped ?? (level === "off" ? "none" : level) } + : { ...(level !== "off" ? { promptMode: "reasoning" } : {}) }; + } + if (!adaptiveThinking && !openAiThinking) return {}; const mapped = model.thinkingLevelMap?.[level]; + if (adaptiveThinking) { + return level === "off" + ? { thinkingEnabled: false } + : { thinkingEnabled: true, effort: mapped ?? (level === "minimal" ? "low" : level) }; + } return { reasoningEffort: mapped ?? (level === "off" ? "none" : level) }; } @@ -149,29 +204,50 @@ export function prepareModelRequest( tools, }; const temperature = request.temperature ?? config.temperature; + const apiKey = getEffectiveApiKey(provider, config.api_key); + const maxTokens = getOutputTokenBudget( + model, + context, + request.maxTokens ?? config.max_tokens, + apiKey + ); + const reasoningOptions = getReasoningOptions(provider, model, config.reasoning_effort, maxTokens); const usageTracker = provider === "openrouter" && model.api === "openai-completions" ? createOpenRouterUsageTracker(isCustomOpenRouterModel(model)) : undefined; + const supportsCustomFetch = + !hasApi(model, "google-generative-ai") && !hasApi(model, "google-vertex"); + const retryTracker = supportsCustomFetch + ? createRetryAfterTracker(usageTracker?.fetch) + : undefined; return { provider, model, context, finalizeUsage: usageTracker?.apply, + retryAfterMs: retryTracker?.retryAfterMs, options: { - ...(usageTracker && { fetch: usageTracker.fetch }), - apiKey: getEffectiveApiKey(provider, config.api_key), - maxTokens: request.maxTokens ?? config.max_tokens, + identity: { + userAgent: { custom: "teleton-agent" }, + attribution: { + name: "teleton-agent", + url: "https://github.com/TONresistor/teleton-agent", + }, + }, + ...(retryTracker && { fetch: retryTracker.fetch }), + maxRetries: 0, + apiKey, + maxTokens, ...(!isCustomOpenRouterModel(model) && - modelSupportsTemperature(provider, model) && { temperature }), + modelSupportsTemperature(provider, model) && + reasoningOptions.thinkingEnabled !== true && { temperature }), sessionId: request.sessionId, cacheRetention: getCacheRetention(provider), signal: request.signal, timeoutMs: request.timeoutMs, - ...getReasoningOptions(provider, model, config.reasoning_effort), - ...(hasApi(model, "anthropic-messages") && - model.compat?.forceAdaptiveThinking === true && { thinkingEnabled: true }), + ...reasoningOptions, ...getProviderPayloadOptions(provider), } as ProviderStreamOptions, }; diff --git a/src/agent/runtime-utils.ts b/src/agent/runtime-utils.ts index b338c89c..80534e89 100644 --- a/src/agent/runtime-utils.ts +++ b/src/agent/runtime-utils.ts @@ -55,13 +55,14 @@ export function isRateLimitError(errorMessage?: string): boolean { export function isServerError(errorMessage?: string): boolean { if (!errorMessage) return false; return ( - errorMessage.includes("500") || - errorMessage.includes("502") || - errorMessage.includes("503") || - errorMessage.includes("529") || - errorMessage.includes("overloaded") || - errorMessage.includes("Internal server error") || - errorMessage.includes("api_error") || + /(? ({ - validateToolCall: vi.fn((tools, toolCall) => toolCall.arguments), -})); vi.mock("../module-permissions.js", () => ({ ModulePermissions: vi.fn(), @@ -422,19 +419,25 @@ describe("ToolRegistry", () => { }); it("denies executing a dm-only tool in a group", async () => { - const result = await registry.execute({ name: "dm_tool", input: { message: "x" } } as any, { - ...mockContext, - isGroup: true, - }); + const result = await registry.execute( + { name: "dm_tool", arguments: { message: "x" } } as any, + { + ...mockContext, + isGroup: true, + } + ); expect(result.success).toBe(false); expect(result.error).toMatch(/direct message/i); }); it("allows executing a dm-only tool in a DM", async () => { - const result = await registry.execute({ name: "dm_tool", input: { message: "x" } } as any, { - ...mockContext, - isGroup: false, - }); + const result = await registry.execute( + { name: "dm_tool", arguments: { message: "x" } } as any, + { + ...mockContext, + isGroup: false, + } + ); expect(result.success).toBe(true); }); }); @@ -501,6 +504,62 @@ describe("ToolRegistry", () => { // ---------- Tool execution ---------- describe("execute()", () => { + it.each([false, true])( + "validates real tool arguments (plain JSON Schema: %s)", + async (plain) => { + const schema = Type.Object({ + count: Type.Integer(), + label: Type.String(), + tags: Type.Array(Type.String()), + }); + const executor = createMockExecutor(); + registry.register( + { + name: "validate_args", + description: "Validate arguments", + parameters: plain ? JSON.parse(JSON.stringify(schema)) : schema, + }, + executor, + "open" + ); + const result = await registry.execute( + { + type: "toolCall", + id: "coerce", + name: "validate_args", + arguments: { count: "3.5", label: null, tags: "one" }, + }, + mockContext + ); + expect(result.success).toBe(true); + expect(executor).toHaveBeenCalledWith( + { count: 3, label: "null", tags: ["one"] }, + mockContext + ); + } + ); + + it.each>([ + { arguments: {} }, + { arguments: { message: {} } }, + { arguments: { message: "partial" }, argumentsError: "Invalid JSON" }, + ] satisfies Partial[])("never executes an invalid tool call: %j", async (input) => { + const executor = createMockExecutor(); + registry.register(createMockTool("validate_args"), executor, "open"); + const result = await registry.execute( + { + type: "toolCall", + id: "invalid", + name: "validate_args", + ...input, + }, + mockContext + ); + expect(result.success).toBe(false); + expect(result.error).toBeTruthy(); + expect(executor).not.toHaveBeenCalled(); + }); + it("executes directly when a legacy approval flag is present", async () => { const tool = createMockTool("financial_tool", "action"); const executor = createMockExecutor({ success: true, data: { tx: "abc" } }); diff --git a/src/agent/tools/telegram/memory/session-search.ts b/src/agent/tools/telegram/memory/session-search.ts index f53d2655..7715ada5 100644 --- a/src/agent/tools/telegram/memory/session-search.ts +++ b/src/agent/tools/telegram/memory/session-search.ts @@ -166,6 +166,7 @@ export const sessionSearchExecutor: ToolExecutor = async ( apiKey, provider, utilityModel: context.config?.agent?.utility_model, + baseUrl: context.config?.agent?.base_url, maxSummaryTokens: 300, customInstructions: "Summarize this conversation excerpt in 2-3 sentences. Focus on the topic and key points discussed.", diff --git a/src/agent/turn-preparation.ts b/src/agent/turn-preparation.ts index 681486b9..1cf0a47d 100644 --- a/src/agent/turn-preparation.ts +++ b/src/agent/turn-preparation.ts @@ -151,6 +151,7 @@ export async function prepareTurn( apiKey: getEffectiveApiKey(deps.config.agent.provider, deps.config.agent.api_key), provider: deps.config.agent.provider as SupportedProvider, utilityModel: deps.config.agent.utility_model, + baseUrl: deps.config.agent.base_url, }); log.info(`Memory saved before reset`); @@ -363,7 +364,8 @@ export async function prepareTurn( getEffectiveApiKey(deps.config.agent.provider, deps.config.agent.api_key), chatId, deps.config.agent.provider as SupportedProvider, - deps.config.agent.utility_model + deps.config.agent.utility_model, + deps.config.agent.base_url ); if (preemptiveCompaction) { log.info(`Preemptive compaction triggered, reloading session...`); diff --git a/src/config/model-catalog.ts b/src/config/model-catalog.ts index dbbc43c6..389f3a55 100644 --- a/src/config/model-catalog.ts +++ b/src/config/model-catalog.ts @@ -93,6 +93,11 @@ const MODEL_OPTIONS: Record = { name: "GPT-6.1 Sol", description: "Agentic coding, reasoning, vision, 272K effective context", }, + { + value: "gpt-6.1-terra", + name: "GPT-6.1 Terra", + description: "Balanced agentic reasoning and vision, 272K effective context", + }, { value: "gpt-6-sol", name: "GPT-6 Sol", @@ -167,6 +172,11 @@ const MODEL_OPTIONS: Record = { name: "GPT-5.6 Terra", description: "Balanced agentic coding model, 272K context", }, + { + value: "gpt-6.1-terra", + name: "GPT-6.1 Terra", + description: "Agentic reasoning and vision, 500K context", + }, { value: "gpt-6.1-sol", name: "GPT-6.1 Sol", @@ -298,6 +308,21 @@ const MODEL_OPTIONS: Record = { name: "GPT-6.1 Sol", description: "Agentic reasoning and vision via OpenRouter, 1M context", }, + { + value: "openai/gpt-6.1-terra", + name: "GPT-6.1 Terra", + description: "Reasoning and vision via OpenRouter", + }, + { + value: "openai/gpt-6.1-terra-pro", + name: "GPT-6.1 Terra Pro", + description: "Advanced reasoning and vision via OpenRouter", + }, + { + value: "moonshotai/kimi-k3.1-pro", + name: "Kimi K3.1 Pro", + description: "Agentic reasoning and vision via OpenRouter", + }, { value: "openai/gpt-6.1-sol-pro", name: "GPT-6.1 Sol Pro", @@ -531,6 +556,16 @@ const MODEL_OPTIONS: Record = { name: "Kimi for Coding", description: "Coding plan, reasoning, 1M context", }, + { + value: "k3.1-pro", + name: "Kimi K3.1 Pro", + description: "Agentic reasoning and vision, 1M context", + }, + { + value: "k3.1-pro-highspeed", + name: "Kimi K3.1 Pro Highspeed", + description: "Fast agentic reasoning and vision, 1M context", + }, { value: "k3", name: "Kimi K3", @@ -553,6 +588,21 @@ const MODEL_OPTIONS: Record = { name: "Mistral Large 4 (Preview)", description: "Agentic reasoning and vision, 1M context", }, + { + value: "mistral-large-4-0-8", + name: "Mistral Large 4.0.8", + description: "Agentic reasoning and vision, 1M context", + }, + { + value: "deepseek-v4-1-flash-1017", + name: "DeepSeek V4.1 Flash 1017", + description: "Agentic reasoning, 1M context", + }, + { + value: "zai-glm-5-3-flash", + name: "GLM-5.3 Flash", + description: "Fast reasoning and vision, 1M context", + }, { value: "mistral-medium-latest", name: "Mistral Medium (Latest)", @@ -563,11 +613,6 @@ const MODEL_OPTIONS: Record = { name: "Mistral Small 4", description: "Efficient reasoning, coding and vision, 256K context", }, - { - value: "mistral-large-2512", - name: "Mistral Large 3", - description: "General-purpose multimodal model, 262K context", - }, { value: "mistral-small-latest", name: "Mistral Small", @@ -632,6 +677,11 @@ const MODEL_OPTIONS: Record = { name: "DeepSeek V4.1 Flash", description: "Fast reasoning and vision, 1M context", }, + { + value: "MiniMaxAI/MiniMax-M3.1-Flash", + name: "MiniMax M3.1 Flash", + description: "Fast reasoning and vision via Hugging Face", + }, { value: "moonshotai/Kimi-K3", name: "Kimi K3", @@ -688,11 +738,6 @@ const MODEL_OPTIONS: Record = { name: "GPT OSS 120B", description: "Open reasoning model, 131K context", }, - { - value: "stepfun-ai/Step-3.7-Flash", - name: "Step 3.7 Flash", - description: "Fast reasoning model, 262K context", - }, { value: "deepseek-ai/DeepSeek-V4-Pro", name: "DeepSeek V4 Pro", diff --git a/src/memory/__tests__/compaction.test.ts b/src/memory/__tests__/compaction.test.ts index c39de40e..08f5ab36 100644 --- a/src/memory/__tests__/compaction.test.ts +++ b/src/memory/__tests__/compaction.test.ts @@ -1,21 +1,40 @@ -import type { Context, Message } from "@earendil-works/pi-ai"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { Context, Message, AssistantMessage } from "@earendil-works/pi-ai"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ transcripts: new Map(), summarize: vi.fn(), + resetSession: vi.fn(), + archiveTranscript: vi.fn(), + root: "", + persistence: undefined as typeof import("../../session/transcript.js") | undefined, })); vi.mock("../../session/transcript.js", () => ({ appendToTranscript: (sessionId: string, message: Message) => { const transcript = mocks.transcripts.get(sessionId) ?? []; transcript.push(message); + mocks.persistence?.appendToTranscript(sessionId, message); mocks.transcripts.set(sessionId, transcript); }, - readTranscript: (sessionId: string) => [...(mocks.transcripts.get(sessionId) ?? [])], - flushTranscript: vi.fn().mockResolvedValue(undefined), + readTranscript: (sessionId: string) => + mocks.persistence?.readTranscript(sessionId) ?? [...(mocks.transcripts.get(sessionId) ?? [])], + flushTranscript: (sessionId: string) => + mocks.persistence?.flushTranscript(sessionId) ?? Promise.resolve(), + archiveTranscript: mocks.archiveTranscript, })); +vi.mock("../../workspace/paths.js", async () => { + const actual = await vi.importActual( + "../../workspace/paths.js" + ); + const { mkdtempSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + if (!mocks.root) mocks.root = mkdtempSync(`${tmpdir()}/teleton-compaction-`); + return { ...actual, TELETON_ROOT: mocks.root }; +}); +vi.mock("../../session/store.js", () => ({ resetSession: mocks.resetSession })); + vi.mock("../ai-summarization.js", () => ({ summarizeWithFallback: mocks.summarize, })); @@ -64,6 +83,27 @@ describe("CompactionManager", () => { expect(secondInstructions).not.toContain("SUMMARY A"); }); + it.each(["Summary unavailable", "Summary response length"])( + "keeps the original session and transcript when summarization fails: %s", + async (failure) => { + const original = context("retained"); + mocks.transcripts.set("original-session", [...original.messages]); + mocks.summarize.mockReset().mockRejectedValue(new Error(failure)); + const manager = new CompactionManager({ + enabled: true, + maxMessages: 2, + keepRecentMessages: 1, + memoryFlushEnabled: false, + }); + + expect( + await manager.checkAndCompact("original-session", original, "key", "chat", "anthropic") + ).toBeNull(); + expect([...mocks.transcripts.keys()]).toEqual(["original-session"]); + expect(mocks.transcripts.get("original-session")).toEqual(original.messages); + } + ); + it("reuses the summary embedded in the same conversation transcript", async () => { const manager = new CompactionManager({ enabled: true, @@ -96,3 +136,348 @@ describe("CompactionManager", () => { expect(secondInstructions).toContain("SUMMARY A"); }); }); + +function summaryResponse(texts: string[], stop = "end_turn"): Response { + const events: unknown[] = [ + { + type: "message_start", + message: { + id: "msg_test", + type: "message", + role: "assistant", + content: [], + model: "test", + usage: { input_tokens: 5, output_tokens: 0 }, + }, + }, + ]; + texts.forEach((text, index) => { + if (index > 0) + events.push( + { + type: "content_block_start", + index: index + 100, + content_block: { type: "thinking", thinking: "", signature: "test" }, + }, + { + type: "content_block_delta", + index: index + 100, + delta: { type: "thinking_delta", thinking: "private reasoning" }, + }, + { type: "content_block_stop", index: index + 100 } + ); + events.push( + { type: "content_block_start", index, content_block: { type: "text", text: "" } }, + { type: "content_block_delta", index, delta: { type: "text_delta", text } }, + { type: "content_block_stop", index } + ); + }); + events.push( + { type: "message_delta", delta: { stop_reason: stop }, usage: { output_tokens: 5 } }, + { type: "message_stop" } + ); + return new Response( + events + .map((e) => { + const event = e as { type: string }; + return `event: ${event.type}\ndata: ${JSON.stringify(e)}\n\n`; + }) + .join(""), + { headers: { "Content-Type": "text/event-stream" } } + ); +} + +describe("summary adapter responses", () => { + afterEach(() => vi.restoreAllMocks()); + + it("rejects a truncated direct summary", async () => { + const actual = + await vi.importActual("../ai-summarization.js"); + vi.spyOn(globalThis, "fetch").mockImplementation(async () => + summaryResponse(["partial"], "max_tokens") + ); + await expect( + actual.summarizeViaClaude({ messages: context("source").messages, apiKey: "test-key" }) + ).rejects.toThrow("length"); + }); + + it("rejects a truncated merge after successful chunks", async () => { + const actual = + await vi.importActual("../ai-summarization.js"); + vi.spyOn(globalThis, "fetch") + .mockImplementationOnce(async () => summaryResponse(["chunk 1"])) + .mockImplementationOnce(async () => summaryResponse(["chunk 2"])) + .mockImplementationOnce(async () => summaryResponse(["partial merge"], "max_tokens")); + await expect( + actual.summarizeInChunks({ + messages: context("source").messages, + apiKey: "test-key", + maxChunkTokens: 1, + }) + ).rejects.toThrow("length"); + }); + it.each([false, true])( + "keeps ordered text blocks but not reasoning (merge: %s)", + async (merge) => { + const actual = + await vi.importActual("../ai-summarization.js"); + vi.spyOn(globalThis, "fetch").mockImplementation(async () => + summaryResponse(["FIRST", "SECOND"]) + ); + const params = { messages: context("source").messages, apiKey: "test-key" }; + const summary = merge + ? (await actual.summarizeInChunks({ ...params, maxChunkTokens: 1 })).summary + : await actual.summarizeViaClaude(params); + expect(summary).toBe("FIRST\nSECOND"); + } + ); + it("sends bounded tool arguments, receipts and errors without mutating the transcript", async () => { + const actual = + await vi.importActual("../ai-summarization.js"); + const messages: Message[] = [ + { + role: "assistant", + content: [ + { + type: "toolCall", + id: "receipt-call", + name: "transfer", + arguments: { amount: 12345, binary: "AAAA" }, + }, + ], + api: "test", + provider: "test", + model: "test", + stopReason: "toolUse", + timestamp: 1, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }, + { + role: "toolResult", + toolCallId: "receipt-call", + toolName: "transfer", + content: [ + { + type: "text", + text: + "receipt=EXACT_RECEIPT; failed: insufficient balance; " + "long text ".repeat(10000), + }, + { type: "image", data: "DO_NOT_SEND", mimeType: "image/png" }, + ], + isError: true, + timestamp: 2, + }, + ]; + const before = JSON.stringify(messages); + let body = ""; + vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + body = String(init?.body); + return summaryResponse(["summary"]); + }); + await actual.summarizeViaClaude({ messages, apiKey: "test-key" }); + for (const value of [ + "12345", + "EXACT_RECEIPT", + "insufficient balance", + "receipt-call", + "isError=true", + ]) + expect(body).toContain(value); + expect(body).not.toContain("DO_NOT_SEND"); + expect(body).not.toContain("AAAA"); + expect(actual.formatMessagesForSummary(messages).length).toBeLessThan(17000); + expect(actual.splitMessagesByTokens(messages, 100)).toHaveLength(2); + expect(JSON.stringify(messages)).toBe(before); + }); + it("does not truncate ordinary conversation text before chunking", async () => { + const actual = + await vi.importActual("../ai-summarization.js"); + const content = "ordinary text ".repeat(3000) + "IMPORTANT_TAIL"; + expect(actual.formatMessagesForSummary([{ role: "user", content, timestamp: 1 }])).toContain( + "IMPORTANT_TAIL" + ); + }); + it("uses the configured endpoint for chunks and merge", async () => { + const actual = + await vi.importActual("../ai-summarization.js"); + const urls: string[] = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => { + urls.push(String(url)); + return summaryResponse(["summary"]); + }); + for (const baseUrl of ["https://first.test", "https://second.test"]) { + await actual.summarizeInChunks({ + messages: context("source").messages, + apiKey: "test-key", + maxChunkTokens: 1, + baseUrl, + }); + } + expect(urls.slice(0, 3).every((url) => url.startsWith("https://first.test/"))).toBe(true); + expect(urls.slice(3).every((url) => url.startsWith("https://second.test/"))).toBe(true); + expect(urls).toHaveLength(6); + }); + it("invalidates only stale context estimates through compaction, disk reload and the agent loop", async () => { + const { AgentConfigSchema } = await import("../../config/schema.js"); + const { compactAndSaveTranscript } = await import("../compaction.js"); + const actualSummary = + await vi.importActual("../ai-summarization.js"); + mocks.summarize.mockReset().mockImplementation(actualSummary.summarizeWithFallback); + mocks.resetSession.mockClear(); + mocks.archiveTranscript.mockClear(); + mocks.persistence = await vi.importActual( + "../../session/transcript.js" + ); + const config = AgentConfigSchema.parse({ + provider: "anthropic", + api_key: "test-key", + reasoning_effort: "none", + }); + const measured: AssistantMessage = { + role: "assistant", + content: [{ type: "toolCall", id: "receipt-call", name: "lookup", arguments: {} }], + api: "anthropic-messages", + provider: "anthropic", + model: config.model, + timestamp: 2000, + stopReason: "toolUse", + usage: { + input: 195000, + output: 1000, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 196000, + cost: { input: 0.4, output: 0.1, cacheRead: 0, cacheWrite: 0, total: 0.5 }, + }, + }; + const user = { role: "user" as const, content: "Continue using the receipt", timestamp: 3000 }; + const original: Context = { + messages: [ + { role: "user", content: "historical decisions ".repeat(10000), timestamp: 1000 }, + measured, + { + role: "toolResult", + toolCallId: "receipt-call", + toolName: "lookup", + content: [{ type: "text", text: "RECEIPT_PRESERVED" }], + isError: false, + timestamp: 2001, + }, + user, + ], + }; + const before = JSON.stringify(original); + const fetch = vi + .spyOn(globalThis, "fetch") + .mockImplementation(async () => summaryResponse(["DECISIONS_PRESERVED"])); + try { + const sessionId = await compactAndSaveTranscript( + "old-session", + original, + { enabled: true, keepRecentMessages: 3, maxTokens: 100000 }, + "test-key" + ); + expect(sessionId).not.toBe("old-session"); + expect(JSON.stringify(original)).toBe(before); + await mocks.persistence.flushTranscript(sessionId); + // Reload the real transcript module to bypass its in-memory cache. + vi.resetModules(); + mocks.persistence = await vi.importActual( + "../../session/transcript.js" + ); + const { loadContextFromTranscript, chatWithContext } = await import("../../agent/client.js"); + const { getProviderModel, getOutputTokenBudget } = + await import("../../providers/model-resolver.js"); + const { executeAgentLoop } = await import("../../agent/loop/executor.js"); + const reloaded = loadContextFromTranscript(sessionId); + const retained = reloaded.messages.find( + (message) => message.role === "assistant" + ) as AssistantMessage; + expect(retained.usage).toEqual(measured.usage); + expect(retained.timestamp).toBe(2000); + expect(reloaded.messages[0].timestamp).toBe(1000); + expect(retained).toHaveProperty("contextUsageInvalidated", true); + expect(JSON.stringify(reloaded)).toContain("RECEIPT_PRESERVED"); + expect(JSON.stringify(reloaded)).toContain("DECISIONS_PRESERVED"); + const model = getProviderModel("anthropic", config.model); + expect(getOutputTokenBudget(model, reloaded, 4096)).toBe(4096); + const session = { sessionId, chatId: "test", createdAt: 1, updatedAt: 1, messageCount: 0 }; + const loop = await executeAgentLoop( + { + turnId: "test-turn", + chatId: "test", + effectiveIsGroup: false, + processStartTime: Date.now(), + session, + context: reloaded, + systemPrompt: "system", + tools: undefined, + userMsg: user, + provider: "anthropic", + requestedModel: config.model, + resolvedModel: config.model, + endpointFingerprint: "test", + sessionKey: "test", + }, + { chatId: "test", userMessage: user.content }, + { progress: vi.fn(), updateTarget: vi.fn() } as unknown as Parameters< + typeof executeAgentLoop + >[2], + { + config: { agent: config } as Parameters[3]["config"], + toolRegistry: null, + } + ); + expect(loop.stopReason).toBe("completed"); + expect(loop.session.sessionId).toBe(sessionId); + expect(JSON.stringify(loop.context)).toContain("RECEIPT_PRESERVED"); + expect(mocks.resetSession).not.toHaveBeenCalled(); + expect(mocks.archiveTranscript).not.toHaveBeenCalled(); + expect(fetch).toHaveBeenCalledTimes(2); + // Fresh measurements still bound the budget; genuine oversized input still fails locally. + expect( + getOutputTokenBudget( + model, + { + messages: [ + ...reloaded.messages, + { ...measured, content: [], stopReason: "stop", timestamp: Date.now() }, + ], + }, + 4096 + ) + ).toBe(0); + const overflow = await chatWithContext(config, { + context: { systemPrompt: "x ".repeat(500000), messages: [] }, + }); + expect(overflow.message.stopReason).toBe("error"); + expect(overflow.message.errorMessage).toContain("Context length exceeded"); + expect(fetch).toHaveBeenCalledTimes(2); + await mocks.persistence.flushAllTranscripts(); + } finally { + mocks.persistence = undefined; + } + }); + it("rejects an undersized utility Responses budget before transport", async () => { + const actual = + await vi.importActual("../ai-summarization.js"); + const fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Network disabled")); + await expect( + actual.summarizeViaClaude({ + messages: context("small budget").messages, + apiKey: "sk-test-only", + provider: "openai", + utilityModel: "gpt-6-sol", + maxSummaryTokens: 8, + }) + ).rejects.toThrow("at least 16 tokens"); + expect(fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/src/memory/ai-summarization.ts b/src/memory/ai-summarization.ts index 8d689769..f55abf43 100644 --- a/src/memory/ai-summarization.ts +++ b/src/memory/ai-summarization.ts @@ -1,11 +1,6 @@ -import { - complete, - type Context, - type Message, - type TextContent, -} from "@earendil-works/pi-ai/compat"; -import { extractText, extractToolNames, stripEnvelopePrefix } from "../utils/pi-message.js"; -import { getUtilityModel } from "../providers/model-resolver.js"; +import { complete, type Context, type Message } from "@earendil-works/pi-ai/compat"; +import { extractText, stripEnvelopePrefix, truncate } from "../utils/pi-message.js"; +import { getUtilityModel, getOutputTokenBudget } from "../providers/model-resolver.js"; import type { SupportedProvider } from "../config/providers.js"; import { CHARS_PER_TOKEN_ESTIMATE, @@ -73,38 +68,65 @@ export function splitMessagesByTokens(messages: Message[], maxChunkTokens: numbe return chunks; } +const SUMMARY_MESSAGE_MAX_CHARS = 16_000; + +function boundedSummaryText(text: string, maxChars = SUMMARY_MESSAGE_MAX_CHARS): string { + return truncate( + text + .replace(/data:[^\s";]+;base64,[A-Za-z0-9+/=_-]+/g, "[binary omitted]") + .replace(/[A-Za-z0-9+/_-]{256,}={0,2}/g, "[encoded data omitted]"), + maxChars + ); +} + +function serializeSummaryValue(value: unknown): string { + return ( + JSON.stringify(value, (key, entry) => + /base64|binary/i.test(key) || + entry?.type === "image" || + (entry?.type === "Buffer" && Array.isArray(entry.data)) + ? "[binary omitted]" + : entry + ) ?? "{}" + ); +} + function extractMessageContent(message: Message): string { if (message.role === "user") { - return typeof message.content === "string" ? message.content : "[complex content]"; - } else if (message.role === "assistant") { - return extractText(message); + return `User: ${boundedSummaryText(stripEnvelopePrefix(extractText(message)), Infinity)}`; + } + if (message.role === "assistant") { + const parts = [boundedSummaryText(extractText(message), Infinity)].filter(Boolean); + for (const block of message.content) { + if (block.type !== "toolCall") continue; + const args = serializeSummaryValue(block.arguments); + parts.push( + `[Tool call: ${block.name}; id=${block.id}; arguments=${boundedSummaryText(args ?? "{}", 2048)}]` + ); + } + return parts.join("\n"); + } + if (message.role === "toolResult") { + let text = message.content + .filter((block) => block.type === "text") + .map((block) => block.text) + .join("\n"); + let reference = ""; + try { + const parsed: unknown = JSON.parse(text); + const artifact = (parsed as { data?: { _artifact?: { id?: unknown } } })?.data?._artifact; + text = serializeSummaryValue(parsed); + if (artifact?.id) reference = `; artifact=${String(artifact.id)}; read_with=tool_result_read`; + } catch { + /* Plain text results need no artifact lookup. */ + } + return `[Tool result: ${message.toolName}; id=${message.toolCallId}; isError=${message.isError}${reference}]\n${boundedSummaryText(text)}`; } return ""; } export function formatMessagesForSummary(messages: Message[]): string { - const formatted: string[] = []; - - for (const msg of messages) { - if (msg.role === "user") { - const content = typeof msg.content === "string" ? msg.content : "[complex]"; - const body = stripEnvelopePrefix(content); - formatted.push(`User: ${body}`); - } else if (msg.role === "assistant") { - const textBlocks = msg.content.filter((b): b is TextContent => b.type === "text"); - if (textBlocks.length > 0) { - formatted.push(`Assistant: ${extractText(msg)}`); - } - const toolNames = extractToolNames(msg); - if (toolNames.length > 0) { - formatted.push(`[Used tools: ${toolNames.join(", ")}]`); - } - } else if (msg.role === "toolResult") { - formatted.push(`[Tool result: ${msg.toolName}]`); - } - } - - return formatted.join("\n\n"); + return messages.map(extractMessageContent).filter(Boolean).join("\n\n"); } /** @@ -155,9 +177,10 @@ export async function summarizeViaClaude(params: { customInstructions?: string; provider?: SupportedProvider; utilityModel?: string; + baseUrl?: string; }): Promise { const provider = params.provider || "anthropic"; - const model = getUtilityModel(provider, params.utilityModel); + const model = getUtilityModel(provider, params.utilityModel, params.baseUrl); const maxTokens = params.maxSummaryTokens ?? DEFAULT_SUMMARY_FALLBACK_TOKENS; const formatted = formatMessagesForSummary(params.messages); @@ -189,14 +212,23 @@ Be specific but concise. Preserve critical information.`; ], }; + if (!getOutputTokenBudget(model, context, maxTokens, params.apiKey)) + throw new Error("Context length exceeded during summarization"); const response = await complete(model, context, { apiKey: params.apiKey, - maxTokens, + maxTokens: getOutputTokenBudget(model, context, maxTokens, params.apiKey), }); - const textContent = response.content.find((block) => block.type === "text"); - const summary = textContent?.type === "text" ? textContent.text : ""; - return summary.trim() || "Unable to generate summary."; + if ( + response.stopReason === "error" || + response.stopReason === "aborted" || + response.stopReason === "length" + ) { + throw new Error(response.errorMessage || `Summary response ${response.stopReason}`); + } + const summary = extractText(response); + if (!summary.trim()) throw new Error("Model returned an empty summary"); + return summary.trim(); } catch (error) { log.error({ err: error }, "Summarization error"); throw new Error(`Summarization failed: ${getErrorMessage(error)}`); @@ -215,6 +247,7 @@ export async function summarizeInChunks(params: { customInstructions?: string; provider?: SupportedProvider; utilityModel?: string; + baseUrl?: string; }): Promise { if (params.messages.length === 0) { return { @@ -236,6 +269,7 @@ export async function summarizeInChunks(params: { customInstructions: params.customInstructions, provider: params.provider, utilityModel: params.utilityModel, + baseUrl: params.baseUrl, }); return { @@ -259,6 +293,7 @@ export async function summarizeInChunks(params: { customInstructions: params.customInstructions, provider: params.provider, utilityModel: params.utilityModel, + baseUrl: params.baseUrl, }); partialSummaries.push(partial); @@ -267,7 +302,7 @@ export async function summarizeInChunks(params: { log.info(`Merging ${partialSummaries.length} partial summaries`); const provider = params.provider || "anthropic"; - const model = getUtilityModel(provider, params.utilityModel); + const model = getUtilityModel(provider, params.utilityModel, params.baseUrl); const mergeContext: Context = { messages: [ { @@ -284,16 +319,37 @@ ${partialSummaries.map((s, i) => `Part ${i + 1}:\n${s}`).join("\n\n---\n\n")}`, ], }; + if ( + !getOutputTokenBudget( + model, + mergeContext, + params.maxSummaryTokens ?? DEFAULT_SUMMARY_FALLBACK_TOKENS, + params.apiKey + ) + ) + throw new Error("Context length exceeded during summary merge"); const mergeResponse = await complete(model, mergeContext, { apiKey: params.apiKey, - maxTokens: params.maxSummaryTokens ?? DEFAULT_SUMMARY_FALLBACK_TOKENS, + maxTokens: getOutputTokenBudget( + model, + mergeContext, + params.maxSummaryTokens ?? DEFAULT_SUMMARY_FALLBACK_TOKENS, + params.apiKey + ), }); - const textContent = mergeResponse.content.find((block) => block.type === "text"); - const merged = textContent?.type === "text" ? textContent.text : ""; + if ( + mergeResponse.stopReason === "error" || + mergeResponse.stopReason === "aborted" || + mergeResponse.stopReason === "length" + ) { + throw new Error(mergeResponse.errorMessage || `Summary merge ${mergeResponse.stopReason}`); + } + const merged = extractText(mergeResponse); + if (!merged.trim()) throw new Error("Model returned an empty merged summary"); return { - summary: merged.trim() || "Unable to merge summaries.", + summary: merged.trim(), tokensUsed: estimateMessageTokens(merged), chunksProcessed: chunks.length, }; @@ -311,6 +367,7 @@ export async function summarizeWithFallback(params: { customInstructions?: string; provider?: SupportedProvider; utilityModel?: string; + baseUrl?: string; }): Promise { if (params.messages.length === 0) { return { @@ -336,6 +393,7 @@ export async function summarizeWithFallback(params: { customInstructions: params.customInstructions, provider: params.provider, utilityModel: params.utilityModel, + baseUrl: params.baseUrl, }); } catch (fullError) { log.warn(`Full summarization failed: ${getErrorMessage(fullError)}`); @@ -370,6 +428,7 @@ export async function summarizeWithFallback(params: { customInstructions: params.customInstructions, provider: params.provider, utilityModel: params.utilityModel, + baseUrl: params.baseUrl, }); const notes = oversizedNotes.length > 0 ? `\n\n${oversizedNotes.join("\n")}` : ""; @@ -383,15 +442,5 @@ export async function summarizeWithFallback(params: { } } - const note = - `Context contained ${params.messages.length} messages ` + - `(${oversizedNotes.length} were oversized). ` + - `AI summarization unavailable due to size constraints. ` + - `Recent conversation history was preserved.`; - - return { - summary: note, - tokensUsed: estimateMessageTokens(note), - chunksProcessed: 0, - }; + throw new Error("AI summarization failed for all fallback attempts"); } diff --git a/src/memory/compaction.ts b/src/memory/compaction.ts index db7d7e91..dc22e868 100644 --- a/src/memory/compaction.ts +++ b/src/memory/compaction.ts @@ -158,7 +158,8 @@ export async function compactContext( apiKey: string, provider?: SupportedProvider, utilityModel?: string, - previousSummary?: string | null + previousSummary?: string | null, + baseUrl?: string ): Promise { const keepCount = config.keepRecentMessages ?? 10; @@ -264,6 +265,7 @@ What was completed. Each bullet: tool used + result. Keep specific values. Unfinished work, blocked tasks, questions waiting for user response. Most urgent first.`, provider, utilityModel, + baseUrl, }); log.info(`AI Summary: ${result.tokensUsed} tokens, ${result.chunksProcessed} chunks processed`); @@ -278,23 +280,19 @@ Unfinished work, blocked tasks, questions waiting for user response. Most urgent return { ...context, - messages: [summaryMessage, ...recentMessages], + messages: [ + summaryMessage, + ...recentMessages.map((message) => + message.role === "assistant" + ? // Billing and timestamps remain intact; this usage covered the removed prefix. + { ...message, contextUsageInvalidated: true } + : message + ), + ], }; } catch (error) { - log.error({ err: error }, "AI summarization failed, using fallback"); - - const summaryText = `${COMPACTION_PREFIX}: ${oldMessages.length} earlier messages from this conversation]`; - - const summaryMessage: Message = { - role: "user", - content: summaryText, - timestamp: oldMessages[0]?.timestamp ?? Date.now(), - }; - - return { - ...context, - messages: [summaryMessage, ...recentMessages], - }; + log.error({ err: error }, "AI summarization failed, keeping original context"); + return context; } } @@ -306,8 +304,20 @@ export async function compactAndSaveTranscript( chatId?: string, provider?: SupportedProvider, utilityModel?: string, - previousSummary?: string | null + previousSummary?: string | null, + baseUrl?: string ): Promise { + const compactedContext = await compactContext( + context, + config, + apiKey, + provider, + utilityModel, + previousSummary, + baseUrl + ); + if (compactedContext === context) return sessionId; + const newSessionId = randomUUID(); log.info(`Creating compacted transcript: ${sessionId} → ${newSessionId}`); @@ -321,18 +331,10 @@ export async function compactAndSaveTranscript( apiKey, provider, utilityModel, + baseUrl, }); } - const compactedContext = await compactContext( - context, - config, - apiKey, - provider, - utilityModel, - previousSummary - ); - for (const message of compactedContext.messages) { appendToTranscript(newSessionId, message); } @@ -354,7 +356,8 @@ export class CompactionManager { apiKey: string, chatId?: string, provider?: SupportedProvider, - utilityModel?: string + utilityModel?: string, + baseUrl?: string ): Promise { const tokenCount = estimateContextTokens(context); @@ -381,8 +384,10 @@ export class CompactionManager { chatId, provider, utilityModel, - findPreviousCompactionSummary(context) + findPreviousCompactionSummary(context), + baseUrl ); + if (newSessionId === sessionId) return null; log.info(`Compaction complete: ${newSessionId}`); return newSessionId; diff --git a/src/providers/__tests__/codex-models.test.ts b/src/providers/__tests__/codex-models.test.ts index dde45be6..efef2e6a 100644 --- a/src/providers/__tests__/codex-models.test.ts +++ b/src/providers/__tests__/codex-models.test.ts @@ -5,6 +5,7 @@ import { AgentConfigSchema } from "../../config/schema.js"; import { getProviderModel } from "../model-resolver.js"; const CODEX_MODELS = [ + "gpt-6.1-terra", "gpt-6.1-sol", "gpt-6-sol", "gpt-6-luna", @@ -22,7 +23,9 @@ describe("Codex models", () => { expect(model.provider).toBe("openai-codex"); expect(model.api).toBe("openai-codex-responses"); expect(model.input).toContain("image"); - expect(model.contextWindow).toBe(modelId === "gpt-6.1-sol" ? 500_000 : 272_000); + expect(model.contextWindow).toBe( + ["gpt-6.1-sol", "gpt-6.1-terra"].includes(modelId) ? 500_000 : 272_000 + ); expect(model.maxTokens).toBe(128_000); }); diff --git a/src/providers/__tests__/model-catalog.test.ts b/src/providers/__tests__/model-catalog.test.ts index 336ffa3a..646af036 100644 --- a/src/providers/__tests__/model-catalog.test.ts +++ b/src/providers/__tests__/model-catalog.test.ts @@ -53,6 +53,8 @@ const LEGACY_MODEL_CASES: ReadonlyArray< describe("provider model catalog", () => { it.each([ + ["mistral", "mistral-large-2512"], + ["huggingface", "stepfun-ai/Step-3.7-Flash"], ["codex", "gpt-5.5"], ["codex", "gpt-5.3-codex-spark"], ["codex", "gpt-5.4"], @@ -136,6 +138,17 @@ describe("provider model catalog", () => { }); it.each([ + ["openai", "gpt-6.1-terra"], + ["codex", "gpt-6.1-terra"], + ["moonshot", "k3.1-pro"], + ["moonshot", "k3.1-pro-highspeed"], + ["openrouter", "openai/gpt-6.1-terra"], + ["openrouter", "openai/gpt-6.1-terra-pro"], + ["openrouter", "moonshotai/kimi-k3.1-pro"], + ["mistral", "mistral-large-4-0-8"], + ["mistral", "deepseek-v4-1-flash-1017"], + ["mistral", "zai-glm-5-3-flash"], + ["huggingface", "MiniMaxAI/MiniMax-M3.1-Flash"], ["anthropic", "claude-sonnet-5-5"], ["anthropic", "claude-haiku-5-5"], ["google", "gemini-4-argon"], diff --git a/src/providers/__tests__/model-resolver-dynamic.test.ts b/src/providers/__tests__/model-resolver-dynamic.test.ts index 144ebc76..5591eecb 100644 --- a/src/providers/__tests__/model-resolver-dynamic.test.ts +++ b/src/providers/__tests__/model-resolver-dynamic.test.ts @@ -5,6 +5,7 @@ vi.mock("../../utils/fetch.js", () => ({ fetchWithTimeout: mocks.fetchWithTimeou import { getProviderModel, + getUtilityModel, isCustomOpenRouterModel, registerLocalModels, } from "../model-resolver.js"; @@ -82,4 +83,16 @@ describe("dynamic model registry", () => { await expect(registerLocalModels("http://new.local/v1")).resolves.toEqual([]); expect(() => getProviderModel("local", "old-model")).toThrow(/not served/i); }); + it("isolates utility model endpoints and local discovery", async () => { + for (const endpoint of ["https://first.test/v1", "https://second.test/v1"]) { + expect(getUtilityModel("anthropic", undefined, endpoint).baseUrl).toBe(endpoint); + mocks.fetchWithTimeout.mockResolvedValue({ + ok: true, + json: async () => ({ data: [{ id: endpoint.includes("first") ? "first" : "second" }] }), + }); + await registerLocalModels(endpoint); + } + expect(getUtilityModel("local", "auto", "https://first.test/v1").id).toBe("first"); + expect(getUtilityModel("local", "auto", "https://second.test/v1").id).toBe("second"); + }); }); diff --git a/src/providers/model-resolver.ts b/src/providers/model-resolver.ts index 61efdc9a..e5ffe252 100644 --- a/src/providers/model-resolver.ts +++ b/src/providers/model-resolver.ts @@ -1,4 +1,13 @@ -import { getModel, type Model, type Api } from "@earendil-works/pi-ai/compat"; +import { estimateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate"; +import { + getModel, + hasApi, + getEnvApiKey, + normalizeContext, + type Context, + type Model, + type Api, +} from "@earendil-works/pi-ai/compat"; import { getProviderMetadata, type SupportedProvider } from "../config/providers.js"; import { createLogger } from "../utils/logger.js"; import { fetchWithTimeout } from "../utils/fetch.js"; @@ -332,10 +341,82 @@ export function getProviderModel( } } -export function getUtilityModel(provider: SupportedProvider, overrideModel?: string): Model { +export function getUtilityModel( + provider: SupportedProvider, + overrideModel?: string, + baseUrl?: string +): Model { const meta = getProviderMetadata(provider); const requested = overrideModel || meta.utilityModel; const modelId = - provider === "local" && requested === "auto" ? (defaultLocalModel ?? requested) : requested; - return getProviderModel(provider, modelId); + provider === "local" && requested === "auto" + ? baseUrl + ? (Object.keys(LOCAL_ENDPOINTS.get(baseUrl.replace(/\/+$/, "")) ?? {})[0] ?? requested) + : (defaultLocalModel ?? requested) + : requested; + return getProviderModel(provider, modelId, baseUrl); +} + +/** Conservative estimate; measured prefix usage already includes the system and tools. */ +export function getOutputTokenBudget( + model: Model, + context: Context, + requested: number, + apiKey?: string +): number { + if (!Number.isFinite(requested) || requested < 1) + throw new Error("Output token budget must be positive"); + // Mirror the installed Responses adapter: Codex and transports omitting the field have no such minimum. + const responsesKey = + model.api === "openai-responses" + ? apiKey?.trim() + ? apiKey + : getEnvApiKey(model.provider) + : undefined; + const chatGptSignIn = + model.provider === "openai" && + model.baseUrl === "https://api.openai.com/v1" && + responsesKey !== undefined && + !responsesKey.startsWith("sk-"); + const minimum = + hasApi(model, "openai-responses") && + model.compat?.supportsMaxOutputTokens !== false && + !chatGptSignIn + ? 16 + : 1; + if (requested < minimum) + throw new Error(`Output token budget must be at least ${minimum} tokens for OpenAI Responses`); + const transcript = normalizeContext(context); + // Current schemas may differ from those covered by a previous usage measurement. + const staticTokens = transcript.messages.reduce( + (sum, message) => sum + estimateMessageTokens(message), + 0 + ); + const estimationTranscript = { + messages: transcript.messages.map((message) => + message.role === "assistant" && + "contextUsageInvalidated" in message && + message.contextUsageInvalidated === true + ? { + ...message, + usage: { + ...message.usage, + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + }, + } + : message + ), + }; + const contextTokens = Math.max( + estimateContextTokens(estimationTranscript.messages).tokens, + staticTokens + ); + const available = + model.contextWindow > 0 ? model.contextWindow - contextTokens - 4096 : model.maxTokens; + const budget = Math.max(0, Math.floor(Math.min(requested, model.maxTokens, available))); + return budget < minimum ? 0 : budget; } diff --git a/src/session/memory-hook.ts b/src/session/memory-hook.ts index 46d5a31c..4f9bfbab 100644 --- a/src/session/memory-hook.ts +++ b/src/session/memory-hook.ts @@ -8,6 +8,7 @@ import { formatMessagesForSummary, } from "../memory/ai-summarization.js"; import { getUtilityModel } from "../agent/client.js"; +import { getOutputTokenBudget } from "../providers/model-resolver.js"; import type { SupportedProvider } from "../config/providers.js"; import { createLogger } from "../utils/logger.js"; import { @@ -28,9 +29,10 @@ async function generateSlugViaClaude(params: { apiKey: string; provider?: SupportedProvider; utilityModel?: string; + baseUrl?: string; }): Promise { const provider = params.provider || "anthropic"; - const model = getUtilityModel(provider, params.utilityModel); + const model = getUtilityModel(provider, params.utilityModel, params.baseUrl); const formatted = formatMessagesForSummary(params.messages.slice(-SESSION_SLUG_RECENT_MESSAGES)); @@ -55,9 +57,11 @@ Slug:`, ], }; + const maxTokens = getOutputTokenBudget(model, context, SESSION_SLUG_MAX_TOKENS, params.apiKey); + if (!maxTokens) throw new Error("Context length exceeded during slug generation"); const response = await complete(model, context, { apiKey: params.apiKey, - maxTokens: SESSION_SLUG_MAX_TOKENS, + maxTokens, }); const textContent = response.content.find((block) => block.type === "text"); @@ -90,6 +94,7 @@ export async function saveSessionMemory(params: { apiKey: string; provider?: SupportedProvider; utilityModel?: string; + baseUrl?: string; }): Promise { try { const { TELETON_ROOT } = await import("../workspace/paths.js"); @@ -105,6 +110,7 @@ export async function saveSessionMemory(params: { apiKey: params.apiKey, provider: params.provider, utilityModel: params.utilityModel, + baseUrl: params.baseUrl, }); const filename = `${dateStr}-${slug}.md`; @@ -123,6 +129,7 @@ export async function saveSessionMemory(params: { "Summarize this session comprehensively. Include key topics, decisions made, problems solved, and important context.", provider: params.provider, utilityModel: params.utilityModel, + baseUrl: params.baseUrl, }); } catch (error) { log.warn({ err: error }, "Session summary generation failed"); @@ -190,6 +197,7 @@ export async function consolidateOldMemoryFiles(params: { apiKey: string; provider?: SupportedProvider; utilityModel?: string; + baseUrl?: string; }): Promise<{ consolidated: number }> { try { const { TELETON_ROOT } = await import("../workspace/paths.js"); @@ -307,6 +315,7 @@ ${sourceList} Preserve key facts, decisions, patterns, and important context. Remove redundancy. Organize by topic. You may reference source file names when relevant.`, provider: params.provider, utilityModel: params.utilityModel, + baseUrl: params.baseUrl, }); summary = result.summary; } catch (error) { diff --git a/src/startup-maintenance.ts b/src/startup-maintenance.ts index c7096655..76c7e35a 100644 --- a/src/startup-maintenance.ts +++ b/src/startup-maintenance.ts @@ -1,3 +1,4 @@ +import { getEffectiveApiKey } from "./agent/model-request.js"; import type Database from "better-sqlite3"; import type { Config } from "./config/schema.js"; import type { EmbeddingProvider } from "./memory/embeddings/provider.js"; @@ -114,9 +115,10 @@ export class StartupMaintenance { import("./session/memory-hook.js") .then(({ consolidateOldMemoryFiles }) => consolidateOldMemoryFiles({ - apiKey: this.config.agent.api_key, + apiKey: getEffectiveApiKey(this.config.agent.provider, this.config.agent.api_key), provider: this.config.agent.provider as SupportedProvider, utilityModel: this.config.agent.utility_model, + baseUrl: this.config.agent.base_url, }) ) .then((r) => { diff --git a/src/utils/fetch.ts b/src/utils/fetch.ts index db0a2118..00b151f3 100644 --- a/src/utils/fetch.ts +++ b/src/utils/fetch.ts @@ -19,3 +19,52 @@ export function fetchWithTimeout( : AbortSignal.timeout(timeoutMs), }); } + +/** Capture retry metadata even when a provider adapter never calls onResponse. */ +export function createRetryAfterTracker(fetcher: typeof fetch = globalThis.fetch) { + let retryAt: number | undefined; + return { + fetch: (async (input, init) => { + retryAt = undefined; + const response = await fetcher(input, init); + if (!response.ok) { + const ms = response.headers.get("retry-after-ms"); + const after = response.headers.get("retry-after"); + let delay: number | undefined; + if (ms !== null && ms.trim() && Number.isFinite(Number(ms)) && Number(ms) >= 0) + delay = Number(ms); + else if (after !== null && after.trim()) { + const seconds = Number(after); + delay = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(after) - Date.now(); + } + if (delay !== undefined && Number.isFinite(delay) && delay >= 0) + retryAt = Date.now() + delay; + } + return response; + }) as typeof fetch, + retryAfterMs: () => (retryAt === undefined ? undefined : Math.max(0, retryAt - Date.now())), + }; +} + +export async function waitForRetry( + delayMs: number, + signal?: AbortSignal, + deadline?: number +): Promise { + signal?.throwIfAborted(); + if (deadline !== undefined && delayMs >= deadline - Date.now()) { + throw new Error("Provider retry delay exceeds remaining turn budget"); + } + await new Promise((resolve, reject) => { + const abort = () => { + clearTimeout(timer); + reject(signal?.reason ?? new Error("Retry cancelled")); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", abort); + resolve(); + }, delayMs); + signal?.addEventListener("abort", abort, { once: true }); + }); + signal?.throwIfAborted(); +} diff --git a/src/utils/pi-message.ts b/src/utils/pi-message.ts index f382e8cc..25b1ae9a 100644 --- a/src/utils/pi-message.ts +++ b/src/utils/pi-message.ts @@ -49,3 +49,47 @@ export function stripEnvelopePrefix(content: string): string { export function truncate(s: string, n: number): string { return s.length > n ? s.substring(0, n) + "..." : s; } + +/** Per-response filter: retain possible tag prefixes across stream chunks. */ +export function createThinkFilter(): { + push(text: string): string; + flushPublic(): string; + end(completed?: boolean): string; +} { + let pending = ""; + let hidden = false; + return { + push(text) { + pending += text; + let visible = ""; + while (pending) { + const tag = hidden ? "" : ""; + const index = pending.indexOf(tag); + if (index >= 0) { + if (!hidden) visible += pending.slice(0, index); + pending = pending.slice(index + tag.length); + hidden = !hidden; + continue; + } + let keep = Math.min(tag.length - 1, pending.length); + while (keep > 0 && !tag.startsWith(pending.slice(-keep))) keep--; + if (!hidden) visible += pending.slice(0, pending.length - keep); + pending = keep ? pending.slice(-keep) : ""; + break; + } + return visible; + }, + flushPublic() { + if (hidden) return ""; + const suffix = pending; + pending = ""; + return suffix; + }, + end(completed = true) { + // Incomplete responses discard pending prefixes; hidden content is never flushed. + const suffix = completed && !hidden ? pending : ""; + pending = ""; + return suffix; + }, + }; +} diff --git a/vitest.config.ts b/vitest.config.ts index 98454edd..bf654cb6 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -11,6 +11,7 @@ export default defineConfig({ ], coverage: { provider: "v8", + reportsDirectory: "coverage/backend", reporter: ["text", "lcov", "json-summary"], include: [ "src/**/*.ts", @@ -31,4 +32,4 @@ export default defineConfig({ // Longer timeout for tests that import heavy deps (GramJS, @ton/ton) testTimeout: 10_000, }, -}); \ No newline at end of file +}); diff --git a/vitest.sdk.config.ts b/vitest.sdk.config.ts index ca81ad18..79dfab07 100644 --- a/vitest.sdk.config.ts +++ b/vitest.sdk.config.ts @@ -9,6 +9,7 @@ export default defineConfig({ testTimeout: 10_000, coverage: { provider: "v8", + reportsDirectory: "coverage/sdk", reporter: ["text", "json-summary"], include: ["src/sdk/**/*.ts", "packages/sdk/src/**/*.ts"], exclude: ["**/__tests__/**", "**/dist/**"],