Backport the existing master guard so this long-lived feature worktree does not fan out Git scans across its cloned workspace inventory.
Co-Authored-By: Paperclip <noreply@paperclip.ing>
Removing an app only flipped the connection to `archived`. Everything that
made it work stayed behind: the operator's pasted key or OAuth tokens as live
secrets, the `company_secret_bindings` that project them into runtimes, the
install, the app-managed `app:<connectionId>` profile, gateway tokens minted
against that profile, and any authorization still in flight. Reconnecting
reused the retained credential, so "remove" never actually revoked anything.
Removal is now a teardown, and the order is the security property. Every
database-side access path closes first — grants revoked, bindings and installs
deleted, the app profile removed (archived instead when a gateway's RESTRICT
foreign key forbids deleting it, with that gateway's tokens and sessions
revoked), live local runtimes stopped, catalog entries marked `removed`,
outstanding OAuth state discarded, the connection and its application archived
— so the app is undispatchable before the first call out to a secret provider.
Only then are the credentials revoked, and each secret's ref survives until
that secret is gone: a provider that errors leaves the operation failed closed
and resumable, because the secret row is marked deleted before the provider
call and the surviving refs are what a retry reads to finish the job.
A secret is destroyed only when two independent tests agree: it was minted
into the `tool_app.` namespace by connect/reconnect/OAuth, and nothing outside
this connection references it. Anything ambiguous keeps its row and is
reported as retained — deleting a credential another target still resolves is
an outage, retaining an unreachable row is not.
What stays is deliberate. Connection and application identity, names and
activity survive so a reconnect reuses them, but with no credential, install
or profile, reconnecting has to ask for fresh authentication and rebuild
access. The activity receipt carries cleanup counts only; six of those count
keys name what they counted ("secrets", "token"), so `sanitizeRecord` lets
them through while the value is a finite number and still blanks the same key
carrying anything else.
Refs PAP-17119, PAP-17118, PAP-17089 (QA finding F6).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Map OAuth origin, duplicate-name, and DNS failures to stable operator guidance, and derive collision-resistant defaults from host, port, and path.
Co-Authored-By: Paperclip <noreply@paperclip.ing>
Prevent connection installs from adding connection-wide allow entries, keep wizard-managed app profiles additive across binding precedence, and repair legacy over-grants with a data migration. Add decision-level regression coverage for generic and curated MCP paths.
Co-Authored-By: Paperclip <noreply@paperclip.ing>
Preserve the unverified-server trust marker on URL-only connection details and compact the mobile action step above the bottom nav.
Co-Authored-By: Paperclip <noreply@paperclip.ing>
A denial or a cancel is a final answer to an authorization request, but
`completeOAuthCallback` treated it as merely a failed callback: the row
in `tool_oauth_states` survived, so the `state` the user just refused
stayed completable for the rest of its 10-minute TTL by anyone who could
produce a code. Any linked `request_confirmation` also stayed `pending`,
so the board kept offering an authorization link for a flow the user had
already declined and the requesting agent never learned the answer.
Route every terminal callback — success, denial, cancel — through one
`consumeOAuthState` helper. Two properties pull in opposite directions
and both matter:
- a stranger's callback must not *consume* the request, so the row is
loaded and bound to the caller (expiry, actor type/id, session, or the
subject user) before anything is deleted, and a failed binding check
leaves the victim's flow live and completable;
- a replayed callback must not *complete* the request, so the delete is
the single statement that decides ownership — `DELETE … RETURNING`
hands the row to exactly one of two concurrent callbacks and the loser
is told the state is spent rather than exchanging a code against it.
A denial then resolves any linked interaction as `rejected`, scoped to a
still-`pending` row so a board user who answered the card directly keeps
their own answer, with a Paperclip-authored reason rather than the
provider's.
The message and its `providerError` label are PAP-17108's, unchanged.
Five regression tests, both negative-controlled: a code obtained before
a denial can no longer be exchanged; an unrecognized cancel code behaves
the same; another session's or another user's denial is refused without
spending the request, which the owner then completes; the board's prompt
ends `rejected`; and two simultaneous callbacks produce exactly one
token exchange. That last one needs a second database handle — this
driver pipelines everything issued through one handle, which serializes
the two callbacks and makes a non-atomic delete pass — and it has to
connect before racing, or the first callback wins uncontested.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A generic remote MCP connection points at an arbitrary authorization server, so
`error`, `error_description`, `error_uri` and the response body are all
attacker-chosen. Paperclip was returning the provider's `error_description`
verbatim as the public error message on the callback-denial, token-exchange and
dynamic-client-registration paths, and the callback did it before validating the
state at all. A hostile provider could therefore plant a canary secret, ANSI
escapes, or "paste your recovery key here" instructions into API responses,
board UI copy, and 4xx log lines — in Paperclip's own voice.
The operator now only ever reads text Paperclip authored:
- `normalizeOAuthProviderError` reduces the provider's `error` to a bounded,
allowlisted label (RFC 6749 §4.1.2.1/§5.2, RFC 7591 §3.2.2, OIDC Core
§3.1.2.6). An unrecognized code collapses to `unrecognized` rather than being
echoed, since the label is still untrusted input.
- `oauthProviderErrorMessage` maps that label to stable Paperclip copy. The
label plus the upstream HTTP status stay in structured `details` for
diagnosis; the description and body are never read on any path.
- `error_description` is gone from the callback route and from the
`completeOAuthCallback` input type, so there is nothing left to reflect
through, and `redactSensitive` scrubs it from the request query that
`customProps` copies into 4xx log lines.
- The callback validates the state binding and the actor before acting on a
provider-reported failure, and consumes the state so a denial is terminal.
Refresh goes through the same token-exchange path, and revocation makes no
provider call, so both are covered. Tests plant a canary secret, ANSI escapes
and markdown in `error_description` and assert none of it reaches an API
response, a thrown message, a console line, an audit row or an activity detail;
both assertions were negative-controlled by restoring the reflection.
PAP-17108. Finding 3 of the PAP-17088 security review.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Pinning to `approved[0]` alone dropped the failover `fetch` gave a
multi-homed host, so one dead A record took the whole connection down.
Walk the approved addresses in resolution order instead — but only for
addresses that are unreachable. A peer that answers from an unapproved
address is the rebinding defence firing, not a reachability problem, so
it still fails closed on the first try rather than being retried past.
Also close the gaps the response deadline left behind:
- a connect timeout used to leak the half-open socket, since nothing
above that point owned it yet;
- both deadlines threw bare `Error`s, so callers that switch on the
guard's error codes saw a timeout as an unclassified failure — they
now carry `remote_http_response_timeout`;
- a finished response left an armed socket timer behind; and
- the default deadline drops from undici's 300 s to 30 s, which is
already generous for metadata discovery, a token exchange or a
JSON-RPC round trip. `tools/call` owns a caller-set budget an operator
can raise to 60 s, so it passes `responseTimeoutMs` explicitly rather
than being truncated by the tighter default.
Covers each with a regression test, including a peer that dribbles
header bytes forever — the case that rules out `req.setTimeout`, whose
idle clock such a peer can reset indefinitely.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A generic remote MCP connection lets the server it points at advertise its own
authorization-server metadata, and `authorization_endpoint` was accepted as an
arbitrary string: `startOAuth` built a `URL` from it and the board passed the
result to `window.location.assign`. A hostile server could therefore advertise
`javascript:`/`data:` to run script in the board's origin, `file:` to read a
local path, or plain `http:`/a credential-bearing URL to downgrade or disguise
where the operator was being sent.
Parse every OAuth endpoint through one shared validator instead — discovered
metadata, `WWW-Authenticate` hints, pasted/persisted config, and gallery
defaults alike. It requires https (loopback http only under the existing
local-development policy, plus this deployment's own origin, which is how the
smoke-lab fixture is served), and rejects embedded credentials, fragments and
malformed values. Discovery drops an unusable endpoint so a second advertised
authorization server still gets a chance, and raises the refusal only if nothing
safe was found — so an unsafe value is never persisted and never reported as a
bare "does not advertise OAuth sign in". The token and registration endpoints go
through the same gate, so a row written before this existed cannot send a code or
client secret over plaintext.
The board applies the same validator at the navigation boundary rather than
trusting the response body, and — since a valid HTTPS page can still phish —
names the authorization host on the redirect screen while keeping the
"Unverified server" label.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The pinned transport replaced platform fetch, and with it undici's
headersTimeout/bodyTimeout. Only the gateway tools/call path passes an
AbortSignal; the OAuth discovery, registration and token-exchange callers
pass none, so a remote server that accepted the connection and then stayed
silent would hold the request open indefinitely. That is a hang the code
this replaced did not have.
Adds a 300s default matching undici, applied as a hard headers deadline
(not req.setTimeout, which is socket-idle based and a dribbling server
could reset forever) plus an idle deadline between body chunks so a
half-sent body rejects in response.text() instead of hanging the caller.
Both new tests hang to the vitest timeout when the deadlines are removed.
Refs PAP-17098
assertPublicRemoteHttpEndpoint resolved an operator-supplied hostname,
approved it, and then handed the *hostname* to global fetch, which
resolved it a second time. A name server the attacker controls can answer
with a public address for the guard's lookup and a loopback, RFC 1918 or
link-local address for the connection, so an authenticated public
deployment could be walked onto internal services or cloud metadata.
The guard now returns the address set it approved, and
guardedRemoteHttpFetch dials that address itself: one resolution, no
second lookup below it, the original hostname kept for Host, TLS SNI and
certificate identity, and a peer-address check before a single request
byte (or ClientHello) is written. Redirects stay manual so the caller
re-runs the whole guard on every hop it follows.
Wired into all three guard-then-fetch sites: OAuth discovery/registration/
token exchange, catalog tools/list, and the gateway tools/call path.
Two cases keep platform fetch, both because there is nothing to pin:
deployments that allow private endpoints, and URLs that already carry an
IP literal.
Regression coverage models the rebinding name server deterministically —
public on the first answer, 127.0.0.1 after it — and proves the request
lands on the approved address while the loopback listener sees no
connection at all. Reintroducing either half of the fix (a second lookup
at dial time, or dropping the peer check) turns those tests red.
Residual risk unchanged: egress allowlisting and network policy are still
recommended as defence in depth.
Refs PAP-17098
Add GENERIC-REMOTE-MCP.md: the two operator routes, what the guided flow does
with each kind of endpoint, header-safety rules, and the registration preference
order with its client-binding and re-registration behaviour.
Correct the connector playbook, which read as though a curated `AppDefinition`
were required and as though `ownershipModes` gated registration generally. It now
opens by saying a catalog entry is the optional branded convenience layer, and its
DCR section describes all four registration tiers, the public-HTTPS requirement
for CIMD, the issuer/resource/callback/company binding, and the path-aware
discovery and `iss`/`resource` conformance the broker now implements.
Note on the PostHog doc that the curated flow is preferable but not required —
which is exactly what the acceptance demo has to establish.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Pasting an MCP URL now walks the operator through whatever the endpoint turns out
to need. The simple path is unchanged in length — address, name, "does it need a
key?" — but the dead ends are gone: an endpoint that wants browser sign-in goes
to sign-in instead of a "coming soon" toast, and an invalid, private-network,
unreachable, or credential-demanding endpoint says which of those it was and
which field to change, inline, next to that field.
Advanced authentication adds the explicit choices for operators who already know:
no sign-in, key or token, custom headers, or browser sign-in with a client they
registered themselves. Header values become Paperclip secrets and are rejected
client-side before a round trip if Paperclip wouldn't send them. The choices are
phrased as how the *server* authenticates; nothing on this screen mentions DCR,
CIMD, PKCE or an RFC, and a test asserts that stays true.
The endpoint host and "Unverified server" now ride on the step header, so they
stay visible through review, access and install rather than only on the screen
where the address was pasted. A curated definition matching the endpoint is
offered as a branded shortcut beside — not instead of — the generic form.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
An operator who only knows a tool's name has nothing to paste. Add a compact
question-mark control that hands them a ready-made request for an agent: research
the official docs, reply with one paste-ready `mcpServers` JSON object first, use
placeholders for every credential, then explain how to get each one.
The prompt is a constant in shared, deliberately not a template. Nothing about
the company, the endpoint, the pasted config, or a secret can reach it, so
"opening or copying help makes no connection or import request" holds by
construction rather than by review — and a server test lifts the JSON example
straight out of the prompt and runs the real preview parser on it, so the prompt
and the parser cannot drift apart.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
One in-process fetch fixture stands in for an MCP server plus its authorization
server, so the whole generic path — discovery, registration, authorization,
catalog, review, install, revoke — is deterministic and needs no network or
vendor credentials. Every case deliberately connects by URL and never names a
gallery app, and asserts the connection carries no `sourceTemplateKey`, so a
regression that reintroduced a dependency on curated metadata would fail here.
Covers public/bearer/custom-header endpoints, the four registration tiers and
their preference order, RFC 8707 `resource` on authorize and token, RFC 8414 and
OIDC-suffix discovery for a pathful issuer, `iss` acceptance and mismatch,
re-registration on a moved callback, refusal to auto-re-register over an
operator-supplied client, SSRF rejection, company isolation, secret redaction in
config/refs/API readback, and a client metadata document with no tenant data.
The manual-client binding test caught a real bug: a pasted client's callback was
never stamped on first use, so its binding check would have accepted any
callback forever. Fixed alongside.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
An unknown standards-compliant MCP endpoint could discover an OAuth challenge
but never complete one: `ensureOAuthClient` only reached registration when a
gallery `AppDefinition` method listed `ownershipModes: ["dcr"]`, so a URL-only
connection died on "OAuth client id is not configured".
Replace that gate with the registration preference the current MCP
client-registration guidance recommends — a client the deployment preconfigured
for the issuer, then a Client ID Metadata Document, then dynamic registration,
then client credentials the operator preregistered — and allow a generic
connection to register only after protected-resource/authorization-server
discovery actually produced a metadata document. Client material is bound to
issuer, MCP resource, callback URI and company, and re-registers when any of
those move; a manually supplied client refuses to auto-re-register and asks the
operator instead.
Bring the broker in line with current guidance along the way: RFC 8707
`resource` on authorization, token and refresh requests; RFC 8414 and OIDC
path-aware `.well-known` variants for pathful issuers, with the issuer in the
document validated against the one used to build the URL; RFC 9207 `iss`
validated on the callback when returned; `application_type: web` on DCR; and
`authKind`/issuer/resource persisted so refresh, reconnect, revoke and
diagnostics stop treating a generic connection as `authKind: none`.
Header names and values from a pasted config are re-checked here, at the last
point before they become real request headers.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The guided "Connect your own MCP server" flow and the paste-config escape
hatch both let an operator name arbitrary request headers for an arbitrary
endpoint, and those names reach a real outbound fetch. Validate them once in
shared code rather than at each call site: RFC 9110 token names only, no
hop-by-hop/framing/routing/ambient-credential headers, and no control
characters in values.
Also add the generic-auth inputs the guided flow needs (`authMode`, a
preregistered `oauthClient`) and the auth-challenge shape the wizard branches
on, so a URL-only connection can describe what the endpoint asked for.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Default PostHog to broad tool access, move optional filters and response mode behind a reusable Advanced disclosure, and codify the connection UX rule in the bundled integration skill and playbook.
Co-Authored-By: Paperclip <noreply@paperclip.ing>
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Runs on sandbox execution targets spend their first minutes in
preparation phases — config seed, workspace and skills sync into the
sandbox — before the agent CLI produces its first transcript token
> - The engine already reports these phases through the runtime-progress
mechanism (`onRuntimeProgress` →
`recordCurrentHeartbeatRunRuntimeProgress` → `currentStatusMessage` on
the live run), and the pre-task-chat issue view surfaced them in its
live status line
> - The chat-style task view's live tail dropped that affordance: with
zero renderable transcript entries it shows an opaque "Waiting for
transcript..." for minutes, which reads as a hang (and prompted a real
is-this-broken investigation on a healthy run)
> - This pull request surfaces the live run's `currentStatusMessage` as
the tail's empty-state message, with the generic wait text as fallback
> - The benefit is that operators watching a sandbox run see "Syncing
workspace to sandbox" instead of wondering whether the run is stuck —
for every adapter, with no adapter identities involved
## Linked Issues or Issue Description
**What existing behavior does this improve?**
The chat-style task view's live transcript tail (`TaskChatThread` →
`TaskChatLiveTail`), introduced with the experimental chat-style task
view.
**Current behavior**
While a live run has no renderable transcript entries yet — the normal
state for the multi-minute sandbox preparation window — the tail shows a
static "Waiting for transcript...". The run's live
`currentStatusMessage` (e.g. "Syncing workspace to sandbox", emitted by
the sandbox-managed runtime's progress reporting) is available on the
same live-run object but unused by this surface, although the earlier
issue-chat view did display it.
**Proposed behavior**
When the tail is streaming a live run and no transcript rows exist yet,
the empty-state message prefers the run's `currentStatusMessage`; the
generic wait text remains the fallback when no runtime status has been
reported (e.g. local runs that produce output immediately, or the brief
pre-status window).
**Reason and benefit**
The preparation phases are real, reportable progress that the engine
already emits. Showing them turns a minutes-long apparent hang into a
legible status, for every adapter and execution target, using data the
view already receives.
## What Changed
- `ui/src/components/TaskChatThread.tsx`: the live tail's `emptyMessage`
prefers `liveRun.currentStatusMessage` (guarded to the run the tail is
actually streaming) over the static "Waiting for transcript..."
fallback. Queued runs keep "Waiting to start...".
- `ui/src/components/TaskChatThread.test.tsx`: a test covering both
branches — a live run with a runtime status shows it (and not the wait
text), and a run without one keeps the generic message.
## Verification
- `vitest run ui/src/components/TaskChatThread.test.tsx
ui/src/components/task-chat/TaskChatLiveTail.test.tsx`: 22/22 pass
(including the new test)
- `pnpm --filter @paperclipai/ui typecheck`: clean
- Reproduced live: a `claude_local` run on a Daytona sandbox environment
showed "Waiting for transcript..." for the full sync window; with this
change the same window shows the streamed preparation statuses
## Risks
- Low: a one-expression change to an empty-state string, active only
while a live run has produced no renderable transcript rows. The
fallback path is byte-identical to today.
- `currentStatusMessage` is truncated/humanized upstream by the
runtime-progress reporter; this surface renders it verbatim in the same
muted style as the wait text.
## Model Used
- Anthropic, **Claude Fable 5** (`claude-fable-5`) via Claude Code, with
repository, shell, and Git tooling. It traced the runtime-progress
mechanism end-to-end (engine emitter → heartbeat recorder → live-run API
→ both thread views), identified the dropped affordance in the
chat-style view, and wrote the fix and test.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
Auto-generated lockfile refresh after dependencies changed on master.
This PR only updates pnpm-lock.yaml.
Co-authored-by: lockfile-bot <lockfile-bot@users.noreply.github.com>
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Local agent adapters (`claude_local`, `gemini_local`, `grok_local`,
…) are the integration surface that lets Paperclip run coding CLIs on
the host machine
> - The Kimi Code CLI (`kimi`, Moonshot AI) has a documented
non-interactive mode, `kimi -p --output-format stream-json` with session
resume via `kimi -r`, but Paperclip has no built-in adapter for it
> - So Kimi users (especially Kimi membership / OAuth subscribers)
cannot onboard their CLI to Paperclip agent teams
> - This pull request adds a complete built-in `kimi_local` adapter
(both execution engines, session management, instructions + skills
delivery, thinking-effort control, environment test, UI and CLI modules,
docs) following the established `gemini_local`/`grok_local` package
pattern
> - Kimi Code ships an ACP server (`kimi acp`), so the adapter runs on
Paperclip's shared acpx engine by default (streaming transcript with
live tool status, like `claude_local`/`gemini_local`) and falls back to
a headless CLI lane (`kimi -p --output-format stream-json`) when ACP
prerequisites are unavailable
> - The benefit is that Kimi Code becomes a first-class Paperclip agent
lane: selectable in the UI, resumable across heartbeats, with the same
operating context (instruction bundle, skills, effort) and streaming
transcript the other local adapters get
## Linked Issues or Issue Description
- Supersedes #9880 (same branch; expanded from the CLI-only lane into a
complete adapter with the default ACP engine lane, control-plane skill
install, and live transcript wiring)
- Refs #9879 (adapter request for Kimi Code CLI, filed with this PR)
- Refs #163 (original Kimi support request)
Duplicate/related prior PRs, per the dedup search (both appear stale: no
updates or maintainer review since May 2026, and both target an older
Kimi CLI interface; calling them out for reviewer context per
CONTRIBUTING.md):
- Refs #6276 (`feat: add kimi-local adapter`): targets an older
array-based content format (`{type: think}`/`{type: text}` blocks), not
the current documented stream-json schema
- Refs #5202 (`feat(adapter): add Kimi CLI local adapter with Wire
protocol support`): builds on a `--wire` JSON-RPC interface that current
Kimi Code CLI (0.27.0) no longer documents; the current documented
headless interface is `-p --output-format stream-json`
This PR is a fresh implementation against current master and the
currently documented/verified Kimi CLI behavior (see Verification).
Happy to fold in anything useful from the earlier attempts if a reviewer
prefers.
## What Changed
- **New adapter package** `packages/adapters/kimi-local`
(`@paperclipai/adapter-kimi-local`), modeled on
`gemini-local`/`grok-local`:
- `src/server/execute.ts`: spawns `kimi -p <prompt> --output-format
stream-json` (argv array, no shell), `-m <model>` only when configured,
`-r <sessionId>` when the stored session cwd matches the run cwd,
automatic fresh-session retry on unrecoverable-session errors,
headless-safe env (`CI=1`, `NO_COLOR=1`, `KIMI_CODE_NO_AUTO_UPDATE=1`,
`TERM=dumb`; user-configured values win), full remote (ssh/sandbox)
execution lane with runtime install via `@moonshot-ai/kimi-code`
- **Instruction bundle delivery**: the prompt path directive now names
the sibling instruction files (`./HEARTBEAT.md`, `./SOUL.md`,
`./TOOLS.md`) alongside the prepended entry file, and local runs pass
`--add-dir <instructions-dir>` so Kimi can actually open them (matching
`claude_local`). Without this, only the entry file reached Kimi and
agents improvised the operating workflow that `HEARTBEAT.md` documents
- **Thinking effort**: a configured `effort` is forwarded as the
`KIMI_MODEL_THINKING_EFFORT` operational override (Kimi has no
per-invocation effort flag). It is only sent for models that advertise
`support_efforts` (currently `kimi-code/k3`) to avoid provider
rejections, and `medium` maps to `high` since Kimi has no medium tier
(`low`/`high`/`max` pass through)
- **Skills delivery**: desired Paperclip skills are delivered via Kimi's
`--skills-dir` flag from a dedicated per-run directory (a local
snapshot, or the synced snapshot on remote targets), so skills load
reliably and in isolation. Paperclip never overwrites the shared
`$KIMI_CODE_HOME/skills` home, so skills installed by the operator or
other agents are left intact. `--skills-dir` is only passed when at
least one skill is desired, so unconfigured agents keep Kimi's default
skill discovery
- **Live run status**: the adapter now forwards each streamed
stream-json line to `onEvent` (assistant `content` as an assistant
snippet, `tool_calls` as tool-name events), which drives the
issue-thread activity indicator (`currentToolName` /
`lastAssistantSnippet` / `lastEventAt`). Previously the adapter only
wrote the raw run log, so the issue thread showed a stale "no output for
N s" line with no tool or reasoning context while Kimi worked. Tool
results are omitted so the last meaningful "Using X" / snippet is not
overwritten by a generic label
- `src/server/parse.ts`: parses the verified Kimi stream-json event
shapes (`assistant` text, `assistant.tool_calls` with JSON-string
arguments, `tool` results, trailing `meta.session.resume_hint` for
session-id capture) plus failure classifiers (`kimi_auth_required`,
transient network, unrecoverable session). A signaled exit (null exit
code, not a timeout) is now reported as a failure rather than coalesced
to success, and the error message names the terminating signal
- `src/server/skills.ts`: lists/syncs Paperclip skills for the adapter's
skill-management surface
- `src/server/test.ts`: environment test covering CLI resolution + `kimi
--version`, cwd check, auth detection (OAuth credential dirs, keyed
`[providers.*]` in config.toml, or the `KIMI_MODEL_NAME` +
`KIMI_MODEL_API_KEY` env pair), and a live hello probe
- `src/ui/` (stdout-line parser for transcripts, config builder) and
`src/cli/` (stream event formatter) modules
- Root metadata: three managed model aliases
(`kimi-code/kimi-for-coding`, `kimi-code/kimi-for-coding-highspeed`,
`kimi-code/k3`), effort-capable-model metadata (`EFFORT_CAPABLE_MODELS`,
effort mapping helpers), `agentConfigurationDoc`
- Tests: 101 tests across parse, execute (args building, resume gating,
retry, auth error code, timeout, signaled-exit failure, effort
forwarding/gating/mapping, `--add-dir` instructions directive,
`--skills-dir` gating, `onEvent` runtime-event forwarding), ACP engine
(engine resolution, acpx config build, node-version gate), ACP
transcript delegation, environment test, UI parse/build-config
- **ACP engine lane (default)** (`src/server/acp.ts` + shared
`adapter-utils/acpx-engine`): Kimi Code ships an ACP server (`kimi
acp`), so `kimi_local` now runs on Paperclip's shared acpx engine by
default, matching `claude_local`/`codex_local`/`gemini_local`. The
issue-thread transcript streams live (assistant text deltas, tool calls
with a `pending`->`completed` status lifecycle) instead of the CLI
lane's bursty complete-message output. Registered `kimi_local -> "kimi"`
in `ACPX_ADAPTER_AGENT_IDS` and resolved the built-in agent command to
`kimi acp`; `execute.ts` dispatches to the ACP executor first with an
automatic CLI fallback when ACP prerequisites fail (`engine=acp`
requires ACP, `engine=cli` pins the headless lane); `index.ts` falls
back to the shared acpx session codec; the UI/CLI delegate `acpx.*`
events to the shared acpx transcript parser and event formatter. The
headless CLI lane (above) remains as the fallback
- **Registration** (one entry each, mirroring existing adapters): server
adapter registry + `BUILTIN_ADAPTER_TYPES`, `AGENT_ADAPTER_TYPES`
(shared), UI adapter registry + display registry (`Kimi Code`, Moon
icon) + capabilities defaults, CLI adapter registry, `Dockerfile`
(package copy + `npm install --global @moonshot-ai/kimi-code@latest`),
`vitest.config.ts` workspace, `scripts/release-package-manifest.json`
- **Behavioral sets** mirroring `gemini_local` (Kimi resumes sessions
the same way): `GIT_SENSITIVE_LOCAL_ADAPTER_TYPES`,
`SESSIONED_LOCAL_ADAPTERS` (heartbeat + recovery),
`REMOTE_MANAGED_ADAPTERS`, ssh/sandbox execution-target allow-lists,
`ADAPTER_DEFAULT_RULES_BY_TYPE` (`timeoutSec: 0`, `graceSec: 15`), and
`LEGACY_SESSIONED_ADAPTER_TYPES` + `ADAPTER_SESSION_MANAGEMENT` in
adapter-utils
- **UI touch-points**: New Agent default-model branch, AgentConfigForm
command map (`kimi_local: "kimi"`) + model defaults + a Kimi-specific
thinking-effort option list (`Low`/`High`/`Max`, reflecting Kimi's tiers
rather than borrowing Claude's), OnboardingWizard (command map, model
default, `kimi login` / `KIMI_MODEL_NAME + KIMI_MODEL_API_KEY` auth
hints, manual-debug command line), InviteLanding enabled adapters
- **Control-plane skill install** (`cli/src/commands/client/agent.ts`):
`paperclipai agent local-cli` seeded the Paperclip control-plane skills
into `~/.codex/skills` and `~/.claude/skills` so Codex/Claude agents
auto-discover the API reference every run. Kimi had no equivalent
target, so `kimi_local` agents began each session without the
control-plane skill and rediscovered routes (e.g. the company-scoped
`POST /api/companies/{companyId}/issues`) by trial and error. Added
`~/.kimi-code/skills` (honoring `KIMI_CODE_HOME`) as a third install
target for parity. Independent of the per-run `--skills-dir` delivery,
which only applies to explicitly configured skills.
- **Docs**: `docs/adapters/kimi-local.md` (prerequisites, auth options,
config fields including `effort`, session resume, instruction bundle,
skills delivery, control-plane skill install) + a row in
`docs/adapters/overview.md`
Out of scope (deliberately): model profiles, built-in agent
`allowedAdapterTypes` additions.
## Verification\n\nCurrent-master rebase verification (OpenAI Codex,
2026-08-03): 13 focused files / 231 tests pass; adapter-utils, server,
UI, CLI, and Kimi adapter typechecks pass; full repository build and UI
token gates pass. The branch is conflict-free against master at head
`1249df117c5e12e5771b9a570a6340866450619e`.\n\nAutomated (all from repo
root, pnpm 9.15.4, Node 22):
- `vitest run packages/adapters/kimi-local`: 89/89 pass (includes
coverage for the instruction `--add-dir` directive, effort
forwarding/gating/mapping, `--skills-dir` gating, the signaled-exit
failure path, and `onEvent` runtime-event forwarding with cross-chunk
line buffering)
- `vitest run server/src/__tests__/adapter-registry.test.ts
server/src/__tests__/adapter-routes.test.ts
server/src/services/heartbeat-stop-metadata.test.ts
ui/src/adapters/adapter-display-registry.test.ts`: 37/37 pass
- `vitest run cli/src/__tests__/skills.test.ts`: 13/13 pass (the
control-plane skill install target follows the existing Codex/Claude
install path, whose symlink logic is unchanged)
- `vitest run packages/shared`: 307/307 pass; `vitest run
packages/adapter-utils`: pass except one pre-existing, unrelated failure
(`mcp-isolation.integration.test.ts` requires Claude CLI ≥ 2.1.207; host
has 2.1.185, fails identically on unmodified master)
- `pnpm --filter @paperclipai/adapter-kimi-local typecheck|build`, plus
typecheck of `server`, `ui`, `cli`, `adapter-utils`: all clean
- `pnpm install --frozen-lockfile`: passes (the PR diff itself contains
no lockfile changes, per repo policy; verified against a locally
regenerated lockfile)
- `node scripts/check-no-git-push.mjs` and `node
scripts/check-forbidden-tokens.mjs`: pass
- CI note: the `policy` job's release-bootstrap step is expected to stay
red until a maintainer bootstraps the first npm publish of
`@paperclipai/adapter-kimi-local`; see the CI Note for Maintainers
comment. All other contributor-actionable checks are green.
Manual end-to-end (real Kimi CLI 0.27.0, OAuth login, dev server on an
isolated instance):
1. Server `GET /api/adapters` lists `kimi_local` as builtin with correct
capability flags; models endpoint returns the three Kimi models
2. `POST .../adapters/kimi_local/test-environment`: all checks pass,
including a live `kimi -p` hello probe
3. Created a `kimi_local` agent and invoked two heartbeats: run 1
spawned `kimi -p ... --output-format stream-json`, Kimi used its `Read`
tool, produced the expected answer, and the session id was captured from
the `session.resume_hint` meta event; run 2 resumed the **same** Kimi
session (`sessionIdBefore == sessionIdAfter`) via `-r`
4. UI: adapter appears in the New Agent dropdown; selecting it shows the
Kimi command placeholder, the three models, and the Kimi config fields;
the run transcript renders Kimi tool calls via the adapter's stdout
parser
The instruction-bundle, thinking-effort, and `--skills-dir` changes
landed after the manual run above. They are covered by the unit tests
listed under Automated, and the Kimi CLI flags they rely on
(`--add-dir`, `--skills-dir`, `KIMI_MODEL_THINKING_EFFORT`) were
confirmed against the installed Kimi Code CLI 0.27.0 (`kimi --help`,
config-file thinking-effort docs).
Screenshots (assets branch on the fork, not part of the diff):






## Risks
- Low risk to existing behavior: the change is additive, one new
workspace package plus single-entry registrations alongside existing
adapters; no existing adapter code paths are modified.
- The adapter invokes the locally installed `kimi` CLI; like other local
adapters, run behavior depends on the host's Kimi version. The parser is
written against the documented/verified 0.27.0 stream-json schema and
degrades gracefully (malformed lines are skipped, failures surface as
run errors).
- `--skills-dir` overrides Kimi's auto-discovery of user and project
skills for the run. This is intentional (paperclip-managed agents get a
reproducible, isolated skill set), and it is only passed when at least
one Paperclip skill is desired, so unconfigured agents keep default
discovery.
- Thinking effort is only forwarded to models that advertise
`support_efforts` (currently `kimi-code/k3`); `EFFORT_CAPABLE_MODELS`
must be extended when more Kimi models gain support, otherwise a
configured effort is silently ignored for them.
- `Dockerfile` now installs `@moonshot-ai/kimi-code@latest` globally
alongside the other agent CLIs, so image size increases slightly.
- Maintainer action needed for the npm bootstrap gate: the `policy`
job's release-bootstrap step fails until the first npm publish of
`@paperclipai/adapter-kimi-local` (the gate from #5146 that every new
adapter package has passed through). Enrollment with `publishFromCi:
true` is required by the manifest validator (dropping the entry,
`false`, or `private` are all rejected), so this is intentionally left
to a maintainer. Remaining CI lanes are expected to run once it is done.
## Model Used\n\n- **Current-master rebase, conflict adaptation, and
registry-parity coverage:** OpenAI, **GPT-5 Codex** (Codex agent; exact
serving model ID and context-window size were not exposed to the
runtime), with repository, shell, Git, and GitHub tooling. It preserved
Hawik’s commit authorship, reconciled ACPX and environment-capability
changes, added current registry tests, and ran the verification
above.\n- **Adapter implementation and initial review:** Moonshot AI,
**Kimi K3 Coding** (latest), via **Kimi Code CLI v0.27.0**
(`kimi-code/k3` alias, 1M-token context window, thinking mode, agentic
tool use). The CLI agent explored the repo, wrote the adapter
implementation (delegated to a coder sub-agent of the same model), ran
tests, and drafted the first version of this PR body. A second
model-driven review pass (read-only, same model) audited the diff for
security/correctness before submission; its findings (shell-quoting
hardening, auth-detection false positive, session-compaction
registration, test gaps) were fixed and are included.
- **Harness-context fixes and review responses:** Anthropic, **Claude
Opus 4.8** (`claude-opus-4-8`) via Claude Code. Diagnosed from run logs
that Kimi received only the entry instructions file (not the
`HEARTBEAT.md`/`SOUL.md`/`TOOLS.md` bundle) and that `effort` was never
wired, then implemented the instruction `--add-dir` delivery,
`KIMI_MODEL_THINKING_EFFORT` forwarding, and `--skills-dir` skill
delivery, added the accompanying tests and docs, and addressed the
automated review comments (preserving external skills on remote sync,
treating a signaled exit as a failure). Also extended the `paperclipai
agent local-cli` installer to seed the control-plane skills into
`~/.kimi-code/skills` for Codex/Claude parity, wired `onEvent` runtime
events so the issue-thread activity indicator reflects Kimi's tool and
reasoning output live, and built the ACP engine lane (`kimi acp` via the
shared acpx engine, default) so the transcript streams with live tool
status like the other ACP adapters. The Kimi CLI flags, subcommand, and
env var relied on here were verified against the installed Kimi Code CLI
0.27.0.
- All CLI behaviors claimed here (`-p`, `--output-format stream-json`,
`-r` resume, event shapes, `--add-dir`, `--skills-dir`,
`KIMI_MODEL_THINKING_EFFORT`) were verified empirically against the
installed Kimi CLI, not assumed.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green *(only the release-bootstrap step
remains red, pending the maintainer npm publish described in Risks)*
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
*(will address all Greptile comments as they arrive)*
- [x] I will address all Greptile and reviewer comments before
requesting merge
---
## Maintainer Addendum (2026-08-20)
The shared acpx-engine and issue-chat changes (run-summary segmentation,
placeholder tool-event coalescing,
`ISSUE_CHAT_TRANSCRIPT_MAX_VISIBLE_ENTRIES` 30 → 400, live-reasoning UI)
have been **extracted to #11761** so the cross-adapter behavior changes
review and revert independently — both commits there preserve @hawikk's
authorship. This PR is now the kimi-specific adapter only (60 files,
+3,793/−8, essentially pure addition); the only shared-engine touch left
is the `kimi acp` command resolution. `publishFromCi` is `true` — the
package name is bootstrapped on npm.
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Dotta <bippadotta@protonmail.com>
Co-authored-by: Devin Foley <devin@paperclip.ing>
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The workspace runtime starts guest processes and exposes their
ports.
> - The readiness wait bound the guest port to test whether it was
ready.
> - That bind could take the port before the guest process used it.
> - This pull request reads listener state without a competing bind and
recovers from a real port collision.
> - The benefit is stable runtime exposure and a clear recovery path for
a genuine collision.
## Linked Issues or Issue Description
**What happened?**
The managed HTTPS exposure test failed intermittently with `listen
EADDRINUSE` on `127.0.0.1:42000`. The readiness wait bound the guest
port before the guest process could bind it.
**Expected behavior**
The readiness wait must not hold the guest port. The runtime must
recover when an external process owns the assigned port.
**Steps to reproduce**
1. Run `npx vitest run
server/src/services/workspace-runtime-exposure.test.ts` from the
repository root.
2. Inject a delayed guest bind and a widened readiness-probe hold.
3. Observe the port collision before this fix and the successful retry
after this fix.
**Paperclip version or commit**
`b375bbd913cb2edc8e077f4339ce0745e53bd462`
**Deployment mode**
Built from source with the server test suite.
**Installation method**
Built from source with pnpm.
**Agent adapter(s) involved**
Not adapter-specific. This is a core runtime test.
**Database mode**
Not database-related.
**Relevant logs or output**
Before this fix, the test reported `listen EADDRINUSE: address already
in use 127.0.0.1:42000`.
## What Changed
- Read listener presence from `/proc` on Linux instead of binding the
guest port.
- Keep the bind probe as the fallback on non-Linux hosts.
- Capture the current port owner when an exposed guest exits with
`EADDRINUSE`.
- Quarantine the app and HMR pair, then allocate the next free port pair
within the existing range.
- Add a deterministic regression test for quarantine, re-allocation, and
self-diagnosis logging.
## Verification
- Run `npx vitest run
server/src/services/workspace-runtime-exposure.test.ts` from the
repository root.
- The target suite passes 19 tests locally.
- The related runtime suites pass 105, 128, and 21 tests locally.
- Run `tsc -p server/tsconfig.json` to check the changed server files.
- CI must pass the general server shard and all required checks.
- Greptile must report 5/5 with no open P2 comments, recommendations, or
follow-ups.
## Risks
The Linux readiness path now depends on `/proc` listener data. Non-Linux
hosts retain the existing bind-probe fallback. The port range and
allocation limit do not change.
## Model Used
OpenAI GPT-5. This agent used tool calls for repository checks and
GitHub PR management. Priya Raman authored the code change.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` /
`Closes: #` / `Refs: #` OR (b) described the issue in-PR following the
relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>