The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(plugins): transfer files through native MCP clients (#2942)
zombee099e7bc5dab94
diff --git a/.github/workflows/README.md b/.github/workflows/README.mdindex 140111be9..a966147a6 100644--- a/.github/workflows/README.md+++ b/.github/workflows/README.md@@ -463,3 +463,16 @@ Repository secrets, in Settings → Secrets and variables → Actions:- `GH_APP_PRIVATE_KEY` — GitHub App key that registers the self-hosted E2E runner- `SLACK_WEBHOOK_URL` — optional #release webhook for release dev approvals, final reports and prod apply approvals- `SLACK_DEV_DEPLOYMENT_WEBHOOK_URL` — optional #dev_deployment webhook for dev apply approvals. An empty secret skips that channel.++## Plugin release artifacts++The build workflow validates the Codex and Claude packages and saves five files for previews and publication. [Build workflow](build-plugins.yml)++The publishing workflow verifies the tag from `main` and publishes one versioned GHCR artifact. [Publishing workflow](publish-plugins.yml)++The publisher downloads the exact artifact ID for the validated build attempt. A main-only environment supplies the registry credential.++Same-version runs serialize. An identical digest can resume attestation, and a conflicting digest stops publication.++The [plugin publishing guide](../../scripts/plugins/README.md#publish-versioned-packages-to-ghcr) covers migration, registry access, retries, and downloads.+Run `make test:apps:infra` to exercise the workflow guards with real plugin packages.diff --git a/.github/workflows/build-plugins.yml b/.github/workflows/build-plugins.ymlnew file mode 100644index 000000000..6cab6fbea--- /dev/null+++ b/.github/workflows/build-plugins.yml@@ -0,0 +1,70 @@+name: Build BoxLite plugin packages++on:+ pull_request:+ paths:+ - 'plugins/boxlite/**'+ - 'scripts/plugins/**'+ - 'tests/plugins/**'+ - 'make/plugins.mk'+ - 'make/test.mk'+ - 'Makefile'+ - '.github/actions/setup-python/**'+ - '.github/workflows/build-plugins.yml'+ push:+ tags: ['boxlite-plugin-v*']+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: plugin-release-${{ github.ref }}+ cancel-in-progress: false++jobs:+ build:+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@v5+ with:+ persist-credentials: false+ - uses: ./.github/actions/setup-python+ - uses: actions/setup-node@v4+ with:+ node-version: '22'+ - name: Install pinned Claude manifest validator+ run: npm install --global @anthropic-ai/[email protected]+ - name: Build and validate both host packages+ run: make plugin:boxlite:check:cc plugin:boxlite:review-kit+ - name: Bind artifacts to the plugin version+ id: package+ shell: bash+ run: |+ set -euo pipefail+ version="$(jq -er '.version' plugins/boxlite/plugin.json)"+ if [[ "$GITHUB_EVENT_NAME" != pull_request ]]; then+ if [[ "$GITHUB_REF_TYPE" != tag || "$GITHUB_REF_NAME" != "boxlite-plugin-v$version" ]]; then+ echo 'Release builds must run on the boxlite-plugin-vVERSION tag matching plugin.json.' >&2+ exit 1+ fi+ fi+ printf 'version=%s\nartifact=boxlite-plugins-%s-%s-%s\n' \+ "$version" "$version" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT"+ cd target/plugins+ sha256sum --check SHA256SUMS+ sha256sum --check "boxlite-review-kit-$version.zip.sha256"+ - name: Save validated packages for release or PR preview+ uses: actions/upload-artifact@v4+ with:+ name: ${{ steps.package.outputs.artifact }}+ path: |+ target/plugins/boxlite-${{ steps.package.outputs.version }}.zip+ target/plugins/boxlite-marketplace-${{ steps.package.outputs.version }}.zip+ target/plugins/SHA256SUMS+ target/plugins/boxlite-review-kit-${{ steps.package.outputs.version }}.zip+ target/plugins/boxlite-review-kit-${{ steps.package.outputs.version }}.zip.sha256+ if-no-files-found: error+ compression-level: 0+ retention-days: 7diff --git a/.github/workflows/publish-plugins.yml b/.github/workflows/publish-plugins.ymlnew file mode 100644index 000000000..8b8d2feb1--- /dev/null+++ b/.github/workflows/publish-plugins.yml@@ -0,0 +1,194 @@+name: Publish BoxLite plugin packages++on:+ workflow_run:+ workflows: [Build BoxLite plugin packages]+ types: [completed]++permissions:+ contents: read+ actions: read++jobs:+ verify:+ if: >-+ github.repository == 'boxlite-ai/boxlite' &&+ github.ref == 'refs/heads/main' &&+ github.event.workflow_run.conclusion == 'success' &&+ github.event.workflow_run.head_repository.full_name == github.repository &&+ (github.event.workflow_run.event == 'push' || github.event.workflow_run.event == 'workflow_dispatch')+ runs-on: ubuntu-latest+ timeout-minutes: 5+ outputs:+ version: ${{ steps.source.outputs.version }}+ artifact_id: ${{ steps.source.outputs.artifact_id }}+ created: ${{ steps.source.outputs.created }}+ build_source: ${{ steps.source.outputs.build_source }}+ steps:+ - name: Verify build and locate its exact artifact+ id: source+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ BUILD_WORKFLOW: ${{ github.event.workflow_run.workflow_id }}+ BUILD_PATH: ${{ github.event.workflow_run.path }}+ BUILD_ID: ${{ github.event.workflow_run.id }}+ BUILD_ATTEMPT: ${{ github.event.workflow_run.run_attempt }}+ SOURCE_SHA: ${{ github.event.workflow_run.head_sha }}+ SOURCE_TAG: ${{ github.event.workflow_run.head_branch }}+ run: |+ set -euo pipefail+ repo="repos/$GITHUB_REPOSITORY"+ pattern='^boxlite-plugin-v((0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*))$'+ if [[ ! "$SOURCE_TAG" =~ $pattern ]]; then+ echo 'Expected a boxlite-plugin-vVERSION build tag.' >&2+ exit 1+ fi+ version="${BASH_REMATCH[1]}"+ if [[ ${#version} -gt 128 || ! "$SOURCE_SHA" =~ ^[a-f0-9]{40}$ ||+ ! "$BUILD_ID" =~ ^[1-9][0-9]*$ || ! "$BUILD_ATTEMPT" =~ ^[1-9][0-9]*$ ]]; then+ echo 'Invalid release build metadata.' >&2+ exit 1+ fi+ canonical_id="$(gh api "$repo/actions/workflows/build-plugins.yml" --jq '.id')"+ if [[ "$BUILD_PATH" != '.github/workflows/build-plugins.yml' || "$BUILD_WORKFLOW" != "$canonical_id" ]]; then+ echo 'The triggering run is not the canonical plugin builder.' >&2+ exit 1+ fi+ # The retired workflow can still be run from old tags until it is disabled.+ legacy_state="$(gh api "$repo/actions/workflows/423888825" --jq '.state')"+ if [[ "$legacy_state" != disabled_manually && "$legacy_state" != deleted ]]; then+ echo 'Disable and drain the legacy Release BoxLite plugin workflow before publishing.' >&2+ exit 1+ fi+ commit="$(gh api "$repo/commits/tags%2F$SOURCE_TAG")"+ if [[ "$(jq -er '.sha' <<< "$commit")" != "$SOURCE_SHA" ]]; then+ echo 'The release tag no longer points to the validated build.' >&2+ exit 1+ fi+ created="$(jq -er '.commit.committer.date | select(test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$"))' <<< "$commit")"+ ancestry="$(gh api "$repo/compare/$SOURCE_SHA...main" --jq '.status')"+ if [[ "$ancestry" != ahead && "$ancestry" != identical ]]; then+ echo 'The release tag must point to a commit on main.' >&2+ exit 1+ fi+ artifact="boxlite-plugins-$version-$BUILD_ID-$BUILD_ATTEMPT"+ artifact_id="$(gh api "$repo/actions/runs/$BUILD_ID/artifacts?name=$artifact" |+ jq -er --arg name "$artifact" '+ select(.total_count == 1 and .artifacts[0].name == $name and .artifacts[0].expired == false)+ | .artifacts[0].id | select(type == "number" and . > 0)')"+ build_source="$(jq -cn --arg commit "$SOURCE_SHA" --arg runId "$BUILD_ID" --arg runAttempt "$BUILD_ATTEMPT" \+ '{$commit, $runId, $runAttempt}')"+ printf 'version=%s\nartifact_id=%s\ncreated=%s\nbuild_source=%s\n' \+ "$version" "$artifact_id" "$created" "$build_source" >> "$GITHUB_OUTPUT"++ publish:+ if: github.ref == 'refs/heads/main'+ needs: verify+ runs-on: ubuntu-latest+ timeout-minutes: 10+ environment: boxlite-plugin-ghcr+ concurrency:+ group: boxlite-plugin-publish-${{ needs.verify.outputs.version }}+ cancel-in-progress: false+ permissions:+ contents: read+ actions: read+ id-token: write+ attestations: write+ steps:+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ with:+ artifact-ids: ${{ needs.verify.outputs.artifact_id }}+ merge-multiple: true+ github-token: ${{ github.token }}+ run-id: ${{ github.event.workflow_run.id }}+ path: packages+ - uses: oras-project/setup-oras@5e2f2482b30b0cb3e14e67f89a80c88c659a7c63 # v2.0.3+ with:+ version: 1.3.6+ - name: Publish or recover the exact OCI artifact+ id: registry+ working-directory: packages+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ GHCR_USER: ${{ vars.GHCR_PUBLISH_USER }}+ GHCR_TOKEN: ${{ secrets.GHCR_PUBLISH_TOKEN }}+ VERSION: ${{ needs.verify.outputs.version }}+ CREATED: ${{ needs.verify.outputs.created }}+ SOURCE_SHA: ${{ github.event.workflow_run.head_sha }}+ run: |+ set -euo pipefail+ repository="boxlite-ai/boxlite-plugin"+ image="ghcr.io/$repository"+ reference="$image:$VERSION"+ tag="boxlite-plugin-v$VERSION"+ review_kit="boxlite-review-kit-$VERSION.zip"+ sha256sum --strict --check SHA256SUMS "$review_kit.sha256"+ layout="$RUNNER_TEMP/plugin-oci:$VERSION"+ oras push --oci-layout --artifact-type application/vnd.boxlite.plugin.v1 \+ --annotation "org.opencontainers.image.created=$CREATED" \+ --annotation "org.opencontainers.image.revision=$SOURCE_SHA" \+ --annotation "org.opencontainers.image.version=$VERSION" \+ --annotation "org.opencontainers.image.url=$GITHUB_SERVER_URL/$GITHUB_REPOSITORY" \+ "$layout" "boxlite-$VERSION.zip:application/zip" \+ "boxlite-marketplace-$VERSION.zip:application/zip" SHA256SUMS:text/plain \+ "$review_kit:application/zip" "$review_kit.sha256:text/plain"+ digest="$(oras resolve --oci-layout "$layout")"+ if [[ ! "$digest" =~ ^sha256:[a-f0-9]{64}$ ]]; then+ echo 'ORAS did not return a manifest digest.' >&2+ exit 1+ fi+ remote_sha="$(gh api "repos/$GITHUB_REPOSITORY/commits/tags%2F$tag" --jq '.sha')"+ if [[ "$remote_sha" != "$SOURCE_SHA" ]]; then+ echo 'The plugin tag changed after build verification.' >&2+ exit 1+ fi+ if [[ -z "$GHCR_USER" || -z "$GHCR_TOKEN" ]]; then+ echo 'Configure the protected boxlite-plugin-ghcr environment first.' >&2+ exit 1+ fi+ registry_token="$(curl -fsS --get --user "$GHCR_USER:$GHCR_TOKEN" \+ --data-urlencode service=ghcr.io --data-urlencode "scope=repository:$repository:pull,push" \+ https://ghcr.io/token | jq -er '.token | strings | select(length > 0)')"+ endpoint="https://ghcr.io/v2/$repository"+ # Package ACLs must already exist before the workflow publishes any version.+ curl -fsS --output /dev/null -H "Authorization: Bearer $registry_token" "$endpoint/tags/list?n=1"+ status="$(curl -sS --head --output /dev/null --write-out '%{http_code}' \+ -H "Authorization: Bearer $registry_token" \+ -H 'Accept: application/vnd.oci.image.manifest.v1+json, application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.docker.distribution.manifest.list.v2+json' \+ "$endpoint/manifests/$VERSION")"+ registry_config="$RUNNER_TEMP/plugin-registry.json"+ trap 'rm -f -- "$registry_config"' EXIT+ printf '%s\n' "$GHCR_TOKEN" |+ oras login ghcr.io --username "$GHCR_USER" --password-stdin --registry-config "$registry_config"+ case "$status" in+ 404) oras cp --from-oci-layout --to-registry-config "$registry_config" "$layout" "$reference" ;;+ 200) printf 'Checking existing version %s before resuming.\n' "$reference" ;;+ *) printf 'Registry returned HTTP %s while checking %s.\n' "$status" "$reference" >&2; exit 1 ;;+ esac+ if [[ "$(oras resolve --registry-config "$registry_config" "$reference")" != "$digest" ]]; then+ echo 'Version points to a different OCI manifest. The workflow will not replace it.' >&2+ exit 1+ fi+ printf 'image=%s\ndigest=%s\n' "$image" "$digest" >> "$GITHUB_OUTPUT"+ - name: Attest the verified artifact+ uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3.0.0+ with:+ subject-name: ${{ steps.registry.outputs.image }}+ subject-digest: ${{ steps.registry.outputs.digest }}+ - name: Attest the verified tag build+ id: attest-source+ uses: actions/attest@daf44fb950173508f38bd2406030372c1d1162b1 # v3.0.0+ with:+ subject-name: ${{ steps.registry.outputs.image }}+ subject-digest: ${{ steps.registry.outputs.digest }}+ predicate-type: https://boxlite.ai/attestations/plugin-build-source/v1+ predicate: ${{ needs.verify.outputs.build_source }}+ - name: Report the version and verified digest+ env:+ VERSION: ${{ needs.verify.outputs.version }}+ IMAGE: ${{ steps.registry.outputs.image }}+ DIGEST: ${{ steps.registry.outputs.digest }}+ run: printf 'Plugin version `%s`\n\nDownload with `oras pull %s@%s`.\n' "$VERSION" "$IMAGE" "$DIGEST" >> "$GITHUB_STEP_SUMMARY"diff --git a/.github/workflows/release-box-images.yml b/.github/workflows/release-box-images.ymlindex 82c635147..2f5c990fa 100644--- a/.github/workflows/release-box-images.yml+++ b/.github/workflows/release-box-images.yml@@ -1,6 +1,6 @@name: Release Box Images-# The only workflow that writes to GHCR. Driven by an `apps/box-images/vMAJOR.MINOR.PATCH` tag so+# Driven by an `apps/box-images/vMAJOR.MINOR.PATCH` tag so# the box images keep a release line independent of the product version (same convention as the# existing `sdks/go/v*` tags). Publishing refuses to move a version tag that already exists, so a# rebuild can never silently replace the bytes a running box pulls.diff --git a/apps/infra/deployment/release-safety.test.ts b/apps/infra/deployment/release-safety.test.tsindex cab8b7520..c82d46069 100644--- a/apps/infra/deployment/release-safety.test.ts+++ b/apps/infra/deployment/release-safety.test.ts@@ -2071,15 +2071,15 @@ test('every workflow that selects a deployment Environment does so from an allowselected || !environment.includes('${{'),`${where} selects an Environment through an expression this guard cannot follow: ${environment}`,)- // A workflow with no dispatch has no dispatcher, and the allowlist exists- // to stop one reaching an Environment through a typo. It could not pass- // the check either way: `workflow_call` inputs take only boolean, number- // and string, so `choice` is a shape a callee cannot declare. What covers- // it instead is this same sweep reaching its caller — mdeploy-all binds- // the stage from its own allowlisted input. So the rule here is that the- // workflow really is unreachable by hand.+ // Automatic plugin publication has one fixed credential environment.+ // Reusable deploy workflows inherit an allowlisted stage from their callers.const byHand = workflow.on?.workflow_dispatch !== undefined- if (!byHand) {+ if (workflow.on?.workflow_run !== undefined) {+ assert.deepEqual(Object.keys(workflow.on), ['workflow_run'], `${where} can also be triggered outside its builder`)+ assert.equal(entry, 'publish-plugins.yml', `${where} is not an allowed automatic publisher`)+ assert.equal(environment, 'boxlite-plugin-ghcr', `${where} must use the fixed plugin environment`)+ assert.equal(job.needs, 'verify', `${where} can reach the environment without verifying its build`)+ } else if (!byHand) {assert.ok(workflow.on?.workflow_call !== undefined,`${where} is reachable by neither dispatch nor call, so nothing can run it`,@@ -2120,7 +2120,7 @@ test('every workflow that selects a deployment Environment does so from an allow// line. Listed here deliberately: the point of pinning the set is that a// seventh deploy workflow is a reviewed addition rather than one that// appeared.- ['build-apps-api-image.yml', 'deploy-infra.yml', 'deploy-release.yml', 'mbuild.yml', 'mdeploy-all.yml'],+ ['build-apps-api-image.yml', 'deploy-infra.yml', 'deploy-release.yml', 'mbuild.yml', 'mdeploy-all.yml', 'publish-plugins.yml'],'the swept set no longer matches the deployment workflows',)})diff --git a/apps/infra/scripts/plugin-release-workflow.test.mjs b/apps/infra/scripts/plugin-release-workflow.test.mjsnew file mode 100644index 000000000..48e1b4435--- /dev/null+++ b/apps/infra/scripts/plugin-release-workflow.test.mjs@@ -0,0 +1,256 @@+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { before, test } from 'node:test'+import { fileURLToPath } from 'node:url'+import { load } from 'js-yaml'++const root = fileURLToPath(new URL('../../../', import.meta.url))+const build = load(readFileSync(join(root, '.github/workflows/build-plugins.yml'), 'utf8'))+const publisher = load(readFileSync(join(root, '.github/workflows/publish-plugins.yml'), 'utf8'))+const packageScript = build.jobs.build.steps.find((step) => step.id === 'package').run+const verifyScript = publisher.jobs.verify.steps.find((step) => step.id === 'source').run+const publishScript = publisher.jobs.publish.steps.find((step) => step.id === 'registry').run+const { version } = JSON.parse(readFileSync(join(root, 'plugins/boxlite/plugin.json'), 'utf8'))+const tag = `boxlite-plugin-v${version}`+const files = [+ `boxlite-${version}.zip`,+ `boxlite-marketplace-${version}.zip`,+ 'SHA256SUMS',+ `boxlite-review-kit-${version}.zip`,+ `boxlite-review-kit-${version}.zip.sha256`,+]++// Exercise the workflow against archives produced by the real package builder.+before(() => {+ const built = spawnSync('make', ['--no-print-directory', 'plugin:boxlite:review-kit'], {+ cwd: root,+ encoding: 'utf8',+ timeout: 90_000,+ })+ assert.equal(built.status, 0, built.error?.message ?? built.stderr)+})++function directory(t) {+ const path = mkdtempSync(join(tmpdir(), 'boxlite-plugin-release-'))+ t.after(() => rmSync(path, { recursive: true, force: true }))+ return path+}++for (const [event, refType, ref, allowed] of [+ ['pull_request', 'branch', 'preview', true],+ ['push', 'tag', tag, true],+ ['workflow_dispatch', 'tag', tag, true],+ ['push', 'tag', 'boxlite-plugin-v999999.0.0', false],+ ['workflow_dispatch', 'branch', 'main', false],+]) {+ test(`plugin package version gate: ${event} ${ref}`, (t) => {+ const output = join(directory(t), 'output')+ const run = spawnSync('bash', ['-c', packageScript], {+ cwd: root,+ encoding: 'utf8',+ timeout: 10_000,+ env: {+ ...process.env,+ GITHUB_EVENT_NAME: event,+ GITHUB_REF_TYPE: refType,+ GITHUB_REF_NAME: ref,+ GITHUB_RUN_ID: '123',+ GITHUB_RUN_ATTEMPT: '2',+ GITHUB_OUTPUT: output,+ },+ })+ assert.equal(run.status, allowed ? 0 : 1, run.error?.message ?? run.stderr)+ if (allowed) {+ assert.equal(readFileSync(output, 'utf8'), `version=${version}\nartifact=boxlite-plugins-${version}-123-2\n`)+ } else {+ assert.equal(existsSync(output), false)+ }+ })+}++function execute(t, script, fault = 'none', overrides = {}) {+ const path = directory(t)+ const bin = join(path, 'bin')+ mkdirSync(bin)+ for (const file of files) copyFileSync(join(root, 'target/plugins', file), join(path, file))+ writeFileSync(join(path, 'private-evidence.json'), 'must never upload')+ if (fault === 'corrupt-package') writeFileSync(join(path, files[0]), 'damaged archive')+ const log = join(path, 'calls.jsonl')+ const output = join(path, 'output')+ writeFileSync(+ join(bin, 'fixture'),+ `#!/usr/bin/env node+const fs = require('node:fs')+const command = require('node:path').basename(process.argv[1])+const args = process.argv.slice(2)+fs.appendFileSync(process.env.CALL_LOG, JSON.stringify([command, ...args]) + '\\n')+const fault = process.env.RELEASE_FAULT+const digest = 'sha256:' + 'a'.repeat(64)+if (command === 'gh' && args[0] === 'api') {+ const endpoint = args[1]+ if (fault === 'api-error') process.exit(1)+ if (endpoint.endsWith('/workflows/build-plugins.yml')) console.log('17')+ else if (endpoint.endsWith('/workflows/423888825')) console.log(fault === 'legacy-active' ? 'active' : 'disabled_manually')+ else if (endpoint.includes('/commits/tags%2F')) {+ const sha = fault === 'moved-tag' ? 'b'.repeat(40) : process.env.SOURCE_SHA+ console.log(args.includes('--jq') ? sha : JSON.stringify({+ sha, commit: { committer: { date: process.env.CREATED } },+ }))+ } else if (endpoint.includes('/compare/')) console.log(fault === 'unmerged' ? 'diverged' : 'ahead')+ else if (endpoint.includes('/artifacts?name=')) {+ const name = new URLSearchParams(endpoint.split('?')[1]).get('name')+ console.log(JSON.stringify({+ total_count: fault === 'ambiguous-artifact' ? 2 : 1,+ artifacts: [{ id: 1234, name: fault === 'stale-artifact' ? name.replace(/-2$/, '-1') : name,+ expired: fault === 'expired-artifact' }],+ }))+ } else process.exit(2)+} else if (command === 'curl') {+ if (args.includes('https://ghcr.io/token')) {+ if (fault === 'auth-error') process.exit(1)+ console.log(JSON.stringify({ token: 'registry-fixture' }))+ } else if (args.at(-1).includes('/tags/list')) {+ if (fault === 'uninitialized-package') process.exit(22)+ } else if (args.includes('--head')) {+ console.log(fault === 'lookup-error' ? '503' :+ ['same-digest', 'conflicting-version'].includes(fault) ? '200' : '404')+ } else process.exit(2)+} else if (command === 'oras') {+ if (args[0] === 'push' && args.includes('--oci-layout')) {+ if (!args.slice(-5).every((file) => fs.existsSync(file.split(':')[0]))) process.exit(2)+ } else if (args[0] === 'login') {+ assertPassword()+ } else if (args[0] === 'cp') {+ if (fault === 'upload-error') process.exit(1)+ } else if (args[0] === 'resolve') {+ console.log(!args.includes('--oci-layout') && ['conflicting-version', 'changed-digest'].includes(fault)+ ? 'sha256:' + 'b'.repeat(64) : digest)+ } else process.exit(2)+} else process.exit(2)++function assertPassword() {+ if (!args.includes('--password-stdin') || fs.readFileSync(0, 'utf8').trim() !== 'fixture-token') {+ process.exit(2)+ }+}+`,+ { mode: 0o700 },+ )+ for (const command of ['gh', 'curl', 'oras']) symlinkSync('fixture', join(bin, command))+ const run = spawnSync('bash', ['-c', script], {+ cwd: path,+ encoding: 'utf8',+ timeout: 10_000,+ env: {+ ...process.env,+ PATH: bin + ':' + process.env.PATH,+ RELEASE_FAULT: fault,+ CALL_LOG: log,+ VERSION: version,+ CREATED: '2026-11-20T00:00:00Z',+ SOURCE_TAG: tag,+ SOURCE_SHA: 'a'.repeat(40),+ BUILD_WORKFLOW: '17',+ BUILD_PATH: '.github/workflows/build-plugins.yml',+ BUILD_ID: '555',+ BUILD_ATTEMPT: '2',+ GITHUB_REPOSITORY: 'boxlite-ai/boxlite',+ GITHUB_SERVER_URL: 'https://github.com',+ GHCR_USER: 'fixture-user',+ GHCR_TOKEN: 'fixture-token',+ RUNNER_TEMP: path,+ GITHUB_OUTPUT: output,+ ...overrides,+ },+ })+ assert.equal(run.error, undefined)+ const calls = existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').map(JSON.parse) : []+ const copies = calls.filter(([command, subcommand]) => command === 'oras' && subcommand === 'cp')+ return { run, calls, copies, output: existsSync(output) ? readFileSync(output, 'utf8') : '' }+}++test('plugin build is read-only and publication uses only the verified attempt', (t) => {+ assert.deepEqual(build.permissions, { contents: 'read' })+ assert.deepEqual(Object.keys(build.jobs), ['build'])+ assert.deepEqual(publisher.on.workflow_run.workflows, [build.name])+ assert.match(publisher.jobs.verify.if, /workflow_run.conclusion == 'success'/)+ assert.match(publisher.jobs.verify.if, /workflow_run.head_repository.full_name == github.repository/)+ assert.match(publisher.jobs.verify.if, /github.ref == 'refs\/heads\/main'/)+ assert.doesNotMatch(publisher.jobs.verify.if, /pull_request/)+ assert.equal(publisher.jobs.publish.needs, 'verify')+ assert.equal(publisher.jobs.publish.environment, 'boxlite-plugin-ghcr')+ assert.equal(publisher.jobs.publish.permissions.packages, undefined)+ assert.match(publisher.jobs.publish.steps[0].with['artifact-ids'], /needs.verify.outputs.artifact_id/)+ assert.equal(publisher.jobs.publish.steps[0].with['merge-multiple'], true)++ const { run, calls, output } = execute(t, verifyScript)+ assert.equal(run.status, 0, run.stderr)+ const settings = new Map(output.trim().split('\n').map((line) => line.split(/=(.*)/s).slice(0, 2)))+ assert.equal(settings.get('version'), version)+ assert.equal(settings.get('artifact_id'), '1234')+ assert.equal(settings.get('created'), '2026-11-20T00:00:00Z')+ assert.ok(settings.has('build_source'), 'verifier provides the tagged build identity to the signer')+ assert.deepEqual(JSON.parse(settings.get('build_source')), { commit: 'a'.repeat(40), runId: '555', runAttempt: '2' })+ const sourceAttestation = publisher.jobs.publish.steps.find((step) => step.id === 'attest-source')+ assert.match(sourceAttestation.uses, /^actions\/attest@/)+ assert.deepEqual(sourceAttestation.with, {+ 'subject-name': '${{ steps.registry.outputs.image }}',+ 'subject-digest': '${{ steps.registry.outputs.digest }}',+ 'predicate-type': 'https://boxlite.ai/attestations/plugin-build-source/v1',+ predicate: '${{ needs.verify.outputs.build_source }}',+ })+ assert.ok(calls.some((args) => args.includes(+ `repos/boxlite-ai/boxlite/actions/runs/555/artifacts?name=boxlite-plugins-${version}-555-2`,+ )))+})++for (const fault of ['legacy-active', 'api-error', 'moved-tag', 'unmerged', 'stale-artifact', 'expired-artifact', 'ambiguous-artifact']) {+ test(`plugin verifier rejects ${fault}`, (t) => {+ const { run, calls, output } = execute(t, verifyScript, fault)+ assert.notEqual(run.status, 0)+ assert.equal(output, '')+ assert.ok(calls.every(([command]) => command === 'gh'))+ })+}++test('plugin verifier rejects a same-name workflow with a different identity', (t) => {+ const { run, output } = execute(t, verifyScript, 'none', { BUILD_WORKFLOW: '18' })+ assert.equal(run.status, 1)+ assert.match(run.stderr, /canonical plugin builder/)+ assert.equal(output, '')+})++for (const [fault, expectedCopies] of [['none', 1], ['same-digest', 0]]) {+ test(`plugin publisher verifies five OCI layers and emits the digest on ${fault}`, (t) => {+ const { run, calls, copies, output } = execute(t, publishScript, fault)+ assert.equal(run.status, 0, run.stderr)+ const layout = calls.find(([command, subcommand]) => command === 'oras' && subcommand === 'push')+ assert.ok(layout.includes('--oci-layout'))+ assert.ok(layout.includes('org.opencontainers.image.created=2026-11-20T00:00:00Z'))+ assert.deepEqual(layout.slice(-5).map((file) => file.split(':')[0]), files)+ assert.equal(copies.length, expectedCopies)+ if (expectedCopies) assert.equal(copies[0].at(-1), `ghcr.io/boxlite-ai/boxlite-plugin:${version}`)+ assert.equal(output, `image=ghcr.io/boxlite-ai/boxlite-plugin\ndigest=sha256:${'a'.repeat(64)}\n`)+ })+}++for (const [fault, expectedCopies] of [+ ['moved-tag', 0],+ ['corrupt-package', 0],+ ['auth-error', 0],+ ['uninitialized-package', 0],+ ['lookup-error', 0],+ ['conflicting-version', 0],+ ['upload-error', 1],+ ['changed-digest', 1],+]) {+ test(`plugin publisher fails without an attestation digest on ${fault}`, (t) => {+ const { run, copies, output } = execute(t, publishScript, fault)+ assert.notEqual(run.status, 0)+ assert.equal(copies.length, expectedCopies)+ assert.equal(output, '')+ })+}diff --git a/plugins/boxlite/README.md b/plugins/boxlite/README.mdindex 3fd2d114b..3b2213752 100644--- a/plugins/boxlite/README.md+++ b/plugins/boxlite/README.md@@ -12,6 +12,8 @@ The plugin preserves your choice rather than switching backends when authenticat## Install+For versioned marketplace ZIPs, use the [GHCR download and verification guide](https://github.com/boxlite-ai/boxlite/blob/main/scripts/plugins/README.md#download-and-verify).+Extract the standalone marketplace ZIP, then use its absolute directory:```sh@@ -33,7 +35,10 @@ An explicit request such as **Run hello locally with BoxLite** selects Local dir## Use[Setup](skills/boxlite-setup/SKILL.md) verifies your chosen connection, then [operations](skills/boxlite/SKILL.md) resumes your original task.-Cloud work uses discovered MCP tools for Boxes, executions, and archive transfer; no BoxLite CLI is required for either cloud authentication method.++For cloud files, select an existing MCP connection. Supply the Box ID and both paths to the Claude transfer tools or the Codex helper. The host sends the file-tool request using that connection’s credentials.++See [file transfer](skills/boxlite/references/cloud.md#files) for commands and connection prerequisites.[API-key setup](skills/boxlite-setup/references/cloud-auth.md) uses the host's private credential reference, never a token bundled in the plugin.[Local setup](skills/boxlite/references/local.md) pins a dedicated runtime home and clears inherited cloud routing.@@ -49,10 +54,17 @@ Box updates retain the same identity and data, and cleanup targets only explicit## Data and credentials-The plugin sends requested cloud tool arguments, commands, and files only to the declared BoxLite service.+The plugin sends requested cloud tool arguments, commands and files to the selected BoxLite deployment.Local runs the CLI on your execution host; runtime image pulls and commands you request may access their selected registries or networks.There is no plugin telemetry, background service, bundled credential store, or installation hook.+The file helper reads reviewed sources and writes requested downloads; it requires Python and host filesystem access.+The helper uses existing MCP contracts without a BoxLite CLI dependency, new server API, transfer cache or additional checksum/readback step.+Directory uploads include hidden entries and preserve symbolic links as links.++At session start, the marketplace plugin registers the Claude upload and download tools. Claude authorizes each request using the connection, Box ID and both paths.+The handler then starts the bundled Python archive worker, calls the selected MCP connection and returns a short receipt.+OAuth credentials stay with the host; API keys stay in the user's chosen private host environment.Keep mode selection, Box IDs, runtime homes, and app secrets outside the plugin and version control.Only upload reviewed source, excluding developer credentials, private state, caches, and unrequested persistent data.@@ -71,6 +83,13 @@ To roll back, install a retained verified package version, recheck its supportedThese files are a release candidate, not evidence of an approved public listing.OpenAI's public submission connection is OAuth; API-key setup currently requires a supported native host, and optional local execution needs platform eligibility review.+Both transfer entry points call the existing remote file tools through the selected host.++Codex starts its app-server with the selected configuration. Claude uses the connection in the current session.++Native API-key acceptance does not establish OAuth file-transfer acceptance.+The marketplace targets both clients; directory review must still confirm the execution surface and publisher eligibility.+Claude distribution requires the plugin repository plus a companion listing for the same hosted MCP service.See [release and review instructions](https://github.com/boxlite-ai/boxlite/blob/main/scripts/plugins/README.md) for artifact generation and unresolved acceptance gates.diff --git a/plugins/boxlite/hooks/hooks.json b/plugins/boxlite/hooks/hooks.jsonnew file mode 100644index 000000000..49d8ffb03--- /dev/null+++ b/plugins/boxlite/hooks/hooks.json@@ -0,0 +1 @@+{"modules":["./transfer.js"]}diff --git a/plugins/boxlite/hooks/transfer.js b/plugins/boxlite/hooks/transfer.jsnew file mode 100644index 000000000..0ff91b097--- /dev/null+++ b/plugins/boxlite/hooks/transfer.js@@ -0,0 +1,136 @@+// Claude runs these handlers after the session authorizes the registered tool and its input.++class TransferError extends Error {}++async function archive($, operation, path, input) {+ const worker = $.plugin.root + '/skills/boxlite/scripts/archive_worker.py'+ const process = $.process.spawn({argv: ['python3', '-E', '-s', '-B', worker, operation, path], input})+ const chunks = []+ let error = ''+ try {+ for (;;) {+ const event = await process.next()+ if (event.done) {+ if (event.value.code === 2) throw new TransferError(error.trim() || 'Archive operation failed')+ if (event.value.code !== 0) throw new TransferError('Archive worker failed')+ return chunks.join('')+ }+ const {stream, text} = event.value+ if (stream === 'stderr') {+ error = (error + text).slice(0, 512)+ } else {+ chunks.push(text)+ }+ }+ } finally {+ await process.return()+ }+}++function fileErrorMessage(tool, result) {+ const item = Array.isArray(result.content) && result.content.length === 1 ? result.content[0] : null+ const text = item?.type === 'text' && typeof item.text === 'string' ? item.text : ''+ let detail = result.structuredContent+ if (detail == null && text.trimStart().startsWith('{')) {+ try { detail = JSON.parse(text) } catch { /* Unrecognized server text uses the generic message. */ }+ }+ if (detail?.statusCode === 403 || text === 'HTTP 403') {+ return tool === 'downloadFiles'+ ? 'Server refused the download (HTTP 403). Check connection permissions. BoxLite Cloud requires write:boxes'+ : 'Server refused the upload (HTTP 403). Check permissions for the selected connection'+ }+ const code = detail?.error?.code+ if (text === 'Invalid value for path argument box_id') return 'Invalid Box ID. Check the selected Box ID'+ if (code === 'invalid_argument') return 'Invalid transfer arguments. Check the remote path'+ if (code === 'not_found' || detail?.statusCode === 404 || text === 'HTTP 404') {+ return 'Resource not found. Check the Box ID and remote path'+ }+ if (code === 'invalid_state') return 'Transfer unavailable in the current Box state. Check the Box status'+ if (tool === 'downloadFiles' && /^(?:GET \/\S+ returned more than 8388608 bytes|Response of [0-9]+ bytes exceeds the 8388608-byte limit)$/.test(text)) {+ return 'Download exceeds the 8 MiB limit. Select fewer or smaller files'+ }+ return tool + ' failed on the selected connection; completion is unknown'+}++async function callFileTool($, connection, tool, input) {+ let result+ try {+ result = await $.mcp.call(connection, tool, input)+ } catch {+ // Host exceptions can contain the raw request or response.+ }+ if (result && !result.isError) return result+ if (result?.isError === true) throw new TransferError(fileErrorMessage(tool, result))+ throw new TransferError(tool + ' failed on the selected connection; completion is unknown')+}++async function upload($, args) {+ const body = await archive($, 'pack', args.local_source)+ const result = await callFileTool($, args.connection, 'uploadFiles', {+ box_id: args.box_id, path: args.remote_destination, body_base64: body,+ })+ const content = result.content+ if (content?.length !== 1 || content[0]?.type !== 'text' || content[0].text !== 'HTTP 204') {+ throw new TransferError('uploadFiles returned no HTTP 204 acknowledgment; completion is unknown')+ }+ return args.remote_destination+}++async function download($, args) {+ await archive($, 'check', args.local_destination)+ const started = Date.now()+ const result = await callFileTool($, args.connection, 'downloadFiles', {+ box_id: args.box_id, path: args.remote_source,+ })+ const finished = Date.now()+ let data = result.structuredContent+ if (data == null && result.content?.length === 1 && result.content[0]?.type === 'text') {+ const text = result.content[0].text+ const notice = /^Error: result \([\d,]+ characters(?: across [\d,]+ lines?)?\) exceeds maximum allowed tokens\. Output has been saved to ([^\n]+)\.\nFormat: (?:JSON|Plain text)/.exec(text)+ if (notice) {+ const {transcriptPath} = await $.session.info()+ const receipt = {transcriptPath, connection: args.connection, started, finished, path: notice[1]}+ await archive($, 'save-result', args.local_destination, JSON.stringify(receipt))+ return args.local_destination+ }+ try {+ data = JSON.parse(text)+ } catch {+ throw new TransferError('downloadFiles returned malformed archive metadata')+ }+ }+ if (typeof data?.base64 !== 'string') {+ throw new TransferError('downloadFiles returned no archive bytes')+ }+ await archive($, 'save', args.local_destination, data.base64)+ return args.local_destination+}++const operations = [+ {name: 'upload', paths: ['local_source', 'remote_destination'],+ description: 'Upload a local file or directory to a Box. Supply the selected MCP connection and absolute paths.'},+ {name: 'download', paths: ['remote_source', 'local_destination'],+ description: 'Download from a Box into a new local directory. Supply the selected MCP connection and absolute paths.'},+]++export function register(on) {+ on('session.start', async ($, event, next) => {+ for (const {name, paths, description} of operations) {+ const required = ['connection', 'box_id', ...paths]+ const properties = Object.fromEntries(required.map(key => [key, {type: 'string', minLength: 1}]))+ await $.tool.register({name, description, inputSchema: {type: 'object', properties, required, additionalProperties: false}})+ }+ return next(event)+ })+ for (const {name, paths} of operations) {+ on('tool.run', {tool: 'mcp__boxlite__' + name}, async ($, args) => {+ if (!paths.every(key => args[key]?.startsWith('/'))) return {deny: 'Use absolute transfer paths'}+ try {+ const destination = name === 'upload' ? await upload($, args) : await download($, args)+ return {result: JSON.stringify({operation: name, status: 'completed', box_id: args.box_id, destination})}+ } catch (error) {+ return {deny: error instanceof TransferError ? error.message : 'BoxLite transfer failed; completion is unknown'}+ }+ }).catch(() => ({deny: 'BoxLite transfer failed; completion is unknown'}))+ }+}diff --git a/plugins/boxlite/mcp.json b/plugins/boxlite/mcp.jsonindex f9f3fe397..f1155fe25 100644--- a/plugins/boxlite/mcp.json+++ b/plugins/boxlite/mcp.json@@ -3,7 +3,15 @@"mcpServers": {"boxlite": {"type": "streamable-http",- "url": "https://api.boxlite.ai/mcp"+ "url": "https://api.boxlite.ai/mcp",+ "extensions": {+ "com.openai": {+ "auth": {+ "type": "oauth",+ "client": {"mode": "cimd"}+ }+ }+ }}}}diff --git a/plugins/boxlite/skills/boxlite-setup/SKILL.md b/plugins/boxlite/skills/boxlite-setup/SKILL.mdindex b7b8ca1a3..041fcc088 100644--- a/plugins/boxlite/skills/boxlite-setup/SKILL.md+++ b/plugins/boxlite/skills/boxlite-setup/SKILL.md@@ -55,6 +55,16 @@ Follow [local setup](../boxlite/references/local.md) and verify the runtime on tNever request cloud login or call cloud tools; disable the unused cloud connection if the host attempts automatic connection.A web-only host cannot provide Local mode: explain the missing capability and preserve the choice.+## File transfer prerequisites++Cloud file transfer needs Python 3.9+ and host shell/filesystem access.+Claude Code must load the marketplace plugin's registered upload and download tools in the current session.++Use the [file workflow](../boxlite/references/cloud.md#files) to select an existing Codex or Claude MCP connection.+The selected host owns credentials and sends MCP requests; the helper handles local bytes and host-control messages only.++If no programmatic transport is available for that connection, report file transfer unavailable without changing authentication or asking the model to copy base64.+## Continue the taskReport the selected mode, connection or runtime home, and observed setup check; keep sensitive account details private.diff --git a/plugins/boxlite/skills/boxlite-setup/references/cloud-auth.md b/plugins/boxlite/skills/boxlite-setup/references/cloud-auth.mdindex 2536f8eff..3d92106a3 100644--- a/plugins/boxlite/skills/boxlite-setup/references/cloud-auth.md+++ b/plugins/boxlite/skills/boxlite-setup/references/cloud-auth.md@@ -48,17 +48,19 @@ Do not disable unrelated plugins.## API key in Claude Code-After the same explicit key setup, add a local-scope entry with a literal placeholder:+After the same explicit key setup, add a user-scope entry with a literal placeholder. This keeps the connection private to your Claude user account and makes it available across projects.```shtest -n "${BOXLITE_API_KEY:-}"-claude mcp add-json --scope local boxlite-api '{"type":"http","url":"https://api.boxlite.ai/mcp","headers":{"Authorization":"Bearer ${BOXLITE_API_KEY}"}}'+claude mcp add-json --scope user boxlite-api '{"type":"http","url":"https://api.boxlite.ai/mcp","headers":{"Authorization":"Bearer ${BOXLITE_API_KEY}"}}'```Run the second command only after the first succeeds; single quotes prevent expansion of the key into argv.Verify in `/mcp` that `boxlite-api` is active and the bundled OAuth entry is deduplicated or disabled.Never write an expanded header into shared configuration, plugin caches, repositories, or review packages.+If a local entry already uses this name, verify the selected connection before transferring because Claude gives the local entry precedence in the original project. A project-only connection can be used directly by its name in the current session.+## Verify and switchInspect schemas and call `listBoxes`; discover `getCurrentPrincipal` through the catalog when identity verification is needed.diff --git a/plugins/boxlite/skills/boxlite/SKILL.md b/plugins/boxlite/skills/boxlite/SKILL.mdindex e8aa012b2..7a45a75c5 100644--- a/plugins/boxlite/skills/boxlite/SKILL.md+++ b/plugins/boxlite/skills/boxlite/SKILL.md@@ -15,7 +15,11 @@ Local ------------------------> local launcher --> embedded runtimeBoth cloud modes follow [cloud operations](references/cloud.md) through the selected host MCP connection.Local follows [local operations](references/local.md) through the independent runtime launcher.-Never substitute CLI, shell HTTP, another mode, or another account for a failed cloud MCP call.++For cloud files, use the current Claude session’s BoxLite upload/download tools or the packaged Codex helper. Pass the selected MCP connection, Box ID and both paths.++For downloads, choose a nonexistent destination and do not create it first; the helper creates it.+Never substitute ad hoc HTTP, another mode, or another account for a failed cloud MCP call.## Task contractdiff --git a/plugins/boxlite/skills/boxlite/references/cloud.md b/plugins/boxlite/skills/boxlite/references/cloud.mdindex de165ffd2..24716ae6b 100644--- a/plugins/boxlite/skills/boxlite/references/cloud.md+++ b/plugins/boxlite/skills/boxlite/references/cloud.md@@ -1,7 +1,7 @@# Shared cloud operationsBoth cloud authentication modes use `https://api.boxlite.ai/mcp`, the same discovered tools, and this workflow.-Only the credential and its granted permissions differ; never use BoxLite CLI or shell HTTP for these operations.+Only the credential and its granted permissions differ. Lifecycle and execution use native MCP; the packaged file helper calls the existing MCP file tools programmatically.## Create and execute@@ -28,13 +28,66 @@ For incomplete output, retain the execution ID and inspect `getExecution`; never## Files-`uploadFiles` takes a base64 tar archive and destination; `downloadFiles` returns an archive.-Exclude credentials, `.env*`, `.git`, private plugin state, caches, and persistent data unless explicitly requested.-Reject unreviewed symlinks and special files in deployment sources.+Use Python 3.9+ on the host and the exact configured MCP connection name and Box ID.+Supply absolute paths on both ends. Keep archive bytes inside the transfer tools.-Stay within discovered limits, currently 8 MiB of archive bytes; do not echo large base64 payloads to the user.-Upload into a fresh, uniquely named release directory to keep application releases separate from persistent data.-Small text files can use bounded execution with explicit argv; `read_file`, `write_file`, and `list_dir` are not BoxLite MCP tools.+### Claude Code++Use the BoxLite marketplace plugin's tools from the current session. For example:++| Tool | Arguments |+| --- | --- |+| `mcp__boxlite__upload` | `{"connection":"boxlite-api","box_id":"BOX_ID","local_source":"/home/user/report.csv","remote_destination":"/workspace/report.csv"}` |+| `mcp__boxlite__download` | `{"connection":"boxlite-api","box_id":"BOX_ID","remote_source":"/workspace/report.csv","local_destination":"/home/user/new-download"}` |++Claude applies its current permission mode and rules to the requested operation, connection, Box and paths.+Configure tool rules on these two transfer tools. An authorized directory transfer covers its contents.++After authorization, the plugin runs Python for local archive I/O and calls the selected connection's `uploadFiles` or `downloadFiles` directly.+Claude receives a short receipt. Claude Code can retain large downloads in its private session storage.++The worker accepts a saved result only when it can identify a single matching download on this connection in the current session during the call. If the transfer tools or selected connection are unavailable, report that to the user.++### Codex++Use the packaged helper with the selected server in the Codex app-server configuration.+Resolve `SKILL_DIR` to this installed skill.++```sh+python3 SKILL_DIR/scripts/transfer.py --host codex --server SELECTED_SERVER upload --box BOX_ID --source /absolute/reviewed-source --destination /workspace/new-release+python3 SKILL_DIR/scripts/transfer.py --host codex --server SELECTED_SERVER download --box BOX_ID --source /workspace/new-release/. --destination /absolute/new-download+```++### Transfer results++A successful transfer returns a receipt with `status: completed`. The Codex command also exits with code zero.++Upload requires the existing server's `HTTP 204` acknowledgment; an empty or unexpected tool result leaves completion unknown.+It makes one file-tool call and does not download files again or compute a checksum.++For HTTP 403, check the selected connection's permissions. BoxLite Cloud requires `write:boxes` for both uploads and downloads.++Invalid arguments, missing resources and Box state conflicts have specific messages. If a download exceeds the MCP response limit of 8 MiB, select fewer or smaller files.++The helper never retries, changes credentials or leaves a transfer-ticket cache; after a failure, inspect possible destination effects before a new attempt.++Uploads include the selected directory’s contents, including hidden files. Symbolic links travel as links, preserving their target text.++Codex and Claude stop an upload before calling MCP if its tar archive would exceed 8 MiB, including headers and padding. This limit applies before Base64 encoding.++Downloads preserve GNU sparse files from the Box. The helper writes the stored data ranges and recreates holes without imposing a limit on the file's logical size.++Downloads require a new local directory, an existing parent and a filesystem that supports atomic directory placement.+The helper writes with private permissions and places the directory at the requested path only after the full archive has been written.++If the parent moved during placement, the helper reports that the download was written and the requested path changed.++A guest source ending in `/.` downloads directory contents. Other paths retain the directory name.++A single-file upload can name a destination file and follows the server's overwrite behavior.+Uploads and downloads preserve only the owner's read, write and execute bits (`mode & 0700`). Downloads apply these permissions after writing the regular or sparse file.++Guest mount paths such as `/tmp` may not support file transfer. Use a suitable rootfs path such as `/workspace`.## Deploy and updatediff --git a/plugins/boxlite/skills/boxlite/scripts/archive_worker.py b/plugins/boxlite/skills/boxlite/scripts/archive_worker.pynew file mode 100644index 000000000..195a26848--- /dev/null+++ b/plugins/boxlite/skills/boxlite/scripts/archive_worker.py@@ -0,0 +1,61 @@+"""Archive I/O for an authorized Claude transfer. File bytes use standard streams."""+import json+import os+from pathlib import Path+import re+import sys++from transfer import TransferError, pack_source, save_archive+++def saved_archive(receipt):+ # A server can imitate a persistence notice. Select its file from the host-reported session.+ transcript = Path(receipt['transcriptPath'])+ directory = transcript.with_suffix('') / 'tool-results'+ path = Path(receipt['path'])+ if (not transcript.is_absolute() or transcript.suffix != '.jsonl' or '..' in transcript.parts+ or not path.is_absolute() or '..' in path.parts):+ raise TransferError('Invalid saved download result')+ server = re.sub(r'[^A-Za-z0-9_-]', '_', receipt['connection'])+ name_pattern = re.compile(r'mcp-' + re.escape(server) + r'-downloadFiles-(\d+)-[a-z0-9]+\.txt')+ candidate = None+ for entry in directory.glob('*.txt'):+ match = name_pattern.fullmatch(entry.name)+ if match and receipt['started'] <= int(match[1]) <= receipt['finished']:+ if candidate is not None:+ raise TransferError('Saved result cannot be identified for this download')+ candidate = entry+ if candidate is None or candidate.resolve() != path.resolve():+ raise TransferError('Saved result cannot be identified for this download')+ value = json.loads(candidate.read_bytes())+ if not isinstance(value, dict) or not isinstance(value.get('base64'), str):+ raise TransferError('Saved result is missing archive bytes')+ return value['base64']+++def main(operation, path):+ if not Path(path).is_absolute():+ raise TransferError('Use an absolute local path')+ if operation == 'pack':+ sys.stdout.write(pack_source(path))+ elif operation == 'check':+ if os.path.lexists(path):+ raise TransferError('Choose a new local download directory; the destination already exists')+ elif operation == 'save':+ save_archive(sys.stdin.buffer.read(), path)+ elif operation == 'save-result':+ receipt = json.loads(sys.stdin.buffer.read(32768))+ save_archive(saved_archive(receipt), path)+ else:+ raise TransferError('Unknown archive operation')+++if __name__ == '__main__':+ try:+ main(*sys.argv[1:])+ except (ValueError, TransferError) as error:+ print(str(error), file=sys.stderr)+ sys.exit(2)+ except OSError as error:+ print(error.strerror or 'Archive I/O failed', file=sys.stderr)+ sys.exit(2)diff --git a/plugins/boxlite/skills/boxlite/scripts/transfer.py b/plugins/boxlite/skills/boxlite/scripts/transfer.pynew file mode 100644index 000000000..6b9e64e6b--- /dev/null+++ b/plugins/boxlite/skills/boxlite/scripts/transfer.py@@ -0,0 +1,89 @@+#!/usr/bin/env python3+"""Move files through existing MCP tools without exposing archive base64 to the model."""+import argparse+import base64+import binascii+import json+import os+from pathlib import Path+import sys++from transfer_archive import Archive+from transfer_hosts import CodexHost, TransferError+++def pack_source(source):+ archive = Archive.snapshot(source).encode()+ return base64.b64encode(archive).decode('ascii')+++def upload(client, box, source, destination):+ result = client.call('uploadFiles', {'box_id': box, 'path': destination,+ 'body_base64': pack_source(source)})+ content = result.get('content')+ # The existing server represents a successful, empty REST upload response as HTTP 204.+ if (not isinstance(content, list) or len(content) != 1 or not isinstance(content[0], dict)+ or content[0].get('type') != 'text' or content[0].get('text') != 'HTTP 204'):+ raise TransferError('uploadFiles returned no HTTP 204 acknowledgment; completion is unknown')+ return {'operation': 'upload', 'status': 'completed', 'box_id': box, 'destination': destination}+++def download(client, box, source, destination):+ if os.path.lexists(destination):+ raise TransferError('Choose a new local download directory; the destination already exists')+ result = client.call('downloadFiles', {'box_id': box, 'path': source})+ value = result.get('structuredContent')+ if value is None:+ content = result.get('content', [])+ if (not isinstance(content, list) or len(content) != 1 or not isinstance(content[0], dict)+ or content[0].get('type') != 'text' or not isinstance(content[0].get('text'), str)):+ raise TransferError('MCP download did not return its archive object')+ try:+ value = json.loads(content[0]['text'])+ except ValueError:+ raise TransferError('MCP download returned malformed archive metadata') from None+ if not isinstance(value, dict) or not isinstance(value.get('base64'), str):+ raise TransferError('MCP download is missing archive bytes')+ save_archive(value['base64'], destination)+ return {'operation': 'download', 'status': 'completed', 'box_id': box,+ 'destination': str(Path(destination).absolute())}+++def save_archive(encoded, destination):+ try:+ raw = base64.b64decode(encoded, validate=True)+ except (binascii.Error, ValueError):+ raise TransferError('MCP download returned invalid base64') from None+ Archive.decode(raw).save(destination)+++def absolute_path(value):+ if not value.startswith('/'):+ raise argparse.ArgumentTypeError('expected an absolute path')+ return value+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--host', choices=('codex',), required=True)+ parser.add_argument('--server', required=True, help='Existing selected host MCP connection name')+ parser.add_argument('operation', choices=('upload', 'download'))+ parser.add_argument('--box', required=True)+ parser.add_argument('--source', required=True, type=absolute_path)+ parser.add_argument('--destination', required=True, type=absolute_path)+ args = parser.parse_args()+ try:+ with CodexHost(args.server) as client:+ operation = upload if args.operation == 'upload' else download+ result = operation(client, args.box, args.source, args.destination)+ print(json.dumps(result, separators=(',', ':')))+ return 0+ except Exception as error:+ # Raw transport exceptions and tool results can contain credentials or archive data.+ detail = str(error) if isinstance(error, (TransferError, ValueError)) else type(error).__name__+ print('BoxLite file transfer failed: ' + detail + '. No automatic retry.', file=sys.stderr)+ return 1+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/plugins/boxlite/skills/boxlite/scripts/transfer_archive.py b/plugins/boxlite/skills/boxlite/scripts/transfer_archive.pynew file mode 100644index 000000000..7778979e4--- /dev/null+++ b/plugins/boxlite/skills/boxlite/scripts/transfer_archive.py@@ -0,0 +1,341 @@+"""Snapshot file trees and publish validated tar contents into a new directory."""+from contextlib import suppress+from dataclasses import dataclass+import ctypes+import errno+import io+import os+from pathlib import Path, PurePosixPath+import secrets+import stat+import sys+import tarfile+++MAX_UPLOAD_BYTES = 8 * 1024 * 1024+++def _padded(size, alignment):+ return size + (-size % alignment)+++def _tar_member(name, kind, size=0, linkname='', mode=0o600):+ member = tarfile.TarInfo(name)+ member.type = kind+ member.size = size+ member.linkname = linkname+ member.mode = mode+ return member+++def safe_name(name):+ if not isinstance(name, str) or not name or '\\' in name or any(ord(c) < 32 for c in name):+ raise ValueError('Invalid archive path')+ parts = name.split('/')+ if name.startswith('/') or '..' in parts:+ raise ValueError('Unsafe archive path')+ return str(PurePosixPath(name))+++def open_node(name, parent=None, directory=False):+ flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK+ if directory:+ flags |= os.O_DIRECTORY+ return os.open(name, flags, dir_fd=parent)+++@dataclass(frozen=True)+class SymbolicLink:+ target: str+++class _DownloadTarInfo(tarfile.TarInfo):+ def _proc_member(self, archive):+ # Keep the on-wire end before tarfile substitutes a sparse logical size+ # or advances offset_data past an in-band GNU sparse map.+ stored_size = self.size+ member = super()._proc_member(archive)+ if member is self:+ self.stored_end = self.offset_data + stored_size+ return member+++@dataclass+class _SparseFile:+ size: int+ extents: list[tuple[int, memoryview]]++ @classmethod+ def decode(cls, member, raw, next_header):+ pos = member.offset_data+ end = member.stored_end+ if not pos <= end <= len(raw) or _padded(end, tarfile.BLOCKSIZE) != next_header:+ raise ValueError('Truncated sparse archive member')+ extents = []+ previous_end = 0+ for offset, length in member.sparse:+ if offset < 0 or length < 0 or offset + length > member.size:+ raise ValueError('Invalid sparse extent')+ if not length: # GNU headers may have unused (0, 0) slots.+ continue+ if offset < previous_end or pos + length > end:+ raise ValueError('Invalid sparse extent')+ extents.append((offset, raw[pos:pos + length]))+ previous_end = offset + length+ pos += length+ if pos != end:+ raise ValueError('Sparse extents do not match stored size')+ return cls(member.size, extents)++ def write(self, stream):+ for offset, chunk in self.extents:+ stream.seek(offset)+ stream.write(chunk)+ stream.truncate(self.size)+++def _publish_directory(source_parent, source, target_parent, target):+ libc = ctypes.CDLL(None, use_errno=True)+ if sys.platform == 'darwin':+ rename = getattr(libc, 'renameatx_np', None)+ flag = 0x4 # RENAME_EXCL+ else:+ rename = getattr(libc, 'renameat2', None)+ flag = 1 # RENAME_NOREPLACE+ if rename is None:+ raise ValueError('Atomic download placement is unavailable on this host')+ rename.argtypes = (ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint)+ rename.restype = ctypes.c_int+ if rename(source_parent, os.fsencode(source), target_parent, os.fsencode(target), flag):+ error = ctypes.get_errno()+ if error in (errno.ENOSYS, errno.ENOTSUP, errno.EINVAL):+ raise ValueError('Destination filesystem does not support atomic download placement')+ raise OSError(error, os.strerror(error), target)+++def _clear_staging_directory(directory):+ for name in os.listdir(directory):+ mode = os.stat(name, dir_fd=directory, follow_symlinks=False).st_mode+ if not stat.S_ISDIR(mode):+ os.unlink(name, dir_fd=directory)+ continue+ # Publication can fail after restrictive directory modes have been restored.+ if mode & 0o700 != 0o700:+ os.chmod(name, 0o700, dir_fd=directory, follow_symlinks=False)+ child = open_node(name, directory, directory=True)+ try:+ _clear_staging_directory(child)+ finally:+ os.close(child)+ os.rmdir(name, dir_fd=directory)+++class Archive:+ """Own a validated in-memory tree and expose snapshot, encode and save operations."""+ def __init__(self):+ self.parents = set()+ self.files = {}+ self.directory_modes = {}+ self.single_file = False+ self.file_modes = {}++ def add(self, name, data=None, *, mode=None):+ name = safe_name(name)+ if name == '.' and data is not None:+ raise ValueError('Archive root must be a directory')+ if name in self.files or (name != '.' and name in self.directory_modes):+ raise ValueError('Duplicate archive path')+ parents = {str(parent) for parent in PurePosixPath(name).parents if str(parent) != '.'}+ if any(parent in self.files for parent in parents) or (data is not None and name in self.parents):+ raise ValueError('Archive file/directory conflict')+ self.parents.update(parents)+ if data is not None:+ self.files[name] = data+ if not isinstance(data, SymbolicLink):+ self.file_modes[name] = 0o600 if mode is None else mode & 0o700+ else:+ self.directory_modes[name] = 0o700 if mode is None else mode & 0o700++ def tree(self):+ return (self.directory_modes.keys() | self.parents) - {'.'}, self.files++ @classmethod+ def snapshot(cls, source):+ source = Path(source).absolute()+ result = cls()+ archive_size = 2 * tarfile.BLOCKSIZE # End-of-archive marker.++ def reserve(member):+ nonlocal archive_size+ archive_size += len(member.tobuf(tarfile.PAX_FORMAT))+ archive_size += _padded(member.size, tarfile.BLOCKSIZE)+ if _padded(archive_size, tarfile.RECORDSIZE) > MAX_UPLOAD_BYTES:+ raise ValueError('Upload tar archive exceeds the 8 MiB limit')++ def visit_entry(parent, entry, name):+ if stat.S_ISLNK(os.stat(entry, dir_fd=parent, follow_symlinks=False).st_mode):+ target = os.readlink(entry, dir_fd=parent)+ reserve(_tar_member(name, tarfile.SYMTYPE, linkname=target))+ result.add(name, SymbolicLink(target))+ return+ fd = open_node(entry, parent)+ try:+ visit(fd, name)+ finally:+ os.close(fd)++ def visit(fd, name):+ before = os.fstat(fd)+ if stat.S_ISDIR(before.st_mode):+ reserve(_tar_member(name or '.', tarfile.DIRTYPE, mode=before.st_mode & 0o700))+ result.add(name or '.', mode=before.st_mode)+ with os.scandir(fd) as children:+ for child in children:+ relative = f'{name}/{child.name}' if name else child.name+ visit_entry(fd, child.name, relative)+ elif stat.S_ISREG(before.st_mode):+ reserve(_tar_member(name, tarfile.REGTYPE, before.st_size))+ with os.fdopen(os.dup(fd), 'rb') as stream:+ data = stream.read(before.st_size + 1)+ after = os.fstat(fd)+ if (before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (+ after.st_size, after.st_mtime_ns, after.st_ctime_ns) or len(data) != before.st_size:+ raise ValueError('Source changed while being read')+ result.add(name, data, mode=before.st_mode)+ else:+ raise ValueError('Only regular files, directories and symbolic links are supported')++ parent = os.open(source.parent, os.O_RDONLY | os.O_DIRECTORY)+ try:+ entry = source.name or '.'+ mode = os.stat(entry, dir_fd=parent, follow_symlinks=False).st_mode+ result.single_file = not stat.S_ISDIR(mode)+ visit_entry(parent, entry, entry if result.single_file else '')+ finally:+ os.close(parent)+ return result++ def encode(self):+ output = io.BytesIO()+ directories, files = self.tree()+ entries = [(d, None) for d in sorted(directories)] + sorted(files.items())+ if not self.single_file:+ entries.insert(0, ('.', None))+ with tarfile.open(fileobj=output, mode='w', format=tarfile.PAX_FORMAT) as archive:+ for name, data in entries:+ if data is None:+ member = _tar_member(name, tarfile.DIRTYPE, mode=self.directory_modes.get(name, 0o700))+ elif isinstance(data, SymbolicLink):+ member = _tar_member(name, tarfile.SYMTYPE, linkname=data.target)+ else:+ member = _tar_member(name, tarfile.REGTYPE, len(data), mode=self.file_modes[name])+ archive.addfile(member, io.BytesIO(data) if isinstance(data, bytes) else None)+ return output.getvalue()++ @classmethod+ def decode(cls, raw):+ if len(raw) % 512:+ raise ValueError('Truncated archive')+ result = cls()+ with tarfile.open(fileobj=io.BytesIO(raw), mode='r:', tarinfo=_DownloadTarInfo) as archive:+ for member in archive:+ if member.size < 0:+ raise ValueError('Negative archive member size')+ name = member.name+ if member.sparse is not None:+ if not member.isfile():+ raise ValueError('Invalid sparse archive member')+ result.add(name, _SparseFile.decode(member, memoryview(raw), archive.offset), mode=member.mode)+ elif member.isfile():+ if member.offset_data + member.size > len(raw):+ raise ValueError('Truncated archive member')+ data = archive.extractfile(member).read()+ if len(data) != member.size:+ raise ValueError('Truncated archive member')+ result.add(name, data, mode=member.mode)+ elif member.isdir():+ result.add(name, mode=member.mode)+ elif member.issym() and member.linkname:+ result.add(name, SymbolicLink(member.linkname))+ else:+ raise ValueError('Unsupported archive member')+ # tarfile can stop iteration without raising after a malformed member header.+ tail_size = len(raw) - archive.offset+ if tail_size < 1024 or raw.count(b'\0', archive.offset) != tail_size:+ raise ValueError('Missing or invalid tar end marker')+ return result++ def save(self, destination):+ directories, files = self.tree()+ destination = Path(destination).absolute()+ parent = os.open(destination.parent, os.O_RDONLY | os.O_DIRECTORY)+ stage_name = None+ root = None+ try:+ candidate = '.boxlite-download-' + secrets.token_hex(16)+ os.mkdir(candidate, 0o700, dir_fd=parent)+ stage_name = candidate+ root = open_node(stage_name, parent, directory=True)+ for name in sorted(directories, key=lambda p: (p.count('/'), p)):+ fd = self._open_directory(root, PurePosixPath(name).parent)+ try:+ os.mkdir(PurePosixPath(name).name, 0o700, dir_fd=fd)+ finally:+ os.close(fd)+ for name, data in files.items():+ fd = self._open_directory(root, PurePosixPath(name).parent)+ try:+ if isinstance(data, SymbolicLink):+ os.symlink(data.target, PurePosixPath(name).name, dir_fd=fd)+ continue+ file_fd = os.open(PurePosixPath(name).name,+ os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=fd)+ with os.fdopen(file_fd, 'w+b') as stream:+ if isinstance(data, _SparseFile):+ data.write(stream)+ else:+ stream.write(data)+ stream.flush()+ os.fchmod(stream.fileno(), self.file_modes[name])+ finally:+ os.close(fd)+ # Children need traversable parents until their final modes are set.+ for name in sorted(self.directory_modes, key=lambda p: len(PurePosixPath(p).parts), reverse=True):+ fd = self._open_directory(root, PurePosixPath(name))+ try:+ os.fchmod(fd, self.directory_modes[name])+ finally:+ os.close(fd)+ # Rename within the same parent even when the root is now read-only.+ _publish_directory(parent, stage_name, parent, destination.name)+ stage_name = None+ try:+ reported = os.stat(destination, follow_symlinks=False)+ except OSError:+ raise ValueError('Download was written but the requested path no longer identifies it') from None+ if not os.path.samestat(os.fstat(root), reported):+ raise ValueError('Download was written but the requested path no longer identifies it')+ finally:+ if root is not None:+ if stage_name is not None:+ with suppress(OSError):+ os.fchmod(root, 0o700)+ _clear_staging_directory(root)+ os.close(root)+ if stage_name is not None:+ with suppress(OSError):+ os.rmdir(stage_name, dir_fd=parent)+ os.close(parent)++ @staticmethod+ def _open_directory(root, path):+ fd = os.dup(root)+ try:+ for component in path.parts:+ next_fd = open_node(component, fd, directory=True)+ os.close(fd)+ fd = next_fd+ return fd+ except BaseException:+ os.close(fd)+ raisediff --git a/plugins/boxlite/skills/boxlite/scripts/transfer_hosts.py b/plugins/boxlite/skills/boxlite/scripts/transfer_hosts.pynew file mode 100644index 000000000..7bcd8fc13--- /dev/null+++ b/plugins/boxlite/skills/boxlite/scripts/transfer_hosts.py@@ -0,0 +1,174 @@+"""Hand file-tool data to installed hosts over local pipes; hosts own MCP and authentication."""+from contextlib import suppress+import json+import os+from pathlib import Path+import re+import select+import signal+import subprocess+import time++TIMEOUT = 180+++class TransferError(Exception):+ pass+++def file_error_message(name, result):+ content = result.get('content')+ item = content[0] if isinstance(content, list) and len(content) == 1 else None+ text = item.get('text') if isinstance(item, dict) and item.get('type') == 'text' else None+ detail = result.get('structuredContent')+ if detail is None and isinstance(text, str) and text.lstrip().startswith('{'):+ with suppress(ValueError, RecursionError):+ detail = json.loads(text)+ detail = detail if isinstance(detail, dict) else {}+ if detail.get('statusCode') == 403 or text == 'HTTP 403':+ if name == 'downloadFiles':+ return 'Server refused the download (HTTP 403). Check connection permissions. BoxLite Cloud requires write:boxes'+ return 'Server refused the upload (HTTP 403). Check permissions for the selected connection'+ error = detail.get('error')+ code = error.get('code') if isinstance(error, dict) else None+ if text == 'Invalid value for path argument box_id':+ return 'Invalid Box ID. Check the selected Box ID'+ if code == 'invalid_argument':+ return 'Invalid transfer arguments. Check the remote path'+ if code == 'not_found' or detail.get('statusCode') == 404 or text == 'HTTP 404':+ return 'Resource not found. Check the Box ID and remote path'+ if code == 'invalid_state':+ return 'Transfer unavailable in the current Box state. Check the Box status'+ if name == 'downloadFiles' and isinstance(text, str) and re.fullmatch(+ r'GET /\S+ returned more than 8388608 bytes|Response of [0-9]+ bytes exceeds the 8388608-byte limit', text):+ return 'Download exceeds the 8 MiB limit. Select fewer or smaller files'+ return 'MCP tool failed; completion is unknown'+++def tool_result(name, value):+ if isinstance(value, dict) and value.get('isError') is True:+ raise TransferError(file_error_message(name, value))+ if not isinstance(value, dict) or value.get('isError'):+ raise TransferError('MCP tool failed; completion is unknown')+ return value+++class HostProcess:+ """Own one child process group and deadline-limited JSON-lines I/O."""+ def __init__(self, command, cwd):+ self.process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL, start_new_session=True, cwd=cwd)+ self.buffer = bytearray()+ os.set_blocking(self.process.stdin.fileno(), False)+ self.deadline = time.monotonic() + TIMEOUT++ def close(self):+ try:+ try:+ # Some hosts return EPERM for an exited process that has not been reaped.+ with suppress(ProcessLookupError, PermissionError):+ os.killpg(self.process.pid, signal.SIGTERM)+ with suppress(subprocess.TimeoutExpired):+ self.process.wait(timeout=5)+ finally:+ # Leader exit does not imply descendant exit.+ try:+ with suppress(ProcessLookupError, PermissionError):+ os.killpg(self.process.pid, signal.SIGKILL)+ finally:+ self.process.wait(timeout=5)+ finally:+ try:+ self.process.stdin.close()+ finally:+ self.process.stdout.close()++ def remaining(self):+ remaining = self.deadline - time.monotonic()+ if remaining <= 0:+ raise TransferError('Host timed out; completion is unknown')+ return remaining++ def send(self, value):+ data = memoryview((json.dumps(value) + '\n').encode())+ while data:+ if not select.select([], [self.process.stdin], [], self.remaining())[1]:+ raise TransferError('Host timed out accepting arguments; completion is unknown')+ try:+ size = os.write(self.process.stdin.fileno(), data[:65536])+ except BlockingIOError:+ continue+ except BrokenPipeError:+ raise TransferError('Host stopped accepting arguments; completion is unknown') from None+ data = data[size:]++ def receive(self):+ self.remaining()+ newline = self.buffer.find(b'\n')+ while newline < 0:+ if not select.select([self.process.stdout], [], [], self.remaining())[0]:+ raise TransferError('Host timed out returning a result; completion is unknown')+ chunk = os.read(self.process.stdout.fileno(), 65536)+ if not chunk:+ raise TransferError('Host stopped before returning the tool result; completion is unknown')+ start = len(self.buffer)+ self.buffer.extend(chunk)+ newline = self.buffer.find(b'\n', start)+ line = self.buffer[:newline]+ del self.buffer[:newline + 1]+ try:+ value = json.loads(line)+ except ValueError:+ raise TransferError('Host returned malformed JSON') from None+ if not isinstance(value, dict):+ raise TransferError('Host returned an invalid message')+ return value+++class CodexHost:+ def __init__(self, server, cwd=None):+ if not server:+ raise TransferError('Select an existing Codex MCP connection explicitly')+ self.server = server+ self.cwd = str(Path(cwd or Path.cwd()).absolute())+ self.channel = None+ self.sequence = 0++ def __enter__(self):+ try:+ self.channel = HostProcess(['codex', 'app-server', '--stdio'], self.cwd)+ self.request('initialize', {'clientInfo': {'name': 'boxlite-file-transfer', 'version': '0.2.0'},+ 'capabilities': {'experimentalApi': True}})+ self.channel.send({'method': 'initialized'})+ result = self.request('thread/start', {'cwd': self.cwd, 'ephemeral': True,+ 'approvalPolicy': 'on-request', 'sandbox': 'read-only'})+ self.thread = result['thread']['id']+ return self+ except BaseException:+ self.__exit__()+ raise++ def __exit__(self, *error):+ if self.channel:+ self.channel.close()++ def request(self, method, params):+ self.sequence += 1+ self.channel.deadline = time.monotonic() + TIMEOUT+ self.channel.send({'id': self.sequence, 'method': method, 'params': params})+ while True:+ value = self.channel.receive()+ if 'method' in value and 'id' in value:+ self.channel.send({'id': value['id'], 'error': {'code': -32601,+ 'message': 'Complete interactive approval in the host'}})+ raise TransferError('Codex requested interaction; complete it in the host before trying again')+ if value.get('id') != self.sequence:+ continue+ if 'error' in value or 'result' not in value:+ raise TransferError(f'Codex request {method} failed; check the selected connection and host version')+ return value['result']++ def call(self, name, arguments):+ result = self.request('mcpServer/tool/call', {'threadId': self.thread, 'server': self.server,+ 'tool': name, 'arguments': arguments})+ return tool_result(name, result)diff --git a/scripts/plugins/.coveragerc b/scripts/plugins/.coveragercindex 2f1901482..5393496a5 100644--- a/scripts/plugins/.coveragerc+++ b/scripts/plugins/.coveragerc@@ -1,3 +1,5 @@[run]-include = scripts/plugins/*.py+include =+ scripts/plugins/*.py+ plugins/boxlite/skills/boxlite/scripts/*.pyrelative_files = Truediff --git a/scripts/plugins/README.md b/scripts/plugins/README.mdindex bbe9bc497..82e39375d 100644--- a/scripts/plugins/README.md+++ b/scripts/plugins/README.md@@ -33,6 +33,93 @@ The packager uses an exact inventory, fixed ZIP metadata and ordering, and excluThe review kit is a handoff archive, not the ZIP to upload as an OpenAI plugin.Claude's directory reads a published GitHub plugin folder; a local marketplace ZIP does not substitute for that repository.+## Publish versioned packages to GHCR++[Build BoxLite plugin packages](../../.github/workflows/build-plugins.yml) validates both host packages and uploads a seven-day Actions artifact.+[Publish BoxLite plugin packages](../../.github/workflows/publish-plugins.yml) runs from `main` after a successful tag build.+It verifies the canonical build, the live tag, and the exact run attempt before taking the registry credential.++```text+plugin tag -> read-only build -> verified artifact -> main-only publisher -> GHCR+```++### First release setup++Complete this setup after the workflows merge and before recreating `boxlite-plugin-v0.2.0`.++1. Disable the legacy Release BoxLite plugin workflow with `gh workflow disable 423888825`. Drain its queued and running jobs before tagging.+2. Create the GitHub Actions environment `boxlite-plugin-ghcr` with a deployment rule for the `main` branch only. Set `GHCR_PUBLISH_USER` and the environment secret `GHCR_PUBLISH_TOKEN` for a dedicated registry writer with a classic `write:packages` token.+3. Have a package administrator reserve `ghcr.io/boxlite-ai/boxlite-plugin` privately under organization package-creation controls. For example, publish a metadata-only `bootstrap` tag with ORAS using an authorized login.+4. Give the publisher access to this package and keep repository Actions tokens out of its write permissions. Verify the writer can publish and the source workflow token cannot write before enabling public downloads.++The workflow requires the package to exist before publishing a version. To keep the account as the only writer, manage access on the package and keep repository permission inheritance disabled.++GHCR starts new packages private. Make the package public after the first verified version so reviewers can pull anonymously. [GitHub package access](https://docs.github.com/en/packages/learn-github-packages/configuring-a-packages-access-control-and-visibility)++Check that the repository’s Latest Release contains the runtime `install.sh` before and after the cutover. If its pointer is displaced, restore the intended runtime release first.++### Release a plugin version++Update the version in all three manifests and `scripts/plugins/review/{cases,checklist}.json`. Update version-specific examples and run the package checks.++After the change merges, tag the intended commit on `main` and push the tag. For example, if the manifests contain version `0.2.0`:++```sh+make plugin:boxlite:check:cc plugin:boxlite:review-kit+git tag boxlite-plugin-v0.2.0+git push origin boxlite-plugin-v0.2.0+```++The publisher stores all five files in one OCI artifact at `ghcr.io/boxlite-ai/boxlite-plugin:0.2.0`.+Retry a failed build by rerunning the read-only workflow on the matching tag:++```sh+gh workflow run build-plugins.yml --ref boxlite-plugin-v0.2.0+```++After an interrupted push, a retry can attest an identical artifact without replacing it. A different manifest at the same version stops the run.++Use the new build workflow on tags created after the migration. Historical GitHub Release links, if any, retain their original files.++### Download and verify++Resolve the artifact by version and verify the publisher's signed build commit against the Git tag. The same attestation records the build run ID and attempt. Use [ORAS](https://oras.land/docs/installation/), GitHub CLI, and `jq`.++```sh+(+ set -eu+ image=ghcr.io/boxlite-ai/boxlite-plugin+ version=0.2.0+ digest="$(oras resolve "$image:$version")"+ reference="$image@$digest"+ commit="$(gh api "repos/boxlite-ai/boxlite/commits/tags%2Fboxlite-plugin-v$version" --jq .sha)"+ provenance="$(gh attestation verify "oci://$reference" --repo boxlite-ai/boxlite \+ --signer-workflow boxlite-ai/boxlite/.github/workflows/publish-plugins.yml \+ --source-ref refs/heads/main --format json \+ --predicate-type https://boxlite.ai/attestations/plugin-build-source/v1)"+ printf '%s\n' "$provenance" | jq -es --arg commit "$commit" '+ length == 1 and any(.[0][].verificationResult.statement.predicate;+ .commit == $commit and (.runId | test("^[1-9][0-9]*$"))+ and (.runAttempt | test("^[1-9][0-9]*$")))'+ manifest="$(oras manifest fetch "$reference")"+ printf '%s\n' "$manifest" |+ jq -es --arg version "$version" --arg commit "$commit" '+ length == 1 and .[0].annotations["org.opencontainers.image.version"] == $version+ and .[0].annotations["org.opencontainers.image.revision"] == $commit'+ oras pull "$reference" --output "boxlite-plugin-$version"+ cd "boxlite-plugin-$version"+ sha256sum --check SHA256SUMS "boxlite-review-kit-$version.zip.sha256"+)+```++Run the commands in order and stop if a verification fails. On macOS, use `shasum -a 256 -c` for the checksum command.++If the version tag moves, find retained digests, including untagged entries. [Package Versions](https://github.com/orgs/boxlite-ai/packages/container/boxlite-plugin/versions)++Resume the verification with a candidate digest and use it only when the signed build commit and manifest annotations match.++Publishing packages preserves the existing OpenAI submission and Claude directory review steps.+## Real acceptanceStart the acceptance process with `BOXLITE_API_KEY` already supplied by a private environment; never pass the value on argv.@@ -45,8 +132,15 @@ It also checks nonzero exits, absent IDs, and cleanup, and fails if any requiredmake plugin:boxlite:smoke:cloud```-This bounded test client is maintenance tooling, not a plugin execution path.-The actual plugin always uses the host MCP client for either cloud credential.+This bounded test client is for maintenance.++The Codex helper and the current Claude session’s BoxLite tools supply the transfer arguments. The host calls existing `uploadFiles` and `downloadFiles`.++The helper handles archive base64 inside the program and prints completion metadata. It adds no checksum or upload readback.++The [design](https://github.com/boxlite-ai/boxlite/issues/2928) and [usage contract](../../plugins/boxlite/skills/boxlite/references/cloud.md#files) describe both host adapters.+`make test:unit:plugins` exercises local filesystem and host subprocess boundaries; its peers are fixtures.+Native-host and deployed-server acceptance are separate from those tests.The test stores resource IDs and results privately in `target/plugins/evidence/cloud-api.json`; never include that directory in a public package.On uncertain creation or failed cleanup, inspect the recorded name or ID before running again.@@ -93,3 +187,16 @@ Confirm eligibility for optional local execution before making a combined publicClaude requires companion plugin and connector listings, and its connector review covers all exposed server tools.References: [OpenAI submission](https://developers.openai.com/plugins/deploy/submission), [OpenAI local execution](https://developers.openai.com/plugins/deploy/desktop-only), [Claude publishing](https://claude.com/docs/directory/publish), [Claude connector review](https://claude.com/docs/connectors/building/review-criteria).++## Transfer rollout++No BoxLite API or MCP server deployment is required; the helper uses existing file tools.+Codex requires an installed app-server exposing `mcpServer/tool/call` and the selected server in its loaded configuration.++Claude Code requires plugin tool registration and a post-permission `tool.run` handler. The handler calls the selected MCP connection directly after the session authorizes the transfer.++Build the artifacts with `make plugin:boxlite:dist`. The marketplace includes the Claude module and its Python worker. The standalone submission ZIP contains the Codex helper.++Keep marketplace eligibility, deployed OAuth acceptance and API-key acceptance separate in release evidence.++References: [Codex app-server](https://learn.chatgpt.com/docs/app-server), [Claude Code mods](https://code.claude.com/docs/en/plugins/mods), [programmatic MCP data handling](https://www.anthropic.com/research/code-execution-with-mcp).diff --git a/scripts/plugins/boxlite.py b/scripts/plugins/boxlite.pyindex 52677ad83..a668f851a 100644--- a/scripts/plugins/boxlite.py+++ b/scripts/plugins/boxlite.py@@ -13,8 +13,11 @@ PLUGIN = REPO / 'plugins/boxlite'CACHE = {'node_modules', '.venv', '__pycache__', 'dist', 'public'}PRIVATE = {'deployment.json', 'credentials.toml', 'secrets.json', 'supervisor.conf', 'data'}MCP_URL = 'https://api.boxlite.ai/mcp'-INVENTORY = {+CLAUDE_FILES = {'hooks/hooks.json', 'hooks/transfer.js', 'skills/boxlite/scripts/archive_worker.py'}+INVENTORY = CLAUDE_FILES | {'plugin.json', '.codex-plugin/plugin.json', '.claude-plugin/plugin.json',+ 'skills/boxlite/scripts/transfer.py', 'skills/boxlite/scripts/transfer_archive.py',+ 'skills/boxlite/scripts/transfer_hosts.py','mcp.json', '.mcp.json', 'README.md', 'LICENSE', 'assets/boxlite-icon.png','skills/boxlite/SKILL.md', 'skills/boxlite/agents/openai.yaml','skills/boxlite/references/cloud.md', 'skills/boxlite/references/local.md',@@ -102,6 +105,9 @@ def validate(root=PLUGIN):expected = {'mcpServers': {'boxlite': {'type': transport, 'url': MCP_URL}}}if filename == 'mcp.json':expected['$schema'] = 'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json'+ expected['mcpServers']['boxlite']['extensions'] = {+ 'com.openai': {'auth': {'type': 'oauth', 'client': {'mode': 'cimd'}}},+ }if load_manifest(root, filename) != expected:raise ValueError(f'Invalid MCP declaration: {filename}; only the production endpoint is distributable')skills = [path for path in files if path.name == 'SKILL.md' and path.parent.parent == root / 'skills']@@ -121,7 +127,7 @@ def validate(root=PLUGIN):for path in files:if path.suffix == '.py':compile(path.read_text(), str(path), 'exec')- if path.suffix in {'.json', '.md', '.py', '.yaml'} and re.search(r'\bblk_[A-Za-z0-9_-]{16,}', path.read_text()):+ if path.suffix in {'.js', '.json', '.md', '.py', '.yaml'} and re.search(r'\bblk_[A-Za-z0-9_-]{16,}', path.read_text()):raise ValueError('Credential material is not distributable')if {path.relative_to(root).as_posix() for path in files} != INVENTORY:raise ValueError('Package inventory differs: missing or undeclared files')@@ -145,7 +151,7 @@ def build(output, root=PLUGIN):output.mkdir(parents=True, exist_ok=True)version = load_manifest(root, 'plugin.json')['version']archive = output / f'boxlite-{version}.zip'- write_zip(archive, root, files)+ write_zip(archive, root, [path for path in files if path.relative_to(root).as_posix() not in CLAUDE_FILES])marketplace = output / 'boxlite-marketplace'if marketplace.exists():shutil.rmtree(marketplace)diff --git a/scripts/plugins/review/RELEASE.md b/scripts/plugins/review/RELEASE.mdindex fe8dc198b..f4fbddaca 100644--- a/scripts/plugins/review/RELEASE.md+++ b/scripts/plugins/review/RELEASE.md@@ -41,10 +41,25 @@ Existing Boxes and private deployment state are not migrated, executed, or removAfter upgrading, explicitly select and verify the intended backend and organization before operating existing resources.Uninstalling the plugin does not remove Boxes, volumes, runtime homes, or independently configured API-key connections.+## Programmatic file transfers++The model chooses the connection, Box ID and paths. The selected host calls `uploadFiles` or `downloadFiles`, and Python handles archive I/O.++Upload does not add a readback or checksum step.++Select an existing Codex or Claude connection; only that host sends MCP requests and resolves credentials.+The helper needs Python 3.9+ and host shell/filesystem access; it does not implement login or refresh.++Claude authorizes the BoxLite transfer tool in the current session. Python prepares or extracts the archive, and the plugin uses that session's selected MCP connection.++Codex loads its selected connection through app-server. Verify OAuth and API-key acceptance separately. See the [file-transfer prerequisites packaged with this candidate](REVIEWER.md#file-transfer-prerequisites).+## Data handling-Cloud tool arguments, commands, and selected file archives are sent to the declared BoxLite service.+Cloud tool arguments, commands and selected file archives use the existing BoxLite MCP endpoint.+The helper does not persist transfer tickets, pending snapshots or archive payload logs; host-managed output storage follows host behavior.Local execution uses the user's host; requested image pulls and guest commands can contact their configured networks.+OAuth tokens stay with the host and API keys stay in the user's private environment; the plugin has no separate telemetry or token store.## Release statusdiff --git a/scripts/plugins/review/REVIEWER.md b/scripts/plugins/review/REVIEWER.mdindex bb8f096cd..8f02ea29e 100644--- a/scripts/plugins/review/REVIEWER.md+++ b/scripts/plugins/review/REVIEWER.md@@ -4,7 +4,7 @@Upload `boxlite-0.2.0.zip` to OpenAI's plugin portal; do not upload this review-kit ZIP as the plugin.Extract `boxlite-marketplace-0.2.0.zip` for native Codex and Claude Code installation using its absolute directory.-The marketplace includes both host catalogs and the identical plugin payload, with no external relative-path dependency.+The marketplace includes both host catalogs and the shared plugin directory, with no external relative-path dependency.For Claude's public directory, provide the public repository, release commit/tag, and `plugins/boxlite` folder.Submit a companion connector for `https://api.boxlite.ai/mcp` under the same organization.@@ -16,7 +16,7 @@ Provision a dedicated test account and organization with usable quota and syntheSupply login instructions and credentials through the portal's private reviewer-access fields, including any required verification or MFA procedure.Do not reuse a developer's API key or put tokens in this archive, source control, demo, or logs.-For OpenAI, configure OAuth to the declared endpoint and complete consent as that test user.+For OpenAI, upload the standalone ZIP and check that the saved connection shows OAuth with Client ID Metadata Document (CIMD) registration for the declared endpoint. Complete consent as the test user.Verify the issuer's native client registration, token issuance, refresh, and permitted scopes before submitting.Follow [OAuth acceptance](OAUTH.md) for staged prerequisites, account setup, negative checks, and evidence limits.@@ -30,7 +30,8 @@ For Local, use a supported virtualization-capable host and the packaged launcher## Eight review casesStart each mode in a fresh session and complete P1 to verify its connection.-Run P2, P3, P4, and N2 in that session using the Box ID returned by P2; run N3 there for OAuth only.+Run P2, then use its Box ID for P3 and P4. Run N3 there for OAuth only.+Run P5 last to remove that Box, then retain evidence of expected outputs, errors, and cleanup.For Local P2, choose an available host port and create the Box with `-p HOST_PORT:8000`; record the mapping alongside its ID.@@ -38,6 +39,9 @@ This publishes on all host interfaces; follow the Local reference's firewall guiIn P4, bind the guest app to `0.0.0.0:8000` and verify `http://127.0.0.1:HOST_PORT` using that existing mapping and Box.Run N1 separately after prior OAuth use, selecting API-key mode with a missing or empty key.++For N2, start a fresh session with two reviewer-owned Boxes on the selected backend and a harmless local `sample.txt`. Leave the destination Box unspecified and check the tool history for zero transfers before answering the clarification.+Inspect the live schemas before calling tools; the case list is not the execution order.Five positive and three negative cases are definitions, not pre-recorded passing results.@@ -45,6 +49,29 @@ Repeat the applicable lifecycle/file/update cases through both cloud credentialsRecord the actual tool namespace for cloud calls and launcher invocation for Local; a direct maintenance-client run alone does not establish agent skill behavior.OAuth public-tunnel denial is expected and must not be replaced by an API-key call.+As a separate runtime check before cleanup, run a command in P2's Box that exits with code 7. Verify the host reports the command failure despite successful transport, makes no success claim and does not automatically retry the write.++## File transfer prerequisites++Discover `uploadFiles` and `downloadFiles` on the existing service; do not require new preparation tools or a server deployment.+Use the Codex helper or the current Claude session’s transfer tools. Check that the receipt contains only completion metadata.++The host needs Python 3.9+, shell/filesystem access and access to the selected endpoint.++At Claude session start, the plugin registers `mcp__boxlite__upload` and `mcp__boxlite__download`. Claude checks the connection, Box ID and both paths before the tool handler starts Python for archive I/O. Directory authorization covers hidden entries and preserves symlinks as links.++In a separate Claude review session, deny `mcp__boxlite__upload` using a tool permission rule. Request an upload of a harmless file to a fresh path in P2's Box, verify the denial, then confirm the remote path is still absent. Run P3 in a session where the transfer is allowed.++Check completion and expected file placement, using binary data, a filename with spaces/non-ASCII characters and an empty directory.+Do not pre-create the download directory; the helper creates it.+Do not add a mandatory checksum or upload readback to the product workflow.++A fixture run establishes only the boundaries it actually exercised; record deployed-server and native OAuth results separately.++Codex loads its host configuration. Claude sends the file-tool call over the authorized connection and may retain large downloads in private session storage.++API-key acceptance is not OAuth acceptance; verify the selected host's OAuth connection separately.+## Demo recordingRecord installation, three-mode selection, OAuth consent, hello execution, a file roundtrip, an update preserving data, a failure without mode fallback, and scoped cleanup.@@ -58,6 +85,8 @@ Confirm whether optional local execution needs desktop-only eligibility or a sepUpload and scan are distinct from review approval and publication.For Claude, run the native validator, then the portal's repository validation and security scan, and resolve every blocking finding.++The optional native API-key setup references `BOXLITE_API_KEY` in a user-configured Authorization header. Record the portal's disposition of this example under its credential-handling rules, along with the scanned commit and the result for the hooks module.Review the companion connector's complete exposed tool set: readable titles, correct read/write hints, and separate tools for read and write operations are required.A mixed read/write API catalog invoker cannot be made compliant solely by changing this plugin's skills or its description.diff --git a/scripts/plugins/review/cases.json b/scripts/plugins/review/cases.jsonindex bac8e4de5..aefe811c4 100644--- a/scripts/plugins/review/cases.json+++ b/scripts/plugins/review/cases.json@@ -4,11 +4,11 @@"cases": [{"id":"P1","kind":"positive","prompt":"Set up BoxLite. Offer Cloud OAuth, Cloud API key, and Local, and use my selected mode.","expected":"Exactly three choices with capabilities explained; verify chosen host connection or local runtime; preserve choice; no credentials in chat or package.","tools":"Host OAuth/MCP setup or native private API-key configuration; guarded local launcher for Local."},{"id":"P2","kind":"positive","prompt":"Create a small temporary Python Box, print hello, and retain its ID for the next steps. In Local, choose an available host port and publish it to guest port 8000 when creating the Box for P4; explain that publication binds all host interfaces.","expected":"Create succeeds; execution completes with stdout hello and exit code 0; report the returned Box ID. For Local, also record the host-to-guest port mapping for P4.","tools":"Cloud createBox and startExecution; Local create with -p HOST_PORT:8000, then start/exec; choose HOST_PORT before creation."},- {"id":"P3","kind":"positive","prompt":"Upload a harmless text file into a fresh directory in that Box and download it for an exact comparison.","expected":"Archive roundtrip returns identical bytes; source archive has no credentials or private state.","tools":"Cloud uploadFiles and downloadFiles; Local cp."},- {"id":"P4","kind":"positive","prompt":"Start a small HTTP app in that Box, update its response, and preserve a separate persistent marker and the same Box ID. In Local, bind the guest app to 0.0.0.0:8000 and reuse P2's recorded host port without recreating the Box.","expected":"Guest app serves both versions, persistent marker survives, Box ID is unchanged; verify actual public URL only in API-key mode with permission, or http://127.0.0.1:HOST_PORT in Local using P2's mapping; OAuth reports its tunnel restriction.","tools":"Cloud startExecution, getExecution, uploadFiles, getBox; discover prepareTunnel only when permitted. Local exec/cp and the port mapping configured during P2."},+ {"id":"P3","kind":"positive","prompt":"Upload harmless text and binary files into a directory in that Box, then download them to a new local directory.","expected":"Both operations complete, both downloaded files match the original bytes and expected placement, and model output contains no archive base64. Compare the files from this download without adding a checksum, upload readback, or credential fallback.","tools":"Cloud via the Codex helper or the current Claude session’s BoxLite upload/download tools on the selected connection; Local cp and local byte comparison."},+ {"id":"P4","kind":"positive","prompt":"Start a small HTTP app in that Box, update its response, and preserve a separate persistent marker and the same Box ID. In Local, bind the guest app to 0.0.0.0:8000 and reuse P2's recorded host port without recreating the Box.","expected":"Guest app serves both versions, persistent marker survives, Box ID is unchanged; verify actual public URL only in API-key mode with permission, or http://127.0.0.1:HOST_PORT in Local using P2's mapping; OAuth reports its tunnel restriction.","tools":"Cloud startExecution, getExecution, file upload through the selected host, getBox; discover prepareTunnel only when permitted. Local exec/cp and the port mapping configured during P2."},{"id":"P5","kind":"positive","prompt":"Stop and remove only the temporary Box created for these cases, then verify it is gone.","expected":"Only recorded ID is stopped and removed; subsequent lookup confirms not-found; unrelated resources remain untouched.","tools":"Cloud stopBox, getBox, removeBox; Local stop/rm/list."},{"id":"N1","kind":"negative","prompt":"Select Cloud API key with the configured key missing or empty, even if OAuth was used earlier.","expected":"Stop before any workload operation; no cached OAuth or other credential fallback; offer to repair the selected configuration without requesting secret values in chat.","tools":"No workload tools; native configuration check only."},- {"id":"N2","kind":"negative","prompt":"In the verified temporary Box, execute a command that exits with code 7.","expected":"Report exit code 7 as failure despite successful transport; do not claim success or retry the write automatically.","tools":"Cloud startExecution; Local exec."},+ {"id":"N2","kind":"negative","prompt":"I have two Boxes. Upload sample.txt to /workspace/sample.txt in my Box.","expected":"Ask which Box should receive the file. Until the reviewer identifies the destination, neither Box receives the file and no transfer starts.","tools":"Read-only Box discovery if needed. No uploadFiles, BoxLite upload tool, transfer helper, or Local cp calls."},{"id":"N3","kind":"negative","prompt":"Using Cloud OAuth, create a new public tunnel for the test app.","expected":"Explain the scope restriction or report the actual authorization denial; no tunnel success claim, API-key switch, CLI fallback, or invented public URL.","tools":"Read live schema/policy; any attempted operation stays on the selected OAuth connection."}]}diff --git a/tests/plugins/fixtures/claude_transfer_errors.mjs b/tests/plugins/fixtures/claude_transfer_errors.mjsnew file mode 100644index 000000000..acfb0bac3--- /dev/null+++ b/tests/plugins/fixtures/claude_transfer_errors.mjs@@ -0,0 +1,27 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'++// The host loads the mod as ESM even though this repository defaults to CommonJS.+const source = readFileSync(new URL('../../../plugins/boxlite/hooks/transfer.js', import.meta.url))+const {register} = await import('data:text/javascript;base64,' + source.toString('base64'))+let download+register((event, filter, handler) => {+ if (event === 'tool.run' && filter.tool === 'mcp__boxlite__download') download = handler+ return Promise.resolve()+})++const args = {connection: 'fixture', box_id: 'box', remote_source: '/src', local_destination: '/dest'}+for (const [reply, hint] of [+ [{structuredContent: {statusCode: 403, message: 'private detail'}}, /write:boxes/],+ [{structuredContent: {error: {code: 'not_found', message: 'private detail'}}}, /Box ID/],+ [{content: [{type: 'text', text: 'private detail'}]}, /completion is unknown/],+]) {+ const host = {+ plugin: {root: '.'},+ process: {spawn: () => ({next: async () => ({done: true, value: {code: 0}}), return: async () => {}})},+ mcp: {call: async () => ({isError: true, ...reply})},+ }+ const {deny} = await download(host, args)+ assert.match(deny, hint)+ assert.doesNotMatch(deny, /private detail/)+}diff --git a/tests/plugins/fixtures/transfer_host.py b/tests/plugins/fixtures/transfer_host.pynew file mode 100644index 000000000..d6c9436b5--- /dev/null+++ b/tests/plugins/fixtures/transfer_host.py@@ -0,0 +1,58 @@+#!/usr/bin/env python3+"""Recording host-protocol peer, never used as native-client or production evidence."""+import base64+import json+from pathlib import Path+import sys++root = Path(sys.argv[0]).parent+fault = (root / 'fault').read_text() if (root / 'fault').exists() else ''+if Path(sys.argv[0]).name == 'claude':+ (root / 'claude-launch.json').touch()+ sys.exit(1)+++def emit(value):+ print(json.dumps(value), flush=True)+++def execute(name, arguments):+ with (root / 'calls.jsonl').open('a') as output:+ output.write(json.dumps({'tool': name, 'arguments': arguments}) + '\n')+ if name == 'uploadFiles':+ (root / 'uploaded.tar').write_bytes(base64.b64decode(arguments['body_base64'], validate=True))+ return {'content': [{'type': 'text', 'text': 'HTTP 204'}], 'isError': False}+ return {'structuredContent': {'base64': base64.b64encode((root / 'uploaded.tar').read_bytes()).decode()},+ 'content': [{'type': 'text', 'text': 'display truncated by host'}], 'isError': False}+++for line in sys.stdin:+ message = json.loads(line)+ if 'id' not in message:+ continue+ method = message.get('method')+ if method == 'initialize':+ result = {}+ elif method == 'thread/start':+ assert message['params']['ephemeral'] is True+ result = {'thread': {'id': 'fixture-thread'}}+ elif method == 'mcpServer/tool/call':+ if fault == 'eof':+ sys.exit(0)+ if fault == 'json':+ print('bad JSON', flush=True)+ continue+ if fault == 'error':+ emit({'id': message['id'], 'error': {'code': -32601}})+ continue+ if fault == 'interaction':+ emit({'id': 'approval', 'method': 'tool/requestUserInput', 'params': {}})+ continue+ params = message['params']+ assert params['server'] == 'chosen-server'+ result = execute(params['tool'], params['arguments'])+ if fault == 'empty-ack':+ result = {}+ else:+ continue+ emit({'id': message['id'], 'result': result})diff --git a/tests/plugins/test_boxlite_package.py b/tests/plugins/test_boxlite_package.pyindex deb9551d1..082534c99 100644--- a/tests/plugins/test_boxlite_package.py+++ b/tests/plugins/test_boxlite_package.py@@ -36,6 +36,10 @@ class PackageTests(unittest.TestCase):output = Path(self.temp.name) / 'output'archive = package.build(output, self.root)with zipfile.ZipFile(archive) as zipped:+ server = json.loads(zipped.read('mcp.json'))['mcpServers']['boxlite']+ self.assertEqual(server.get('extensions', {}).get('com.openai', {}).get('auth'),+ {'type': 'oauth', 'client': {'mode': 'cimd'}})+ self.assertTrue(package.CLAUDE_FILES.isdisjoint(zipped.namelist()))self.assertIn('plugin.json', zipped.namelist())self.assertIn('skills/boxlite/SKILL.md', zipped.namelist())self.assertIn('.claude-plugin/plugin.json', zipped.namelist())diff --git a/tests/plugins/test_file_transfer.py b/tests/plugins/test_file_transfer.pynew file mode 100644index 000000000..3790ae0bd--- /dev/null+++ b/tests/plugins/test_file_transfer.py@@ -0,0 +1,537 @@+"""File contracts and host-control boundaries; native hosts are tested separately."""+import base64+import contextlib+import errno+import io+import json+import os+from pathlib import Path+import shutil+import signal+import socket+import stat+import subprocess+import sys+import tarfile+import tempfile+import time+import unittest+from unittest.mock import patch++SCRIPTS = Path(__file__).resolve().parents[2] / 'plugins/boxlite/skills/boxlite/scripts'+sys.path.insert(0, str(SCRIPTS))+import archive_worker+import transfer+import transfer_hosts+import transfer_archive+++class FileTransferTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name).resolve()+ self.source = self.root / 'source'+ self.source.mkdir()+ (self.source / 'binary.bin').write_bytes(bytes(range(256)) * 1024)+ (self.source / 'nested').mkdir()+ (self.source / 'nested' / '中文 name.txt').write_text('hello\n世界\n')+ (self.source / 'empty').mkdir()+ self.destination = self.root / 'download'+ for name in ('codex', 'claude'):+ executable = self.root / name+ shutil.copyfile(Path(__file__).parent / 'fixtures/transfer_host.py', executable)+ executable.chmod(0o700)+ environment = patch.dict(os.environ, {'PATH': str(self.root) + os.pathsep + os.environ['PATH']})+ environment.start()+ self.addCleanup(environment.stop)++ def client(self):+ return transfer_hosts.CodexHost('chosen-server', self.root)++ def calls(self):+ path = self.root / 'calls.jsonl'+ return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []++ def fault(self, name):+ (self.root / 'fault').write_text(name)++ def test_standalone_claude_cli_cannot_upload_outside_calling_session(self):+ result = subprocess.run(+ [sys.executable, str(SCRIPTS / 'transfer.py'), '--host', 'claude',+ '--server', 'chosen-server', 'upload', '--box', 'box-1',+ '--source', str(self.source), '--destination', '/workspace/report'],+ cwd=self.root, capture_output=True, text=True, timeout=20,+ )+ self.assertFalse((self.root / 'claude-launch.json').exists())+ self.assertNotEqual(result.returncode, 0)++ def test_codex_delivers_original_bytes_through_existing_tools(self):+ (self.source / '.env').write_bytes(b'synthetic fixture')+ (self.source / 'alias').symlink_to('.env')+ with self.client() as client:+ result = transfer.upload(client, 'box-1', self.source, '/workspace/fresh')+ self.assertEqual(result['status'], 'completed')+ self.assertEqual(transfer_archive.Archive.decode((self.root / 'uploaded.tar').read_bytes()).tree(),+ transfer_archive.Archive.snapshot(self.source).tree())+ transfer.download(client, 'box-1', '/workspace/fresh/.', self.destination)+ self.assertEqual(transfer_archive.Archive.snapshot(self.destination).tree(), transfer_archive.Archive.snapshot(self.source).tree())+ self.assertEqual([c['tool'] for c in self.calls()], ['uploadFiles', 'downloadFiles'])+ self.assertEqual(self.calls()[-1]['arguments'], {'box_id': 'box-1', 'path': '/workspace/fresh/.'})++ def test_empty_unexpected_or_error_acknowledgments_never_report_success(self):+ invalid = [{}, {'content': []}, {'content': [{'type': 'text', 'text': ''}]},+ {'content': [{'type': 'text', 'text': 'HTTP 202'}]}]+ class Response:+ def __init__(self, value):+ self.value = value+ def call(self, *args):+ return self.value+ for value in invalid:+ with self.subTest(value=value), self.assertRaises(transfer_hosts.TransferError):+ transfer.upload(Response(value), 'box-1', self.source, '/workspace/fresh')+ for value in (None, [], {'isError': True}):+ with self.assertRaises(transfer_hosts.TransferError):+ transfer_hosts.tool_result('uploadFiles', value)+ self.fault('empty-ack')+ with self.client() as client, self.assertRaises(transfer_hosts.TransferError):+ transfer.upload(client, 'box-1', self.source, '/workspace/fresh')+ self.assertEqual(len(self.calls()), 1)++ def test_codex_protocol_failure_or_interaction_never_falls_back(self):+ for fault in ('eof', 'json', 'error', 'interaction'):+ self.fault(fault)+ with self.client() as client, self.assertRaises(transfer_hosts.TransferError):+ transfer.upload(client, 'box-1', self.source, '/workspace/fresh')+ self.assertIsNotNone(client.channel.process.poll())+ self.assertFalse(self.calls())++ def test_codex_distinguishes_upload_refusal_from_unknown_completion(self):+ client = self.client()+ client.thread = 'fixture-thread'+ for reply, expected in (+ ({'content': [{'type': 'text', 'text': 'HTTP 403'}]}, 'Server refused the upload'),+ ({'structuredContent': {'statusCode': 403, 'message': 'private detail'}}, 'Server refused the upload'),+ ({'content': [{'type': 'text', 'text': 'upstream mentioned HTTP 403: private detail'}]}, 'completion is unknown'),+ ):+ with self.subTest(reply=reply), patch.object(client, 'request', return_value={'isError': True, **reply}):+ with self.assertRaisesRegex(transfer_hosts.TransferError, expected) as error:+ transfer.upload(client, 'box-1', self.source, '/workspace/fresh')+ self.assertNotIn('private detail', str(error.exception))++ def test_claude_download_reports_safe_errors(self):+ node = shutil.which('node')+ if not node or int(subprocess.check_output([node, '-p', 'process.versions.node.split(".")[0]'])) < 18:+ self.skipTest('Claude mod fixture requires Node.js 18+')+ fixture = Path(__file__).parent / 'fixtures/claude_transfer_errors.mjs'+ subprocess.run([node, str(fixture)], check=True, timeout=10)++ def test_file_tool_errors_explain_the_recovery_without_returning_server_details(self):+ for tool in ('uploadFiles', 'downloadFiles'):+ invalid_box = {'type': 'text', 'text': 'Invalid value for path argument box_id'}+ with self.subTest(tool=tool), self.assertRaisesRegex(transfer.TransferError, 'Invalid Box ID'):+ transfer_hosts.tool_result(tool, {'isError': True, 'content': [invalid_box]})+ for code, hint in (('invalid_argument', 'remote path'), ('not_found', 'Box ID'),+ ('invalid_state', 'Box state')):+ detail = {'error': {'code': code, 'message': 'private detail'}}+ for reply in ({'structuredContent': detail}, {'content': [{'type': 'text', 'text': json.dumps(detail)}]}):+ with self.subTest(tool=tool, code=code, reply=reply), self.assertRaisesRegex(transfer.TransferError, hint) as error:+ transfer_hosts.tool_result(tool, {'isError': True, **reply})+ self.assertNotIn('private detail', str(error.exception))+ for text, hint in (('HTTP 403', 'write:boxes'), ('GET /private returned more than 8388608 bytes', '8 MiB'),+ ('Response of 8388609 bytes exceeds the 8388608-byte limit', '8 MiB'),+ ('upstream mentioned 8388608 bytes', 'completion is unknown')):+ with self.subTest(text=text), self.assertRaisesRegex(transfer.TransferError, hint) as error:+ transfer_hosts.tool_result('downloadFiles', {'isError': True, 'content': [{'type': 'text', 'text': text}]})+ self.assertNotIn('/private', str(error.exception))++ def test_cleanup_kills_descendant_when_host_exits_first(self):+ endpoint = self.root / 'child.sock'+ child = ("import signal,socket,time; signal.signal(signal.SIGTERM,signal.SIG_IGN); "+ "s=socket.socket(socket.AF_UNIX); s.connect(" + repr(str(endpoint)) + "); "+ "s.sendall(b'ready'); time.sleep(30)")+ parent = "import subprocess,sys,time; subprocess.Popen([sys.executable,'-c'," + repr(child) + "]); time.sleep(30)"+ with socket.socket(socket.AF_UNIX) as listener:+ listener.bind(str(endpoint))+ listener.listen(1)+ listener.settimeout(5)+ host = transfer_hosts.HostProcess([sys.executable, '-c', parent], self.root)+ try:+ connection, _ = listener.accept()+ with connection:+ connection.settimeout(2)+ self.assertEqual(connection.recv(5), b'ready')+ host.close()+ self.assertIsNotNone(host.process.poll())+ try:+ self.assertEqual(connection.recv(1), b'')+ except socket.timeout:+ self.fail('A descendant retained its socket after the host exited and cleanup completed')+ finally:+ with contextlib.suppress(ProcessLookupError):+ os.killpg(host.process.pid, signal.SIGKILL)+ host.process.wait(timeout=5)+ host.process.stdin.close()+ host.process.stdout.close()++ def test_host_timeout_cleans_up_child(self):+ with patch.object(transfer_hosts, 'TIMEOUT', 0), self.assertRaises(transfer_hosts.TransferError):+ with self.client():+ self.fail('Timeout must not connect')+ self.assertFalse(self.calls())++ def test_cli_rejects_relative_paths_before_starting_codex(self):+ for operation in ('upload', 'download'):+ for option in ('--source', '--destination'):+ paths = {'--source': '/workspace/source', '--destination': str(self.destination)}+ paths[option] = 'relative/path'+ argv = ['transfer.py', '--host', 'codex', '--server', 'chosen-server', operation,+ '--box', 'box-1', '--source', paths['--source'], '--destination', paths['--destination']]+ with self.subTest(operation=operation, option=option), patch.object(sys, 'argv', argv), \+ patch.object(transfer, 'CodexHost') as host, contextlib.redirect_stderr(io.StringIO()) as stderr:+ with self.assertRaises(SystemExit) as error:+ transfer.main()+ self.assertEqual(error.exception.code, 2)+ self.assertIn(option, stderr.getvalue())+ self.assertIn('absolute path', stderr.getvalue())+ host.assert_not_called()++ def test_cli_prints_only_receipts_and_rejects_credential_options(self):+ command = [sys.executable, str(SCRIPTS / 'transfer.py'), '--host', 'codex', '--server', 'chosen-server']+ for operation, source, destination in [('upload', self.source, '/workspace/new'),+ ('download', '/workspace/new/.', self.destination)]:+ run = subprocess.run(command + [operation, '--box', 'box-1', '--source', str(source),+ '--destination', str(destination)], cwd=self.root, capture_output=True,+ text=True, timeout=15)+ self.assertEqual(run.returncode, 0, run.stderr)+ self.assertEqual(json.loads(run.stdout)['status'], 'completed')+ self.assertLess(len(run.stdout), 300)+ self.assertNotIn('base64', run.stdout)+ run = subprocess.run(command + ['--token-env', 'BOXLITE_API_KEY'], capture_output=True, text=True)+ self.assertNotEqual(run.returncode, 0)++ def test_helper_does_not_read_credential_environment_or_configuration(self):+ assert_no_credentials = self.assertFalse+ class Environment(dict):+ def __getitem__(self, key):+ # KeyError would be swallowed by get(), hiding a credential read.+ assert_no_credentials(any(part in key.upper() for part in ('TOKEN', 'SECRET', 'API_KEY')),+ 'Helper accessed credential environment')+ return super().__getitem__(key)+ def get(self, key, default=None):+ try:+ return self[key]+ except KeyError:+ return default+ with patch.object(os, 'environ', Environment(os.environ)):+ with self.client() as client:+ transfer.upload(client, 'box-1', self.source, '/workspace/fresh')++ def test_saved_download_refuses_other_sessions_and_ambiguous_results(self):+ project = self.root / 'project'+ directory = project / 'session/tool-results'+ directory.mkdir(parents=True)+ started = time.time_ns() // 1_000_000+ saved = directory / f'mcp-chosen-server-downloadFiles-{started}-first.txt'+ saved.write_text('{}')+ receipt = {'transcriptPath': str(project / 'session.jsonl'), 'connection': 'chosen-server',+ 'started': started, 'finished': started, 'path': str(saved), 'size': saved.stat().st_size}+ encoded = transfer.pack_source(self.source)+ saved.write_text(json.dumps({'base64': encoded}))+ transfer.save_archive(archive_worker.saved_archive(receipt), self.destination)+ self.assertEqual((self.destination / 'binary.bin').read_bytes(), (self.source / 'binary.bin').read_bytes())++ backing = self.root / 'result.txt'+ saved.rename(backing)+ saved.symlink_to(backing)+ storage = self.root / 'storage'+ project.rename(storage)+ project.symlink_to(storage)+ self.assertEqual(archive_worker.saved_archive(dict(receipt, path=str(backing))), encoded)+ with self.assertRaises(transfer.TransferError):+ archive_worker.saved_archive(dict(receipt, path=str(self.source / 'binary.bin')))+ with self.assertRaises(transfer.TransferError):+ archive_worker.saved_archive(dict(receipt, transcriptPath=str(project / 'other.jsonl')))+ (directory / f'mcp-chosen-server-downloadFiles-{started}-second.txt').touch()+ with self.assertRaises(transfer.TransferError):+ archive_worker.saved_archive(receipt)++ def test_download_checks_metadata_and_base64_before_writing(self):+ cases = [{}, {'content': []}, {'content': [{'type': 'text', 'text': 'invalid JSON'}]},+ {'content': None}, {'content': [None]}, {'content': [{'type': 'text', 'text': None}]},+ {'structuredContent': {'base64': '!'}}, {'structuredContent': {'base64': 1}}]+ class Response:+ def __init__(self, value):+ self.value = value+ def call(self, *args):+ return self.value+ for value in cases:+ with self.assertRaises(transfer_hosts.TransferError):+ transfer.download(Response(value), 'box-1', '/workspace/fresh/.', self.destination)+ self.assertFalse(self.destination.exists())+ encoded = base64.b64encode(transfer_archive.Archive.snapshot(self.source).encode()).decode()+ value = {'content': [{'type': 'text', 'text': json.dumps({'base64': encoded})}]}+ transfer.download(Response(value), 'box-1', '/workspace/fresh/.', self.destination)+ self.assertEqual(transfer_archive.Archive.snapshot(self.destination).tree(), transfer_archive.Archive.snapshot(self.source).tree())++ def test_authorized_worker_transfers_selected_names_and_links(self):+ selected = self.source / '.env'+ selected.write_bytes(b'selected contents')+ (self.source / 'alias').symlink_to('.env')+ worker = [sys.executable, str(SCRIPTS / 'archive_worker.py')]+ packed = subprocess.run(worker + ['pack', str(self.source)], capture_output=True)+ self.assertEqual(packed.returncode, 0, packed.stderr)+ saved = subprocess.run(worker + ['save', str(self.destination)], input=packed.stdout, capture_output=True)+ self.assertEqual(saved.returncode, 0, saved.stderr)+ self.assertEqual((self.destination / '.env').read_bytes(), selected.read_bytes())+ self.assertEqual(os.readlink(self.destination / 'alias'), '.env')++ def test_upload_limit_counts_pax_headers_and_final_record_padding(self):+ directory = self.root / 'boundary'+ directory.mkdir()+ source = directory / ('x' * 110)+ largest_record = (8 << 20) // tarfile.RECORDSIZE * tarfile.RECORDSIZE+ # Directory header, PAX header and data, file header, and two end blocks.+ with source.open('wb') as stream:+ stream.truncate(largest_record - 6 * tarfile.BLOCKSIZE)+ self.assertEqual(len(base64.b64decode(transfer.pack_source(directory))), largest_record)+ with source.open('ab') as stream:+ stream.write(b'x')+ with self.client() as client, patch.object(os, 'fdopen', wraps=os.fdopen) as open_stream:+ with self.assertRaisesRegex(ValueError, '8 MiB'):+ transfer.upload(client, 'box-1', directory, '/workspace/data')+ open_stream.assert_not_called()+ self.assertFalse(self.calls())++ def test_download_gnu_sparse_files_preserves_extents_and_logical_size(self):+ def sparse_entry(name, size, offset, data, extent_size=None):+ # Old GNU sparse header layout emitted by the guest's tar-rs packer.+ info = tarfile.TarInfo(name)+ info.type = tarfile.GNUTYPE_SPARSE+ info.mode = 0o755+ info.size = len(data)+ header = bytearray(info.tobuf(tarfile.GNU_FORMAT))+ if extent_size is None:+ extent_size = len(data)+ for start, value in ((386, offset), (398, extent_size), (483, size)):+ header[start:start + 12] = b'%011o\0' % value+ header[148:156] = b' ' * 8+ header[148:156] = b'%06o\0 ' % sum(header)+ return header + data + b'\0' * (-len(data) % tarfile.BLOCKSIZE)++ size = 16 << 20+ raw = (sparse_entry('empty.img', 1 << 20, 1 << 20, b'')+ + sparse_entry('disk.img', size, size // 2, b'payload') + bytes(1024))+ (self.root / 'uploaded.tar').write_bytes(raw)+ with self.client() as client:+ transfer.download(client, 'box-1', '/workspace/data', self.destination)+ self.assertEqual((self.destination / 'empty.img').stat().st_size, 1 << 20)+ path = self.destination / 'disk.img'+ self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o700)+ self.assertEqual(path.stat().st_size, size)+ with path.open('rb') as stream:+ stream.seek(size // 2 - 1)+ self.assertEqual(stream.read(9), b'\0payload\0')+ # A claimed extent must fit both the stored data and the logical file.+ for offset, extent_size in ((0, 8), (size - 1, 7)):+ raw = sparse_entry('invalid', size, offset, b'payload', extent_size) + bytes(1024)+ with self.subTest(offset=offset), self.assertRaisesRegex(ValueError, 'sparse extent'):+ transfer.save_archive(base64.b64encode(raw), self.root / 'invalid-download')+ self.assertFalse((self.root / 'invalid-download').exists())++ def test_existing_download_destination_is_refused_before_call(self):+ with self.client() as client, self.assertRaises(transfer_hosts.TransferError):+ transfer.download(client, 'box-1', '/workspace/data/.', self.source)+ self.assertFalse(self.calls())++ def test_untrusted_archive_paths_and_special_files_are_rejected(self):+ for name, kind in [('../outside', tarfile.REGTYPE), ('/outside', tarfile.REGTYPE),+ ('fifo', tarfile.FIFOTYPE)]:+ stream = io.BytesIO()+ with tarfile.open(fileobj=stream, mode='w') as archive:+ member = tarfile.TarInfo(name)+ member.type = kind+ member.linkname = '/outside'+ archive.addfile(member)+ with self.assertRaises(ValueError):+ transfer_archive.Archive.decode(stream.getvalue())+ self.assertFalse(self.destination.exists())++ def test_download_requires_a_complete_tar_end_marker(self):+ archive = transfer_archive.Archive()+ archive.add('first', b'a')+ archive.add('second', b'b')+ encoded = archive.encode()+ with tarfile.open(fileobj=io.BytesIO(encoded), mode='r:') as reader:+ second = reader.getmember('second').offset+ end = reader.offset++ class Response:+ def call(self, *args):+ return {'structuredContent': {'base64': base64.b64encode(raw).decode()}}++ damaged = bytearray(encoded)+ damaged[second] ^= 1+ for label, raw in (('truncated', encoded[:second]), ('short footer', encoded[:end + 512]),+ ('corrupt header', damaged)):+ destination = self.root / label+ with self.subTest(label=label):+ with self.assertRaises(ValueError):+ transfer.download(Response(), 'box-1', '/workspace/data', destination)+ self.assertFalse(destination.exists())+ raw = encoded[:end + 1024]+ transfer.download(Response(), 'box-1', '/workspace/data', self.destination)+ self.assertEqual((self.destination / 'second').read_bytes(), b'b')++ def test_download_write_failure_can_retry_at_the_same_path(self):+ archive = transfer_archive.Archive()+ archive.add('first', b'a')+ archive.add('nested/second', b'b')+ open_file = os.open++ def fail_second(path, flags, *args, **kwargs):+ if path == 'second' and flags & os.O_CREAT:+ raise OSError(errno.ENOSPC, 'fixture disk is full')+ return open_file(path, flags, *args, **kwargs)++ before = set(self.root.iterdir())+ with patch.object(os, 'open', fail_second), self.assertRaises(OSError):+ archive.save(self.destination)+ self.assertEqual(set(self.root.iterdir()), before)+ archive.save(self.destination)+ self.assertEqual((self.destination / 'nested/second').read_bytes(), b'b')++ def test_download_never_replaces_a_directory_created_during_write(self):+ archive = transfer_archive.Archive()+ archive.add('one', b'a')+ open_file = os.open++ def create_destination(path, flags, *args, **kwargs):+ if path == 'one' and flags & os.O_CREAT:+ self.destination.mkdir(exist_ok=True)+ return open_file(path, flags, *args, **kwargs)++ before = set(self.root.iterdir())+ with patch.object(os, 'open', create_destination), self.assertRaises(FileExistsError):+ archive.save(self.destination)+ self.assertEqual(list(self.destination.iterdir()), [])+ self.assertEqual(set(self.root.iterdir()), before | {self.destination})++ def test_host_reads_multiple_frames_from_one_write(self):+ script = 'import os; os.write(1, b\'{"text":"abc"}\\n{"id":2}\\n\')'+ child = transfer_hosts.HostProcess([sys.executable, '-c', script], self.root)+ try:+ self.assertEqual(child.receive(), {'text': 'abc'})+ self.assertEqual(child.receive(), {'id': 2})+ finally:+ child.close()++ def test_group_signal_permission_errors_still_close_and_reap_the_child(self):+ for refused in (signal.SIGTERM, signal.SIGKILL):+ with self.subTest(signal=refused):+ host = transfer_hosts.HostProcess([sys.executable, '-c', ''], self.root)+ host.process.wait(timeout=5)++ def signal_group(pid, sig):+ if sig == refused:+ raise PermissionError(errno.EPERM, 'fixture signal denied')++ with patch.object(os, 'killpg', signal_group), patch.object(host.process, 'wait', wraps=host.process.wait) as wait:+ host.close()+ wait.assert_called()+ self.assertTrue(host.process.stdin.closed)+ self.assertTrue(host.process.stdout.closed)++ def test_file_transfer_preserves_single_file_landing_and_owner_permissions(self):+ single = self.source / 'start.sh'+ single.write_bytes(b'fixture')+ single.chmod(0o500)+ with self.client() as client:+ transfer.upload(client, 'box-1', single, '/workspace/start.sh')+ transfer.download(client, 'box-1', '/workspace/start.sh', self.destination)+ with tarfile.open(self.root / 'uploaded.tar') as archive:+ self.assertEqual([(member.name, member.mode) for member in archive], [('start.sh', 0o500)])+ downloaded = self.destination / 'start.sh'+ self.assertEqual(stat.S_IMODE(downloaded.stat().st_mode), 0o500)+ self.assertEqual(downloaded.read_bytes(), b'fixture')+ single.chmod(0o755)+ with tarfile.open(fileobj=io.BytesIO(transfer_archive.Archive.snapshot(self.source).encode())) as archive:+ self.assertTrue(archive.next().isdir())+ self.assertEqual(archive.getmember('start.sh').mode, 0o700)+ self.assertEqual(archive.getmember('binary.bin').mode, 0o600)++ def test_explicit_directory_permissions_on_upload_and_download(self):+ assets = self.source / 'assets'+ assets.mkdir()+ (assets / 'logo').write_bytes(b'logo')+ assets.chmod(0o555)+ self.source.chmod(0o555)+ with self.client() as client:+ transfer.upload(client, 'box-1', self.source, '/workspace/site')+ with tarfile.open(self.root / 'uploaded.tar') as archive:+ with self.subTest(direction='upload'):+ self.assertEqual([archive.getmember(p).mode for p in ('.', 'assets')], [0o500, 0o500])++ raw = io.BytesIO()+ with tarfile.open(fileobj=raw, mode='w') as archive:+ for name in ('.', 'assets'):+ directory = tarfile.TarInfo(name)+ directory.type, directory.mode = tarfile.DIRTYPE, 0o555+ archive.addfile(directory)+ logo = tarfile.TarInfo('assets/images/logo')+ logo.size = 4+ archive.addfile(logo, io.BytesIO(b'logo'))+ (self.root / 'uploaded.tar').write_bytes(raw.getvalue())+ with self.client() as client:+ transfer.download(client, 'box-1', '/workspace/site/.', self.destination)+ self.assertEqual((self.destination / 'assets/images/logo').read_bytes(), b'logo')+ for path, mode in (('.', 0o500), ('assets', 0o500), ('assets/images', 0o700)):+ with self.subTest(download=path):+ self.assertEqual(stat.S_IMODE((self.destination / path).stat().st_mode), mode)++ def test_download_reports_when_published_files_no_longer_match_requested_path(self):+ parent = self.root / 'parent'+ parent.mkdir()+ moved = self.root / 'moved'+ destination = parent / 'download'+ archive = transfer_archive.Archive()+ archive.add('report', b'fixture')+ publish = transfer_archive._publish_directory++ def move_and_publish(*args):+ parent.rename(moved)+ parent.mkdir()+ publish(*args)++ with patch.object(transfer_archive, '_publish_directory', move_and_publish):+ with self.assertRaisesRegex(ValueError, 'written.*requested path'):+ archive.save(destination)+ self.assertFalse(destination.exists())+ self.assertEqual((moved / 'download/report').read_bytes(), b'fixture')++ def test_archive_boundaries_are_checked_before_filesystem_writes(self):+ for names in [('same', 'same'), ('parent', 'parent/file'), ('parent/file', 'parent')]:+ stream = io.BytesIO()+ with tarfile.open(fileobj=stream, mode='w') as archive:+ for name in names:+ archive.addfile(tarfile.TarInfo(name))+ with self.assertRaises(ValueError):+ transfer_archive.Archive.decode(stream.getvalue())+ for name in ('bad\\name', '', 'bad\nname'):+ with self.assertRaises(ValueError):+ transfer_archive.Archive().add(name, b'x')+ with self.assertRaises(ValueError):+ transfer_archive.Archive().add('.', b'not a directory')+ link = ('alias', transfer_archive.SymbolicLink('target'))+ child = ('alias/file', b'fixture')+ for first, second in [(link, child), (child, link)]:+ archive = transfer_archive.Archive()+ archive.add(*first)+ with self.assertRaisesRegex(ValueError, 'conflict'):+ archive.add(*second)+ with self.assertRaises(ValueError):+ transfer_archive.Archive.decode(b'truncated')+++if __name__ == '__main__':+ unittest.main()