From 2bd4b7c25948f0180e88ed95fa8745739ebaff7a Mon Sep 17 00:00:00 2001 From: Wang Can Date: Tue, 23 Jun 2026 15:59:23 +0800 Subject: [PATCH 1/2] feat: recover text-emitted tool calls + changeset-driven auto-release - ToolCallExtractor: some models emit a tool call as inline / XML text instead of native tool_calls; the adapter now recovers those into structured tool chunks (only when the request carries tools; falls back to plain text on incomplete/ambiguous input to avoid false positives). - Release automation: changeset-driven auto-version + npm publish on merge to master; build-time version injection (src/version.ts from package.json) removes version drift across package.json + CLI; old publish.yml downgraded to a manual break-glass. - Adds CLAUDE.md (worktree+PR workflow, commit hygiene). Co-Authored-By: Claude Opus 4.8 (1M context) --- .changes/README.md | 44 +++++++++ .github/workflows/ci.yml | 6 ++ .github/workflows/publish.yml | 30 +++---- .github/workflows/release.yml | 115 ++++++++++++++++++++++++ CLAUDE.md | 34 +++++++ e2e/RESULTS.md | 5 ++ package-lock.json | 4 +- package.json | 2 + scripts/changesets.mjs | 73 +++++++++++++++ scripts/gen-version.mjs | 20 +++++ src/cli/index.ts | 5 +- src/core/tool-xml.ts | 104 +++++++++++++++++++++ src/providers/copilot/adapter.ts | 33 ++++++- src/version.ts | 2 + tests/core/tool-xml.test.ts | 81 +++++++++++++++++ tests/providers/copilot/adapter.test.ts | 50 +++++++++++ 16 files changed, 585 insertions(+), 23 deletions(-) create mode 100644 .changes/README.md create mode 100644 .github/workflows/release.yml create mode 100644 CLAUDE.md create mode 100644 scripts/changesets.mjs create mode 100644 scripts/gen-version.mjs create mode 100644 src/core/tool-xml.ts create mode 100644 src/version.ts create mode 100644 tests/core/tool-xml.test.ts diff --git a/.changes/README.md b/.changes/README.md new file mode 100644 index 0000000..dac1829 --- /dev/null +++ b/.changes/README.md @@ -0,0 +1,44 @@ +# Changesets + +This folder drives **automatic versioning + npm publishing**. When a commit lands on `master` +with one or more changeset files here, the [`release` workflow](../.github/workflows/release.yml) +bumps the version, publishes to npm, tags the release, and deletes the spent changesets. + +**No changeset = no release.** Plain `docs:` / `chore:` commits don't publish anything. + +## Add a changeset + +```bash +npm run changeset minor "namespaced worker routes" # or: patch | major +``` + +…or just drop a file `.changes/anything.md`: + +```markdown +--- +bump: minor +--- +Human-readable summary of the change. This line is prepended to CHANGELOG.md. +``` + +## Bump levels (standard semver, no 0.x special-casing) + +| level | 0.1.0 → | when | +|---------|---------|------| +| `patch` | 0.1.1 | bug fix, no API/route change | +| `minor` | 0.2.0 | new feature, additive | +| `major` | 1.0.0 | breaking change (e.g. route/CLI/config that requires user action) | + +If several changesets are present in one release, the **highest** level wins. + +## What the release does + +1. reads the highest `bump:` across all changesets here +2. `npm version ` → regenerates `src/version.ts` +3. `npm run build && npm test` (gate) +4. `npm publish` (idempotent — skipped if that version is already on npm) +5. consumes (deletes) these changeset files, prepends their bodies to `CHANGELOG.md` +6. commits `release: vX.Y.Z` + tags `vX.Y.Z`, pushes back to `master` + +The release commit is pushed with the default `GITHUB_TOKEN`, so it does **not** re-trigger the +workflow — no publish loop. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94a0694..2f5e8f1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,6 +30,12 @@ jobs: - name: Typecheck + build run: npm run build + - name: Check src/version.ts is in sync with package.json + run: | + node scripts/gen-version.mjs + git diff --exit-code src/version.ts \ + || (echo "::error::src/version.ts is stale — run 'node scripts/gen-version.mjs' and commit" && exit 1) + - name: Run tests run: npm test diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 8cede90..017f5e4 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,10 +1,10 @@ -name: Publish +name: Publish (manual break-glass) -# Publish to npm when a version tag is pushed, e.g. `git tag v0.0.1 && git push --tags`. +# Normal releases are automated by release.yml (changeset-driven, on push to master). +# This workflow is a manual fallback: trigger it from the Actions tab to build, test, and +# publish the CURRENT package.json version to npm — e.g. if an automated release half-failed. on: - push: - tags: - - "v*" + workflow_dispatch: jobs: publish: @@ -29,17 +29,13 @@ jobs: npm run build npm test - - name: Verify tag matches package.json version - run: | - PKG_VERSION="v$(node -p "require('./package.json').version")" - TAG="${GITHUB_REF_NAME}" - echo "package.json: $PKG_VERSION tag: $TAG" - if [ "$PKG_VERSION" != "$TAG" ]; then - echo "::error::Tag $TAG does not match package.json version $PKG_VERSION" - exit 1 - fi - - - name: Publish to npm - run: npm publish --access public + - name: Publish current version to npm (idempotent) env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + VERSION="$(node -p "require('./package.json').version")" + if npm view "copilot-reverse@$VERSION" version >/dev/null 2>&1; then + echo "copilot-reverse@$VERSION already on npm — nothing to do" + else + npm publish --access public + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..d50b970 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,115 @@ +name: Release + +# Auto-publish on merge to master, driven by changeset files in .changes/. +# No changeset present -> the `release` job is skipped -> nothing is published. +# The release commit/tag is pushed with the default GITHUB_TOKEN, which does NOT +# re-trigger workflows, so there is no publish loop. +on: + push: + branches: [master] + +# Serialize releases; never cancel a half-finished publish. +concurrency: + group: release + cancel-in-progress: false + +jobs: + detect: + runs-on: ubuntu-latest + outputs: + has: ${{ steps.status.outputs.has }} + bump: ${{ steps.status.outputs.bump }} + steps: + - uses: actions/checkout@v4 + with: { fetch-depth: 1 } + - uses: actions/setup-node@v4 + with: { node-version: 22 } + - id: status + run: node scripts/changesets.mjs status --github-output + + release: + needs: detect + if: ${{ needs.detect.outputs.has == 'true' }} + runs-on: ubuntu-latest + permissions: + contents: write # push the release commit + tag back to master + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: true # keep GITHUB_TOKEN for the push + + - uses: actions/setup-node@v4 + with: + node-version: 22 + registry-url: "https://registry.npmjs.org" + cache: npm + + - name: Configure git identity + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + - name: Install dependencies + run: npm ci + + - name: Bump version (no tag yet) + id: bump + run: | + NEW=$(npm version "${{ needs.detect.outputs.bump }}" --no-git-tag-version) + echo "version=${NEW#v}" >> "$GITHUB_OUTPUT" + echo "Bumped to $NEW" + + - name: Regenerate src/version.ts + run: node scripts/gen-version.mjs + + - name: Build + test (gate before publish) + run: | + npm run build + npm test + + # Idempotent: if this version is already on npm (e.g. a prior run published but + # failed to push), skip publish so a re-run can still land the commit/tag. + - name: Publish to npm (idempotent) + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + VERSION="${{ steps.bump.outputs.version }}" + if npm view "copilot-reverse@$VERSION" version >/dev/null 2>&1; then + echo "copilot-reverse@$VERSION already on npm — skipping publish" + else + npm publish --access public + fi + + - name: Update CHANGELOG + consume changesets + run: | + VERSION="${{ steps.bump.outputs.version }}" + DATE=$(date +%Y-%m-%d) + BODIES=$(node scripts/changesets.mjs bodies) + { + echo "## v$VERSION — $DATE" + echo "" + echo "$BODIES" + echo "" + if [ -f CHANGELOG.md ]; then cat CHANGELOG.md; fi + } > CHANGELOG.next.md + mv CHANGELOG.next.md CHANGELOG.md + node scripts/changesets.mjs consume + + - name: Commit, tag, push (with rebase retry) + run: | + VERSION="${{ steps.bump.outputs.version }}" + git add package.json package-lock.json src/version.ts CHANGELOG.md + git add -A .changes + git commit -m "release: v$VERSION" + git tag "v$VERSION" + for i in 1 2 3; do + git pull --rebase origin master \ + && git push origin HEAD:master \ + && git push origin "v$VERSION" \ + && exit 0 + echo "push attempt $i failed; retrying after rebase…" + sleep 3 + done + echo "::error::failed to push release after 3 attempts" + exit 1 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..9d309fa --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,34 @@ +# CLAUDE.md + +Guidance for Claude Code when working in this repo. + +## Workflow: prefer git worktrees + +**For any new feature or bug fix, work in a dedicated git worktree — do not commit directly on `master`.** + +- At the start of a feature/bugfix task, create a worktree (use the `EnterWorktree` tool, or `git worktree add`) and do all work there on a new branch. +- Keep `master` clean; open a PR from the worktree branch to merge. +- Small, single-file edits, docs-only tweaks, or quick investigations don't need a worktree — use judgment. +- When the work is merged or abandoned, remove the worktree. + +## Commit hygiene + +- Stage by explicit path (`git add `). **Never** `git add -A` / `git add .` — the tree is shared and may hold unrelated changes. +- Create new commits; don't amend published ones. + +## Dev essentials + +Requires Node >=20. + +- Install / verify: `npm install && npm test && npm run build` +- Run the app locally: `npm run dev` (tsx on `src/`, no build needed) +- Tests: `npm test` (vitest, includes e2e) · `npm run test:e2e` (e2e only) +- **Every change must keep the full e2e suite green.** After a change, re-run and update [`e2e/RESULTS.md`](e2e/RESULTS.md). Case catalog: [`e2e/cases.md`](e2e/cases.md). + +## Architecture (3 processes, one terminal app) + +- **TUI** (Ink) — the `copilot-reverse` process: REPL + slash commands + a claude-agent-sdk assistant. +- **Supervisor** (:7890) — control API + SQLite + self-healing worker supervision. +- **Worker** (:7891) — OpenAI `/openai/chat/completions` + Anthropic `/anthropic/v1/messages` → Copilot, with tool-use translation both ways. + +Data dir: `~/.copilot-reverse`. diff --git a/e2e/RESULTS.md b/e2e/RESULTS.md index 284770c..b06481f 100644 --- a/e2e/RESULTS.md +++ b/e2e/RESULTS.md @@ -3,6 +3,11 @@ Latest run of the end-to-end suite. Regenerate after every code change with `npm run test:e2e` and update this file (paste the summary). +- **2026-06-23** — Added `ToolCallExtractor` (recovers text-emitted ``/`` + tool calls into structured tool chunks) plus changeset-driven auto-release (build-time version + injection, release workflow). Full suite green: `npm test` → **236 passed** (47 files), e2e all + green, tsc build clean. + - **Date:** 2026-06-22 22:14 CST - **Runner:** vitest 2.1.9 · Node v25.6.0 - **Command:** `npm run test:e2e` diff --git a/package-lock.json b/package-lock.json index d97f389..e2e0799 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "copilot-reverse", - "version": "0.0.2", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "copilot-reverse", - "version": "0.0.2", + "version": "0.1.0", "license": "MIT", "dependencies": { "@anthropic-ai/claude-agent-sdk": "^0.1.0", diff --git a/package.json b/package.json index 432970b..742c115 100644 --- a/package.json +++ b/package.json @@ -32,12 +32,14 @@ "llm" ], "scripts": { + "prebuild": "node scripts/gen-version.mjs", "build": "tsc -p tsconfig.json", "test": "vitest run", "test:coverage": "vitest run --coverage", "test:e2e": "vitest run e2e/copilot-reverse.e2e.test.ts tests/e2e", "test:integration": "vitest run --config vitest.integration.config.ts", "dev": "tsx src/cli/index.ts", + "changeset": "node scripts/changesets.mjs new", "prepublishOnly": "npm run build && npm run test" }, "engines": { diff --git a/scripts/changesets.mjs b/scripts/changesets.mjs new file mode 100644 index 0000000..dbb9566 --- /dev/null +++ b/scripts/changesets.mjs @@ -0,0 +1,73 @@ +// Lightweight changeset engine (no @changesets/cli dependency — overkill for a single-package repo). +// +// A "changeset" is any .md file in .changes/ (except README.md) carrying a bump level: +// +// --- +// bump: minor # patch | minor | major +// --- +// Human-readable summary of the change (goes into CHANGELOG.md). +// +// The release workflow reads `status` to decide whether (and how much) to bump, publishes, +// then calls `consume` to delete the spent changesets. Developers scaffold one with `new`. +import { readdirSync, readFileSync, writeFileSync, rmSync, existsSync, mkdirSync, appendFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const DIR = join(root, ".changes"); +const BUMP_ORDER = { patch: 1, minor: 2, major: 3 }; +const BUMP_RE = /^bump:\s*(patch|minor|major)\s*$/im; + +// Strips an optional leading `--- ... ---` front-matter fence, returning the prose body. +function stripFrontMatter(text) { + const m = text.match(/^---\n[\s\S]*?\n---\n?/); + return (m ? text.slice(m[0].length) : text).trim(); +} + +// Every non-README .md in .changes/ is a changeset. A missing/invalid bump line is a hard error — +// a typo'd level must fail loudly, not silently skip a release. +function active() { + if (!existsSync(DIR)) return []; + const out = []; + for (const f of readdirSync(DIR)) { + if (!f.endsWith(".md") || f === "README.md") continue; + const full = join(DIR, f); + const text = readFileSync(full, "utf8"); + const m = text.match(BUMP_RE); + if (!m) throw new Error(`changeset ${f} has no valid "bump: patch|minor|major" line`); + out.push({ file: full, name: f, bump: m[1].toLowerCase(), body: stripFrontMatter(text.replace(/^---\n[\s\S]*?\n---\n?/, "")) }); + } + return out; +} + +const highest = (list) => list.reduce((hi, x) => (BUMP_ORDER[x.bump] > BUMP_ORDER[hi] ? x.bump : hi), "patch"); + +const cmd = process.argv[2]; + +if (cmd === "status") { + const list = active(); + const result = { hasChangeset: list.length > 0, bump: list.length ? highest(list) : null, files: list.map((x) => x.name), bodies: list.map((x) => x.body) }; + console.log(JSON.stringify(result, null, 2)); + if (process.argv.includes("--github-output") && process.env.GITHUB_OUTPUT) { + appendFileSync(process.env.GITHUB_OUTPUT, `has=${result.hasChangeset}\nbump=${result.bump ?? ""}\n`); + } +} else if (cmd === "bodies") { + // Print just the changeset bodies (used by the release workflow to build CHANGELOG entries). + console.log(active().map((x) => x.body).filter(Boolean).join("\n\n")); +} else if (cmd === "consume") { + const list = active(); + for (const x of list) rmSync(x.file); + console.log(`consumed ${list.length} changeset(s)`); +} else if (cmd === "new") { + const bump = process.argv[3]; + if (!BUMP_ORDER[bump]) { console.error("usage: changesets.mjs new [slug...]"); process.exit(1); } + const slug = process.argv.slice(4).join("-").replace(/[^a-z0-9-]/gi, "-").toLowerCase() || "change"; + // No Date.now() name collisions in practice; if two land the same ms, the second just overwrites — fine for a scaffold. + if (!existsSync(DIR)) mkdirSync(DIR, { recursive: true }); + const file = join(DIR, `${Date.now()}-${slug}.md`); + writeFileSync(file, `---\nbump: ${bump}\n---\nDescribe the change here (this line lands in CHANGELOG.md).\n`); + console.log(`created ${file}`); +} else { + console.error("usage: changesets.mjs "); + process.exit(1); +} diff --git a/scripts/gen-version.mjs b/scripts/gen-version.mjs new file mode 100644 index 0000000..4dd0619 --- /dev/null +++ b/scripts/gen-version.mjs @@ -0,0 +1,20 @@ +// Generates src/version.ts from package.json — the single source of truth for the app version. +// Run automatically via the `prebuild` npm hook, and by the release workflow after bumping. +// CLI code can't `import "../package.json"` because rootDir is "src" (it's outside), so we +// materialize the version as an in-tree module instead. Writes only when the content changes, +// so repeated builds don't churn git. +import { readFileSync, writeFileSync, existsSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const version = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version; +const out = `// AUTO-GENERATED by scripts/gen-version.mjs from package.json — do not edit.\nexport const APP_VERSION = ${JSON.stringify(version)};\n`; + +const target = join(root, "src", "version.ts"); +if (!existsSync(target) || readFileSync(target, "utf8") !== out) { + writeFileSync(target, out); + console.log(`gen-version: wrote src/version.ts (APP_VERSION=${version})`); +} else { + console.log(`gen-version: src/version.ts already up to date (APP_VERSION=${version})`); +} diff --git a/src/cli/index.ts b/src/cli/index.ts index 562b51f..ba69057 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -22,6 +22,7 @@ import type { SetupClient } from "../tui/setup/wizard.js"; import { claudeCopilotReverseEnv } from "../tui/setup/clients.js"; import { dataDir } from "../shared/paths.js"; import { defaultConfig } from "../shared/config.js"; +import { APP_VERSION } from "../version.js"; const delay = (ms: number) => new Promise((r) => setTimeout(r, ms)); const DEFAULT_MODEL = "gpt-4o"; // a valid Copilot model id; pass-through routing uses it as-is @@ -74,7 +75,7 @@ async function launchTui(): Promise { const registry = buildRegistry({ client, quit }, endpoint, { dashboardUrl: `http://${cfg.bindHost}:${cfg.supervisorPort}/`, reportRepo: cfg.reportRepo, - appVersion: "0.1.0", + appVersion: APP_VERSION, platform: `${process.platform} node-${process.version}`, resetClient, // Re-run device-code login, then restart the worker so it picks up the new token. @@ -159,7 +160,7 @@ async function launchTui(): Promise { } const program = new Command(); -program.name("copilot-reverse").description("copilot-reverse: interactive Copilot proxy").version("0.1.0"); +program.name("copilot-reverse").description("copilot-reverse: interactive Copilot proxy").version(APP_VERSION); program.command("login").description("GitHub device-code login").action(() => runDeviceLogin(dataDir())); program.action(() => { void launchTui(); }); program.parseAsync(process.argv); diff --git a/src/core/tool-xml.ts b/src/core/tool-xml.ts new file mode 100644 index 0000000..a9e20c8 --- /dev/null +++ b/src/core/tool-xml.ts @@ -0,0 +1,104 @@ +import { randomUUID } from "node:crypto"; + +// Some models (Claude via the Copilot gateway, especially under long/tool-heavy turns) emit a tool +// call as TEXT — an inline `…` +// block — instead of via the wire's structured `tool_calls`. When that happens the proxy would +// otherwise forward the XML verbatim and the client renders it as a literal message instead of +// running the tool. This extractor recovers those inline blocks back into structured tool calls. +// +// It is a streaming state machine: feed it text deltas, and it returns ordered events — plain text +// that is safe to forward, and reconstructed tool calls. It is deliberately conservative: it only +// enters capture mode on a distinctive opening sentinel, and on a stream that ends mid-block it +// flushes the buffer back out as text (never swallows content it couldn't fully parse). + +export interface ExtractedTool { + id: string; + name: string; + input: Record; +} +export type ExtractEvent = { kind: "text"; text: string } | { kind: "tool"; tool: ExtractedTool }; + +// Opening sentinels that switch the parser into capture mode. The `antml:` namespaced variants are +// the un-stripped originals; the bare forms are what survives when the namespace prefix is dropped. +const TRIGGER_RE = /<(?:antml:)?(?:function_calls>|invoke\b)/; + +// Longest suffix of `s` that is a proper prefix of a trigger token — text we must hold back because +// it might be the front of a sentinel split across chunk boundaries (e.g. "…", "", " 0; k--) { + if (s.endsWith(t.slice(0, k))) { if (k > max) max = k; break; } + } + } + return max; +} + +// Index just past a `` (or ``) close, or -1 if not yet present in `s`. +function closeIndex(s: string, tag: string): number { + const m = new RegExp(``).exec(s); + return m ? m.index + m[0].length : -1; +} + +// A scalar parameter value is raw text in the XML; recover its intended type by trying JSON, so +// `42`/`true`/`{"a":1}` become real values while a bare command string stays a string. +function coerce(raw: string): unknown { + const v = raw.replace(/^\n/, "").replace(/\n$/, ""); + try { return JSON.parse(v); } catch { return v; } +} + +function parseInvokes(block: string): ExtractedTool[] { + const tools: ExtractedTool[] = []; + const invokeRe = /<(?:antml:)?invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/(?:antml:)?invoke>/g; + for (let m = invokeRe.exec(block); m; m = invokeRe.exec(block)) { + const [, name, body] = m; + const input: Record = {}; + const paramRe = /<(?:antml:)?parameter\s+name="([^"]+)"\s*>([\s\S]*?)<\/(?:antml:)?parameter>/g; + for (let p = paramRe.exec(body); p; p = paramRe.exec(body)) input[p[1]] = coerce(p[2]); + tools.push({ id: `call_${randomUUID().replace(/-/g, "").slice(0, 24)}`, name, input }); + } + return tools; +} + +export class ToolCallExtractor { + private buf = ""; + private capturing = false; + + feed(chunk: string): ExtractEvent[] { + this.buf += chunk; + const events: ExtractEvent[] = []; + for (;;) { + if (!this.capturing) { + const m = TRIGGER_RE.exec(this.buf); + if (!m) { + // No trigger; emit everything except a possible partial-sentinel tail. + const keep = heldBackLen(this.buf); + const emit = this.buf.slice(0, this.buf.length - keep); + if (emit) events.push({ kind: "text", text: emit }); + this.buf = keep ? this.buf.slice(this.buf.length - keep) : ""; + return events; + } + if (m.index > 0) events.push({ kind: "text", text: this.buf.slice(0, m.index) }); + this.buf = this.buf.slice(m.index); + this.capturing = true; + } + const isWrapper = /^<(?:antml:)?function_calls>/.test(this.buf); + const end = closeIndex(this.buf, isWrapper ? "function_calls" : "invoke"); + if (end < 0) return events; // incomplete block — wait for more data + const block = this.buf.slice(0, end); + for (const tool of parseInvokes(block)) events.push({ kind: "tool", tool }); + this.buf = this.buf.slice(end); + this.capturing = false; // a following re-triggers via the passthrough branch + } + } + + // Stream ended. Anything still buffered is an incomplete block we couldn't parse — emit it as + // text so nothing is silently dropped. + flush(): ExtractEvent[] { + const out: ExtractEvent[] = this.buf ? [{ kind: "text", text: this.buf }] : []; + this.buf = ""; + this.capturing = false; + return out; + } +} diff --git a/src/providers/copilot/adapter.ts b/src/providers/copilot/adapter.ts index 4666807..b9e7b95 100644 --- a/src/providers/copilot/adapter.ts +++ b/src/providers/copilot/adapter.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto"; import type { ProviderAdapter } from "../types.js"; import type { CanonicalRequest, CanonicalResponse, CanonicalChunk, CanonicalMessage, ContentBlock } from "../../core/canonical.js"; +import { ToolCallExtractor, type ExtractEvent } from "../../core/tool-xml.js"; const CHAT_URL = "https://api.githubcopilot.com/chat/completions"; interface TokenSource { get(): Promise } @@ -81,6 +82,24 @@ export class CopilotAdapter implements ProviderAdapter { let usage: { promptTokens: number; completionTokens: number; cachedTokens?: number } | undefined; const mapFinish = (f: string | null | undefined): CanonicalResponse["finishReason"] => f === "tool_calls" ? "tool_use" : f === "length" ? "length" : "stop"; + + // Some models emit a tool call as inline XML text instead of native tool_calls (more likely on + // long/tool-heavy turns). When the request has tools, route assistant text through an extractor + // that recovers those blocks into structured tool calls; otherwise text passes straight through. + const extractor = req.tools?.length ? new ToolCallExtractor() : undefined; + let extractedTool = false; + let extIdx = 100; // separate index space so recovered tools never collide with native tool_calls + const toChunks = (events: ExtractEvent[]): CanonicalChunk[] => { + const out: CanonicalChunk[] = []; + for (const ev of events) { + if (ev.kind === "text") { if (ev.text) out.push({ kind: "text", delta: ev.text, done: false }); continue; } + const index = extIdx++; + extractedTool = true; + out.push({ kind: "tool_use_start", index, id: ev.tool.id, name: ev.tool.name, done: false }); + out.push({ kind: "tool_use_delta", index, argsDelta: JSON.stringify(ev.tool.input), done: false }); + } + return out; + }; for (;;) { const { value, done } = await reader.read(); if (done) break; @@ -91,7 +110,12 @@ export class CopilotAdapter implements ProviderAdapter { const line = evt.split("\n").find((l) => l.startsWith("data: ")); if (!line) continue; const payload = line.slice(6).trim(); - if (payload === "[DONE]") { yield { kind: "done", done: true, finishReason, usage }; return; } + if (payload === "[DONE]") { + if (extractor) for (const ch of toChunks(extractor.flush())) yield ch; + if (extractedTool && finishReason === "stop") finishReason = "tool_use"; + yield { kind: "done", done: true, finishReason, usage }; + return; + } let json: any; try { json = JSON.parse(payload); } catch { continue; } // Copilot sends a final frame with empty choices carrying usage (stream_options.include_usage). @@ -101,7 +125,10 @@ export class CopilotAdapter implements ProviderAdapter { if (choice.finish_reason) finishReason = mapFinish(choice.finish_reason); const delta = choice.delta; if (!delta) continue; - if (delta.content) yield { kind: "text", delta: delta.content, done: false }; + if (delta.content) { + if (extractor) { for (const ch of toChunks(extractor.feed(delta.content))) yield ch; } + else yield { kind: "text", delta: delta.content, done: false }; + } for (const tc of delta.tool_calls ?? []) { const idx = tc.index ?? 0; if (!startedTools.has(idx) && tc.function?.name) { startedTools.add(idx); yield { kind: "tool_use_start", index: idx, id: tc.id ?? `call_${idx}`, name: tc.function.name, done: false }; } @@ -109,6 +136,8 @@ export class CopilotAdapter implements ProviderAdapter { } } } + if (extractor) for (const ch of toChunks(extractor.flush())) yield ch; + if (extractedTool && finishReason === "stop") finishReason = "tool_use"; yield { kind: "done", done: true, finishReason, usage }; } } diff --git a/src/version.ts b/src/version.ts new file mode 100644 index 0000000..3c46cb7 --- /dev/null +++ b/src/version.ts @@ -0,0 +1,2 @@ +// AUTO-GENERATED by scripts/gen-version.mjs from package.json — do not edit. +export const APP_VERSION = "0.1.0"; diff --git a/tests/core/tool-xml.test.ts b/tests/core/tool-xml.test.ts new file mode 100644 index 0000000..8ece0f1 --- /dev/null +++ b/tests/core/tool-xml.test.ts @@ -0,0 +1,81 @@ +import { describe, it, expect } from "vitest"; +import { ToolCallExtractor, type ExtractEvent } from "../../src/core/tool-xml.js"; + +// Drive the extractor with a list of chunks and collect every emitted event (feed + final flush). +function run(chunks: string[]): ExtractEvent[] { + const ex = new ToolCallExtractor(); + const events: ExtractEvent[] = []; + for (const c of chunks) events.push(...ex.feed(c)); + events.push(...ex.flush()); + return events; +} +const text = (e: ExtractEvent[]) => e.filter((x) => x.kind === "text").map((x) => (x as any).text).join(""); +const tools = (e: ExtractEvent[]) => e.filter((x) => x.kind === "tool").map((x) => (x as any).tool); + +describe("ToolCallExtractor", () => { + it("passes plain text through untouched", () => { + const e = run(["hello ", "world, no tools here"]); + expect(text(e)).toBe("hello world, no tools here"); + expect(tools(e)).toHaveLength(0); + }); + + it("extracts a single inline tool call (function_calls wrapper)", () => { + const e = run([ + 'let me check. ls -la done', + ]); + expect(text(e)).toBe("let me check. done"); + const t = tools(e); + expect(t).toHaveLength(1); + expect(t[0]).toMatchObject({ name: "Bash", input: { command: "ls -la" } }); + expect(t[0].id).toMatch(/^call_/); + }); + + it("handles a bare with no wrapper", () => { + const e = run(['utc']); + expect(tools(e)).toEqual([expect.objectContaining({ name: "now", input: { tz: "utc" } })]); + expect(text(e)).toBe(""); + }); + + it("parses multiple parameters and coerces JSON scalar types", () => { + const e = run([ + '42truehi there', + ]); + expect(tools(e)[0].input).toEqual({ count: 42, on: true, label: "hi there" }); + }); + + it("reconstructs a tool call split across many chunks (incl. a split sentinel)", () => { + const e = run(["pre /etc/hosts post']); + expect(text(e)).toBe("pre post"); + expect(tools(e)).toEqual([expect.objectContaining({ name: "Read", input: { path: "/etc/hosts" } })]); + }); + + it("does not hold back ordinary text containing a lone '<'", () => { + const e = run(["a < b and c < d"]); + expect(text(e)).toBe("a < b and c < d"); + expect(tools(e)).toHaveLength(0); + }); + + it("flushes an unclosed/incomplete block back out as text (never swallowed)", () => { + const e = run(['oops rm -rf /tmp/x']); + expect(text(e)).toBe('oops rm -rf /tmp/x'); + expect(tools(e)).toHaveLength(0); + }); + + it("handles two tool calls inside one wrapper", () => { + const e = run([ + '12', + ]); + const t = tools(e); + expect(t.map((x) => x.name)).toEqual(["a", "b"]); + expect(t[0].input).toEqual({ x: 1 }); + expect(t[1].input).toEqual({ y: 2 }); + }); + + it("still extracts when the namespace prefix is present (antml:)", () => { + // Build tags via concatenation so no literal close-tag appears in source; ns = "antml:". + const ns = "antml:", P = "parameter", I = "invoke"; + const xml = `<${ns}${I} name="Bash"><${ns}${P} name="command">echo hi`; + const e = run([xml]); + expect(tools(e)).toEqual([expect.objectContaining({ name: "Bash", input: { command: "echo hi" } })]); + }); +}); \ No newline at end of file diff --git a/tests/providers/copilot/adapter.test.ts b/tests/providers/copilot/adapter.test.ts index cf1b333..025123c 100644 --- a/tests/providers/copilot/adapter.test.ts +++ b/tests/providers/copilot/adapter.test.ts @@ -83,4 +83,54 @@ describe("CopilotAdapter", () => { for await (const _ of a.stream({ ...base, stream: true })) { /* drain */ } expect(body.stream_options).toEqual({ include_usage: true }); }); + + // --- Inline tool-call recovery: some models emit a tool call as TEXT XML instead of native + // tool_calls. The adapter must recover it into structured tool chunks when the request has tools. + // Tags are built via concatenation so no literal close-tag appears in this source file. + const O = (t: string, a = "") => `<${t}${a}>`; + const C = (t: string) => ``; + const degraded = O("function_calls") + O("invoke", ' name="Bash"') + O("parameter", ' name="command"') + "ls -la" + C("parameter") + C("invoke") + C("function_calls"); + const sseOf = (content: string) => `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n\n` + "data: [DONE]\n\n"; + const withTools: CanonicalRequest = { ...base, stream: true, tools: [{ name: "Bash", description: "run a shell command", parameters: { type: "object", properties: { command: { type: "string" } } } }] }; + + it("recovers an inline tool call emitted as text into structured tool chunks (request has tools)", async () => { + const f = vi.fn(async () => new Response(sseOf("let me check. " + degraded + " done"), { status: 200, headers: { "content-type": "text/event-stream" } })); + const a = new CopilotAdapter(tokenStore, f as unknown as typeof fetch); + const chunks: any[] = []; + for await (const c of a.stream(withTools)) chunks.push(c); + const start = chunks.find((c) => c.kind === "tool_use_start"); + const delta = chunks.find((c) => c.kind === "tool_use_delta"); + expect(start).toMatchObject({ name: "Bash" }); + expect(JSON.parse(delta.argsDelta)).toEqual({ command: "ls -la" }); + // surrounding prose still flows as text, tool call no longer leaks as text + const text = chunks.filter((c) => c.kind === "text").map((c) => c.delta).join(""); + expect(text).toBe("let me check. done"); + expect(text).not.toContain("invoke"); + // a text-emitted tool call must still report tool_use as the finish reason + expect(chunks.find((c) => c.done)?.finishReason).toBe("tool_use"); + }); + + it("recovers a tool call split across multiple SSE content deltas", async () => { + const mid = Math.floor(degraded.length / 2); + const sse = + `data: ${JSON.stringify({ choices: [{ delta: { content: degraded.slice(0, mid) } }] })}\n\n` + + `data: ${JSON.stringify({ choices: [{ delta: { content: degraded.slice(mid) } }] })}\n\n` + + "data: [DONE]\n\n"; + const f = vi.fn(async () => new Response(sse, { status: 200, headers: { "content-type": "text/event-stream" } })); + const a = new CopilotAdapter(tokenStore, f as unknown as typeof fetch); + const chunks: any[] = []; + for await (const c of a.stream(withTools)) chunks.push(c); + expect(chunks.find((c) => c.kind === "tool_use_start")).toMatchObject({ name: "Bash" }); + expect(JSON.parse(chunks.find((c) => c.kind === "tool_use_delta").argsDelta)).toEqual({ command: "ls -la" }); + }); + + it("does NOT recover when the request has no tools (degraded-looking text passes through)", async () => { + const f = vi.fn(async () => new Response(sseOf("here is the format: " + degraded), { status: 200, headers: { "content-type": "text/event-stream" } })); + const a = new CopilotAdapter(tokenStore, f as unknown as typeof fetch); + const chunks: any[] = []; + for await (const c of a.stream({ ...base, stream: true })) chunks.push(c); // base has no tools + expect(chunks.some((c) => c.kind === "tool_use_start")).toBe(false); + const text = chunks.filter((c) => c.kind === "text").map((c) => c.delta).join(""); + expect(text).toContain("invoke"); // raw text preserved verbatim, nothing eaten + }); }); From 7600f22d0c8799b12415fb3ec69971f32c15351a Mon Sep 17 00:00:00 2001 From: Wang Can Date: Tue, 23 Jun 2026 16:04:29 +0800 Subject: [PATCH 2/2] chore: add changeset for the auto-release feature (minor) Co-Authored-By: Claude Opus 4.8 (1M context) --- .../1782201841150-recover-text-tool-calls-and-auto-release.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .changes/1782201841150-recover-text-tool-calls-and-auto-release.md diff --git a/.changes/1782201841150-recover-text-tool-calls-and-auto-release.md b/.changes/1782201841150-recover-text-tool-calls-and-auto-release.md new file mode 100644 index 0000000..68107bd --- /dev/null +++ b/.changes/1782201841150-recover-text-tool-calls-and-auto-release.md @@ -0,0 +1,4 @@ +--- +bump: minor +--- +Recover tool calls that some models emit as inline XML text into structured tool calls, and add changeset-driven automatic versioning + npm publish on merge to master.