Widen activateSkillAttachmentSchema so the attachments array accepts text parts alongside image, video and file, letting a caller interleave text and media in the order the model should read them. Schema only; the route already resolves attachments as WireContent.
Media name preservation already ships: the REST schemas expose a name on
image and video content, and kap-server reads imageUrl.name and videoUrl.name
when projecting messages and prompt content. The kosong part types never
declared the field, so it survived only because object literals keep excess
properties through an assignment. Consumers that read these types directly
cannot see the name at all.
Declare it where the other optional part fields live. No runtime change; the
existing media name projection tests continue to cover the behavior.
* feat(agent-core-v2): upload images as file references for Kimi models
* fix(agent-core-v2): scope media upload cache by endpoint and recognize SDK auth error status
* fix(agent-core-v2): restore the stripped /v1 for kimi files uploads on the anthropic route
* feat(agent-core-v2): omit oldest media when accumulated inline media exceed the request budget
* fix(agent-core-v2): key the media upload cache by the stable JWT subject
* fix(agent-core-v2): harden media request recovery
* fix(agent-core-v2): correct image memo accounting
* feat(agent-core-v2): include saved paths in dropped media placeholders
* docs: drop the saved-path re-read guarantee from the media budget note
The guarantee does not hold for inline data-URL media (no persisted
path exists), and the runtime warning already conveys path availability
when it applies. Addresses the codex P2 review suggestion by removal.
* fix(tui): stop /usage and /status from prompting login before the first message
* docs(changeset): simplify the /usage fix entry
* fix(tui): mute the session-usage error line and cover the session-less path in tests
* docs(changeset): restore the confirmed wording
* perf(tui): batch and cache agent swarm progress rendering
* perf(agent-core-v2): evict completed subagent scopes behind an LRU cache
* fix(agent-core-v2): stop the agent actor in the session machine when its scope is removed
* fix(agent-core-v2): emit a terminal event for the final rate-limited run and defer eviction while background tasks run
* fix(agent-core-v2): include in-flight retries when abandoning suspended agents
* fix(agent-core-v2): roll back the closing flag when scope removal fails and wait per the configured eviction timeout
* fix(agent-core-v2): terminalize subagents spawned after batch cancellation and report task timeouts as failures
* chore: restore upstream/main state of files mangled by lint-staged autofix in the merge commit
oxlint --fix rewrites (prefer-set-has, catch-error-name, prefer toSorted/.at(-1)/toReversed)
touched seven files the branch never modified; one of them (oauth managed-kimi-code.ts)
no longer typechecks. Restore all seven to their exact upstream/main state. Committed
with --no-verify so the same autofix does not re-mangle them.
* fix(agent-core-v2): retry deferred scope evictions without exhausting the attempt budget, dedupe terminal events for starting retries, and patch-level the changeset
* fix(agent-core-v2): finish scope teardown instead of reactivating a partially torn-down scope
* fix(agent-core-v2): terminalize subagent-start hook cancellations and re-acquire resume targets after metadata reads
* fix(tui): record cancelled background agents in the transcript
* fix(agent-core-v2): route mirror terminal events through the batch exactly-once guard
* fix(tui): guard terminal swarm members from re-cancellation and deliver terminal status to cancelled foreground subagent cards
* fix(agent-core-v2): classify eviction as removed when teardown already closed the scope
* Merge remote-tracking branch 'upstream/main' into perf/subagent-scope-eviction
Skip lint-staged for this merge: its oxlint --fix pass rewrites unrelated files
(prefer-set-has etc. mangled seven files in the previous merge commit), while the
merge content is upstream's lint-clean code plus conflict resolutions already
verified by oxlint.
* chore: restore upstream/main changes dropped by a stash roundtrip during the merge
A git stash/pop cycle used to isolate an unrelated flaky test reverted 82 files of the
merge result to the pre-merge branch state, so commit 375ff2a4a missed them. The
working tree already held the correct merged content; this commit restores it.
* fix(agent-core-v2): propagate the cancellation reason from turn abort to tool signals
Cancelling a turn aborted the turn's llm scope and every tool scope
without a reason, so tools and subagents only ever saw the default
AbortError and could not tell a user cancellation from a system abort.
With the swarm terminal-event classification this surfaced as
`subagent.failed` ("This operation was aborted") on Ctrl+C instead of
`subagent.cancelled`.
Carry the reason end to end: `MachineEngine.abort(reason)` sends it on
`input.abort`, the agent machine remembers it for the turn and forwards
it to `turn.abort` and to every tool scope it aborts, the turn machine
passes it to the llm scope, and the loop service hands its cancellation
(a `UserCancellationError` by default) to the engine.
* fix(agent-core-v2): stop rebuilding an evicted subagent after its caller aborts
`createAgentAwaitingClose` polled for the previous scope to finish
closing without ever looking at the caller's abort signal, so cancelling
an `Agent` or `AgentSwarm` resume during that wait still recreated the
scope afterwards. In the `Agent` path the run then rejected before any
terminal event was mirrored, leaving an idle scope that the scope cache
no longer tracked.
Thread the caller's signal into the helper and check it before every
attempt; the Agent tool passes its call controller and the swarm service
passes the attempt signal. Also trim the eviction changeset to the one
sentence the changeset rules ask for.
* fix(agent-core-v2): report task-manager aborts of a subagent as cancelled
When the task manager times out or stops a background subagent it aborts
the run with a plain reason ('Timed out', the TaskStop reason), and the
run rejects with that raw reason. The task manager therefore classifies
the task as timed_out or killed, but the mirror only recognised
`UserCancellationError` as a cancellation and emitted `subagent.failed`,
so the transcript recorded a failure before the authoritative
`background.task.terminated` event could land.
Classify a terminated run by the shape of its abort reason: a real
Error that is not an AbortError (the swarm's own per-item timeout) stays
a failure, everything else that aborted the run is a cancellation. The
swarm's start-failure path uses the same rule.
* fix(agent-core-v2): flush the wire before evicting a subagent scope and re-pick LRU candidates
Two gaps in the scope-cache eviction pass:
- `AgentLifecycleService.remove()` swallows a failed wire flush and still
tears the scope down, so an eviction that hit a disk-full or transient
I/O error would drop the in-memory scope and let a later resume rebuild
from a stale wire. Flush the agent's wire explicitly before removing;
if that fails, keep the scope resident and retry on a later pass. The
idle and task checks are repeated after the flush so a resume that
started meanwhile is not cancelled by the removal.
- The pass snapshotted its candidates up front and re-validated them by
attempt count only, so a scope that was resumed and completed again
while an earlier eviction was awaited kept matching with attempts 0 and
was evicted despite now being the most recently used. Pick the oldest
eligible entry from the live map on every step instead, skipping only
the entries this pass already tried.
---------
Co-authored-by: Kaiyi <me@kaiyi.cool>
* fix(plugins): rename WebBridge display name to Kimi Browser Extension
The product has renamed WebBridge to Kimi Browser Extension in work and
Chrome. Update the user-facing display name across the built-in
capability entry, TUI plugins selector, managed plugin manifest,
marketplace catalog, skill docs, and user docs to match. Internal ids,
binary names, CDN paths, and daemon references are unchanged.
* fix(plugins): bump webbridge to 1.11.4 and keep legacy docs anchor
Address review: point the changeset at the scoped CLI package, bump the
renamed plugin's manifest/catalog/docs version so installed users are
offered the renamed package as an update, and preserve the published
#kimi-webbridge documentation anchor beside the renamed heading.
* docs(plugins): match only the known extension-update error messages
Broadening the version-mismatch trigger to the generic prefix 'Please
update the' would misclassify unrelated tool errors as an outdated
browser extension; match the two known full messages instead.
---------
Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
The platform /usages payload now serves per-window used ratios
(goods_version, a usages map of limit5h/limit7d/monthTotal/monthCode
entries with used_ratio/reset_time, and boosterWallet) instead of
absolute used/limit rows.
- oauth: parse and fetch the quota model; keep the platform helpers
- toolkit / agent-core-v2 / node-sdk: getManagedUsage returns the quota
- kap-server: /oauth/usage passes the camelCase quota shape through
(the legacy snake_case wire is gone)
- TUI /usage: plan rows are presence-driven from the quota payload;
the monthly row carries a kimi/code breakdown line
- docs: server-api reference updated for the new response shape
* docs(web): add common slash commands table and rename startup options section
* docs(interaction): fold the goal mode guide into the interaction page and remove the orphaned page
* feat(agent-core-v2): fail fast on unsupported [secondary_model].default_effort
* fix(agent-core-v2): reject default_effort off for always-thinking pool models
* fix(agent-core-v2): surface adaptive_thinking on the assembled catalog model
* perf(tui): batch and cache agent swarm progress rendering
* perf(tui): honor the render-cache escape hatch for cell memoization
* fix(tui): stop swarm frame ticks after tool call end and cap retained label code units
* fix(tui): house swarm label caps in TUI constants and stop splitting surrogate pairs
* fix(tui): close OSC 8 hyperlinks sliced by the swarm label storage cap
* fix(tui): reset SGR styling sliced by the swarm label storage cap
* fix(tui): back the swarm label storage cap off to grapheme cluster boundaries
* test(tui): verify swarm terminal-state retention through the render seam
* perf(agent-core-v2): shard the session event bus by agent id
* fix(agent-core-v2): preserve full-stream-before-typed ordering in agent channels and render perAgent counts in the inspector
* fix(agent-core-v2): deliver agent full streams before session typed handlers and dispose sharded channels with the bus
* fix(agent-core-v2): prevent rebuilding agent channels after the event bus is disposed
* fix(agent-core-v2): isolate agent channels on generation replace and keep typed handlers on the shared per-type channel
* fix(agent-core-v2): require the active lifecycle context before firing an agent full-stream channel
* fix(agent-core-v2): reject stale lifecycle contexts when subscribing to an agent full-stream channel
* fix(agent-core-v2): honor the agent context in typed subscribeAgent subscriptions
* fix(agent-core-v2): release disposed agent scopes from the DI dependency graph
* fix(agent-core-v2): drop retired service instances from the tracked edge nodes and the dependency graph
* fix(agent-core-v2): resolve tower roster identities to the latest registration
Agent ids restart from agent-0 in each session, so a freshly spawned
worker collided with the previous session's roster entry and every
find-first lookup (caller identity, write guard, death bookkeeping)
resolved to the stale entry: workers read the wrong inbox, sent under
the wrong name, and were denied their own writes, mission updates, and
reviews.
- resolveAgent picks the latest roster entry for an agent id; all
callers (resolveCallerName, write guard, resume veto, died/revived)
go through it
- registerAgent retires same-agent-id entries before appending
- enter() (/tower on) now adopts the workspace roster itself instead of
relying on a manual TowerInit
* fix(agent-core-v2): adopt the tower roster when a replayed tower mode finds a dead foreign owner
A forked or restored session replays the durable TowerModeEnter into an
active tower mode without ever calling enter(), so the roster adoption
added there never ran on the restore path: with the previous owner
session gone, the fork kept the mode (and the stale roster) until a
manual TowerInit. The dead-owner branch of the restore-time
reconciliation now adopts the workspace, mirroring enter()'s takeover
of an idle owner; a live foreign owner still causes an exit.
* fix(agent-core-v2): await the outgoing tower owner's release before adopting its roster
Taking tower mode over from a live but idle owner called the owner's
synchronous exit(), whose ownership release ran fire-and-forget, and
immediately adopted the roster — two concurrent load-modify-save cycles
on .tower/comms/state.json that could lose the new owner or resurrect
the stale roster. exit() now awaits the ownership release and the
takeover awaits the owner's exit(); the remaining callers either await
(RPC/HTTP tower-mode-off) or explicitly ignore the promise (mode mutex,
restore-time self-exit).
* fix(agent-core-v2): fail tower activation when the roster adoption cannot complete
Adoption failures (unreadable or unpersistable state.json) were
swallowed into a log warning, so enter() and the stale-owner restore
both activated tower mode with the foreign owner and stale roster still
in place — the exact identity mismatch the adoption is meant to
prevent, now with a false success report. adoptTowerRoster() now throws
a TowerProtocolError with the underlying cause: enter() propagates it
before any tool is activated, and the restore path drops the replayed
tower mode instead (it must not throw inside the restore hook chain).
* fix(agent-core-v2): propagate unreadable tower state during roster adoption
adopt() treated any state.json read failure as an uninitialized
workspace via isInitialized()'s catch-all, so an existing but
unreadable state file (EACCES, EISDIR, transient I/O) reported a
successful no-op adoption and enter() activated tower mode against the
foreign state — bypassing the activation guard added in the previous
commit. Only ENOENT now means uninitialized; every other read error
propagates into the fail-activation / deactivate-on-restore paths.
---------
Co-authored-by: konghuanjun <konghuanjun@moonshot.ai>
* docs(skills): clarify flat-form skill naming and its limits
The flat-form description "Skill name is taken from the filename (minus
.md)" read as if the on-disk file should drop the extension, which
repeatedly confused readers. Rewrite the Creating-a-Skill section with
a concrete directory layout, explicit name-derivation rules for both
forms, the directory-over-flat precedence, and the flat form's top-level
scanning and KIMI_SKILL_DIR limitations.
* docs(skills): attribute directory-form names to the required frontmatter
parseSkillText requires name in directory-form SKILL.md and always
registers under it, so the subdirectory name is only a convention, not
the source of the Skill name. Reword the derivation bullets accordingly
(flat form keeps its filename fallback).
---------
Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
* feat(oauth): add the dynamically_loaded_tools capability from the official models endpoint
* feat(agent-core-v2): support per-server deferred disclosure of MCP tools
* feat(klient): mirror per-server deferred in the MCP config contract
* fix(agent-core-v2): honor per-server deferred for the needs-auth MCP tool
* fix(agent-core-v2): register select_tools regardless of the profile tool allowlist
* feat(agent-core-v2): default MCP servers to inline tool disclosure unless deferred is enabled
* refactor(agent-core-v2): fold the prompt queue into the agent loop service
Delete AgentPromptService/IAgentPromptService: prompt submit/queue/steer/
abort now ride the agent machine queue through IAgentLoopService's extended
surface (submitPrompt/submitSteerPrompt/enqueuePrompt/steerPrompts/
abortPrompt/drainPrompts/injectPrompt/retryPrompt/promptQueue plus
hooks.onBeforeSubmitPrompt and the promptAdmission reservation slot).
Durable prompt.* event classes move to agent/prompt/promptEvents.ts and keep
their registrations; promptAdmissionKey keeps its fold. Dead assets go away:
promptResolutionKey, PROMPT_ALREADY_COMPLETED (kap-server 40903 path),
promptLaunchingKey and clear(). Compaction gating (queue while compacting,
resume on finish) moves into the loop reservation drain.
The 'agentPromptService' wire name keeps its shape: a thin AgentPromptChannel
facade (same decorator id) forwards submit/submitSteer to the loop, so
klient memory/ipc/debug transports and the kap-server dispatcher are
unchanged.
* test(agent-core-v2): re-pin prompt queue semantics on the loop service
Rewrite promptService.test.ts (25 cases, count unchanged) against the real
AgentLoopService with the scripted-LLM harness, fold the launch-window
reservation out of promptQueue().pending to match the old snapshot contract
exactly, and update the debug-channels pin to the facade's submit/submitSteer
surface.
* refactor(agent-core-v2): lint-align the loop prompt queue surface
* fix(agent-core-v2): settle prompt completions on the turn-result chain
Match the deleted service's microtask position: prompt.completed/aborted and
the completion deferreds fire from a result.then chain attached at bind time
instead of synchronously inside endTurn, so wire/emit ordering with
post-turn producers (tool unregister, next-prompt launch) stays identical to
the baseline snapshots. Steered children move onto the reservation so the
chain can settle them after the active turn is gone.
* refactor(agent-core-v2): move the prompt-submit gate into the agent machine
* refactor(agent-core-v2): keep image compression captions inline in prompt messages
* refactor(agent-core-v2): drop the durable prompt admission facility
* refactor(kap-server): resolve prompt auth at turn runtime instead of submit time
* refactor(agent-core-v2): teach the agent machine queue metadata, multi-id steer, gate rewrite, and pause
* refactor(agent-core-v2): converge prompt submission on machine queue user entries
* refactor(agent-core-v2): replace loop prompt records with a waiter registry fed by machine events
* feat(agent-core-v2): make the compaction attempt limit configurable
Add loop_control.compaction_max_attempts (default 5) to control the
maximum total attempts for a failing compaction request, replacing the
hardcoded MAX_COMPACTION_RETRY_ATTEMPTS constant. The value flows
through ProfileModelContext into the compaction retry loop, covering
both retryable generation errors and empty/truncated response shrinks.
* fix(agent-core-v2): bound compaction shrink attempts and compute retry delays lazily
Address codex review on #3750: the empty/truncated shrink path allowed
maxAttempts + 1 requests (throwing only when the shrink counter exceeded
the limit), and the backoff delay array was allocated eagerly with
maxAttempts - 1 entries before the first request. The shrink path now
stops at the configured limit, and each delay is computed lazily from
the retry index.
* fix(agent-core-v2): count every compaction request against the shared attempt limit
Address the second codex review round on #3750: the retryable-error and
empty/truncated recovery paths kept separate counters, and the retry
budget reset after each shrink, so alternating failure modes could issue
more requests than compaction_max_attempts. A single requestAttempts
counter now gates all recovery paths (the overflow shrink path keeps its
own tighter cap of 3), making the configured value a true maximum on
total requests per compaction round.
* feat(agent-core-v2): persist the human runtime mirror as human.* records in the wire journal
Introduce mode-2 coexistence: the machine eventStore journal becomes a
tree-projection-filtered adapter over the same wire file (single writer via
the WireService append queue), the engine switches from memoryJournal to the
file journal with a seed fallback while no human records exist, and cold
readers skip the new record family constructionally. Adds downgrade
round-trip e2e coverage, whitelists agent.switched/context.undone from
unknown-record telemetry, asserts the undo switch triple after flush, and
resets the machine engine after an undo rerun so machine and wire turn
clocks stay aligned.
Squashed from:
refact(agent-core-v2): project wire journal as an in-memory branch tree behind IAgentJournal
refact(agent-core-v2): undo as branch switch with dual-emitted legacy record and restore replay
refact(agent-core-v2): queue late attachments during restore rerun and flatten fork sources to the active chain
feat(agent-core-v2): persist the human runtime mirror as human.* records in the wire journal
* feat(agent-core-v2): add full compaction to the human agent domain
* refactor(agent-core-v2): keep pending input state events out of the wire journal
* refactor(agent-core-v2): flip agent DI scope ownership to session-spawned agent actors
* refactor(agent-core-v2): build the agent wire and blob views in the session layer
* refactor(agent-core-v2): persist human domain records under the agent.* wire namespace
- replace the human. record prefix with an explicit whitelist (AGENT_WIRE_RECORD_TYPES) guarded against the Event2 vocabulary; legacy human.agent.* journals stay readable through a transition prefix
- unknown-type records skipped during restore now go to the log file instead of the console (malformed records still report to the console)
* refactor(agent-core-v2): compose the llm recovery chain outside the turn machine
The turn machine hardcoded credentialsRecovery as the head of its
recovery chain and interpreted a refreshCredentials flag on proposals,
coupling the turn to the credentials domain. Strategies now return
self-describing records (strategy/action, optional messages, optional
opaque prepare effect), the turn only runs prepare and/or swaps
messages, and the engine composes the chain via chainRecoveries.
* refactor(agent-core-v2): inline the two-strategy recovery composition
With self-describing proposals the chain is a one-liner at each call
site; the named chainRecoveries combinator had only two call sites and
no third strategy to justify it.
The Remote Control HTTP tunnel validated each base64 message with a
backtracking regular expression. Requests larger than ~3.5MB (base64
~5MB) exhausted the V8 Irregexp backtracking stack and threw
RangeError, which the catch-all mapped to a 400 with an empty body,
surfacing as a generic connection failure on the web client.
Replace the regex with an O(n) character check, reject oversize
requests from the base64 length before decoding, and map non-SyntaxError
failures to 502 instead of 400.
* fix(agent-core-v2): rebuild session and search indexes on unrecoverable storage failures
* fix(agent-core-v2): propagate search sync truncation and track session count in index freshness
* fix(minidb): wipe derived stores under their own locks during rebuild
* fix(agent-core-v2): isolate wiped stores, invalidate stale projections, and account sync failures
* feat(agent-core-v2): replace session index freshness scans with a dirty journal and targeted reconciliation
* fix(agent-core-v2): split transient failures by op kind, surface failed startup reconciliation, and cool down search session skips
* feat(agent-core-v2): allow rm -rf targeting /tmp and /temp paths
The dangerous command guard flagged every recursive force rm regardless
of target. rm -rf now falls through without an ask when all operands are
literal paths under /tmp or /temp (segment-level prefix, no .. escape);
mixed, non-literal, or out-of-prefix targets stay dangerous.
* chore: add changeset for rm -rf temp path allowance
* feat(remote-control): compress textual tunnel responses with gzip
* fix(remote-control): honor explicit gzip exclusion over accept-encoding wildcard
* fix(remote-control): skip gzip for 206 responses and vary by accept-encoding
* fix(remote-control): compress tunnel responses off the event loop
* fix(remote-control): vary identity responses and version compressed etags
* fix(remote-control): drop etags from gzipped tunnel responses
* fix(agent-core-v2): honor request-level toolMessageConversion in openai formats
The requester already forwarded LlmRequestConfig.toolMessageConversion
into formatRequest, but the openai chat and openai-responses formats
only read the trait hook, so the explicit request config was silently
ignored. Resolve the mode as request config, then trait default, then
the protocol default, and pass the resolved value into lowering.
* refactor(agent-core-v2): split the protocol trait into per-protocol dialects and provider connection
The ProtocolTrait interface bundled endpoint/headers connection config,
model capability, message/params conversion hooks, and error
classification into one bag, and every format received the whole bag
whether or not it consumed each hook — hooks a protocol ignores were
accepted by the type system and silently dead at runtime.
Split it by consumer:
- ProviderConnection (protocol/connection.ts): endpoint env
declaration and default headers, still resolved per request inside
generate.
- Per-protocol typed dialects (OpenAIDialect, OpenAIResponsesDialect,
AnthropicDialect, GoogleGenAIDialect): only the customization points
each protocol actually consumes; data-shaped hooks (reasoningKey,
toolCallIdPolicy, toolMessageConversion, strictThinkingValidation)
are data fields, and message/history hooks use the protocol wire
types instead of Record<string, unknown>.
- convertError moves to a requester option, capability to a provider
variant field.
Dialects are bound when the format is created (createOpenAIFormat and
siblings), so FormatRequestInput and the stream parser carry request
data only; ProtocolTrait is deleted. The thinking hook returns the
kwargs and the preserveThinking flag together as ThinkingApplication,
and the kimi dialect emits the final thinking params directly instead
of routing them through an extra_body flatten in buildParams. The
llm-adapter layer is migrated to the same {connection, dialect,
convertError} assembly.
* refactor(agent-core-v2): compose format stages and dialect hooks in the requester pipeline
* refactor(agent-core-v2): rename protocol dialects to traits
* fix(agent-core-v2): include the system message in openai mergeHistory input
* refactor(agent-core-v2): enforce the format/trait contract boundary
- move CONTEXT_MANAGEMENT_BETA into anthropic/contract and have the kimi
trait import wire types from each protocol's contract.ts instead of
format/lower; export the four contract modules from human/index.ts and
guard the boundary in check-import-boundaries
- rename protocol/trait.ts to protocol/thinking.ts and move TraitContext
to protocol/base.ts; clean up the remaining dialect-era test variable
- type extractUsage as OpenAIRawUsage / OpenAIResponsesRawUsage instead of
Record<string, unknown> and drop the requester-side casts
* refactor(agent-core-v2): thread the request config by spread and drop dead format types
- the four requesters spread LlmRequestConfig into the plan input instead
of hand-enumerating fields, so a new cross-protocol config field cannot
be silently dropped per protocol
- ProtocolFormat loses the phantom TRequest/TResponse type parameters;
the dead OpenAIRawResponse/AnthropicRawResponse/GoogleRawChunk contract
types go with them
- the thinking test now names the extra_body flatten behavior explicitly
* refactor(agent-core-v2): keep protocol format modules internal to the requester pipeline
- drop the four format barrels (and openai/reasoning-key) from
human/index.ts; each base's public seam is now exactly
contract / trait / requester
- stop re-exporting contract wire types from format/lower modules so the
neutral vocabulary has a single home; move the *LoweredMessage staging
types out of contract into the owning format module
- guard the seam in check-import-boundaries: only llm/requester/bases
code and tests may import format/lower/patterns/reasoning-key
* refactor(agent-core-v2): plug llm credentials in through request config
Replace the withAuth/withAuthUpload requester decorators with a
credential contribution point on LlmRequestConfig: the llm machine's
request actor (machine path) and ModelRequesterImpl (direct path)
resolve credentials per attempt, and a recoverable 401 is recovered by
invalidating and re-resolving — emitted as llm.recovering on the turn
machine's credentials branch.
* fix(agent-core-v2): surface request-actor failures as llm.failed.remote
A rejection inside the llm machine's detached request actor (credential
resolution, message resolvers, or a throwing requester) could not reach
the machine, leaving the turn stuck in thinking. Convert it to an
llm.failed.remote event so the turn lands in its failed state.
* docs(agent-core-v2): attribute retry/recovery to the turn machine in llm.md
* refactor(agent-core-v2): unify credentials in human/credentials, turn-owned 401 recovery
* fix(agent-core-v2): credential recovery for direct paths, abort guard, turn-snapshotted credentials
* feat(agent-core-v2): IModelCatalog.generate with stream credential recovery
* refactor(agent-core-v2): inline credential recovery at call sites
Remove the attemptWithCredentialRecovery/streamWithCredentialRecovery
helpers from human/credentials; the single-retry recovery is now written
out at each direct call site (catalog ping/generate, full compaction,
media upload) so the control flow reads linearly without a wrapper hop.
The credentials module keeps only the provider factories and the
credential application helpers; recoverability and invalidation stay on
the LlmCredentialProvider itself.
* fix(agent-core-v2): settle the queued turn when a machine turn settles before gating
When the llm machine fails before requester.generate() runs — for
example when OAuth credential resolution rejects — the loop cleared the
pending machine turn marker on turnSettled without ever binding or
settling the queued reservation, leaving the submitter's ready/result
promises and settled() hanging. The loop now settles the unbound
reservation explicitly: cancelled on abort, failed otherwise, mirroring
the evaluateSettle error propagation.
* fix(agent-core-v2): bind and end pre-gate failures through the normal turn lifecycle
The direct settlement resolved turn.result without endTurn(), so no
TurnPrompt/TurnStarted/TurnEnded/AgentErrorEvent was published and the
next queued reservation was never launched. The unbound reservation is
now bound via beginActiveTurn and ended via endTurn (failed, or
cancelled on abort), chained onto afterChain when the previous turn is
still settling, so pre-gate failures get the same lifecycle events and
queue progression as any other failed turn.
* fix(agent-core-v2): settle seeded turns on pre-gate failure, preserve coded credential errors, close steps on recovering
- Notification-seeded machine turns that fail before gating now bind a
seeded reservation and end through endTurn like queued ones, instead
of leaving the nudge pending and settled() hanging
- The llm machine's request actor attaches the raw error to
llm.failed.remote and the turn machine prefers it for its terminal
failure, so coded errors (e.g. auth.login_required) survive to
endTurn's error payload
- projectMachineEvent now closes the current machine step on recovering
exactly as it does on retrying, keeping step.begin/step.end balanced
when credential recovery re-enters the request
* fix(kap-server): add generate to IModelCatalog test fakes
* fix(klient): migrate examples to the credentials API
* test(agent-core-v2): drop credential recovery coverage
* refactor(agent-core-v2): fold kimi-oauth credential adapter into credentials/
* refactor(agent-core-v2): pair credential refresh with invalidate, optional Model.credentials, abort-safe request actor
- oauthCredentials.invalidate() now starts the forced refresh eagerly and
hands the pending token to the next resolve(), so the force signal can no
longer leak into or be consumed by unrelated resolves
- Model.credentials becomes optional, dropping the {} as never /
staticCredentials(undefined) filler in test fakes
- the llm machine request actor swallows abort outcomes instead of
reporting llm.failed.remote, so an aborted turn settles as aborted
rather than failed
* refactor(agent-core-v2): credentials recovery strategy chain, shared credential-recovery executors, single-proposal failure triage
* fix(agent-core-v2): settle message-less notifications on pre-gate failure, recover credentials in media resolver uploads
* test(kap-server): add the IModelCatalog.generate stub to the history suite
* fix(agent-core-v2): honor request-level toolMessageConversion in openai formats
The requester already forwarded LlmRequestConfig.toolMessageConversion
into formatRequest, but the openai chat and openai-responses formats
only read the trait hook, so the explicit request config was silently
ignored. Resolve the mode as request config, then trait default, then
the protocol default, and pass the resolved value into lowering.
* refactor(agent-core-v2): split the protocol trait into per-protocol dialects and provider connection
The ProtocolTrait interface bundled endpoint/headers connection config,
model capability, message/params conversion hooks, and error
classification into one bag, and every format received the whole bag
whether or not it consumed each hook — hooks a protocol ignores were
accepted by the type system and silently dead at runtime.
Split it by consumer:
- ProviderConnection (protocol/connection.ts): endpoint env
declaration and default headers, still resolved per request inside
generate.
- Per-protocol typed dialects (OpenAIDialect, OpenAIResponsesDialect,
AnthropicDialect, GoogleGenAIDialect): only the customization points
each protocol actually consumes; data-shaped hooks (reasoningKey,
toolCallIdPolicy, toolMessageConversion, strictThinkingValidation)
are data fields, and message/history hooks use the protocol wire
types instead of Record<string, unknown>.
- convertError moves to a requester option, capability to a provider
variant field.
Dialects are bound when the format is created (createOpenAIFormat and
siblings), so FormatRequestInput and the stream parser carry request
data only; ProtocolTrait is deleted. The thinking hook returns the
kwargs and the preserveThinking flag together as ThinkingApplication,
and the kimi dialect emits the final thinking params directly instead
of routing them through an extra_body flatten in buildParams. The
llm-adapter layer is migrated to the same {connection, dialect,
convertError} assembly.
* refactor(agent-core-v2): compose format stages and dialect hooks in the requester pipeline
* refactor(agent-core-v2): rename protocol dialects to traits
* fix(agent-core-v2): include the system message in openai mergeHistory input
* refactor(agent-core-v2): enforce the format/trait contract boundary
- move CONTEXT_MANAGEMENT_BETA into anthropic/contract and have the kimi
trait import wire types from each protocol's contract.ts instead of
format/lower; export the four contract modules from human/index.ts and
guard the boundary in check-import-boundaries
- rename protocol/trait.ts to protocol/thinking.ts and move TraitContext
to protocol/base.ts; clean up the remaining dialect-era test variable
- type extractUsage as OpenAIRawUsage / OpenAIResponsesRawUsage instead of
Record<string, unknown> and drop the requester-side casts
* refactor(agent-core-v2): thread the request config by spread and drop dead format types
- the four requesters spread LlmRequestConfig into the plan input instead
of hand-enumerating fields, so a new cross-protocol config field cannot
be silently dropped per protocol
- ProtocolFormat loses the phantom TRequest/TResponse type parameters;
the dead OpenAIRawResponse/AnthropicRawResponse/GoogleRawChunk contract
types go with them
- the thinking test now names the extra_body flatten behavior explicitly
* refactor(agent-core-v2): keep protocol format modules internal to the requester pipeline
- drop the four format barrels (and openai/reasoning-key) from
human/index.ts; each base's public seam is now exactly
contract / trait / requester
- stop re-exporting contract wire types from format/lower modules so the
neutral vocabulary has a single home; move the *LoweredMessage staging
types out of contract into the owning format module
- guard the seam in check-import-boundaries: only llm/requester/bases
code and tests may import format/lower/patterns/reasoning-key