42 Commits

Author SHA1 Message Date
MertSoylu 30f92ad986 fix(coding-agent): keep the system prompt byte-stable across date/cwd changes
Move the per-request date/cwd line out of the system prompt into a
first-turn system-reminder so open-weight providers keep their tool-schema
prefix cache; the reminder refreshes itself at midnight. Closes #7404.

Generated with Codebuff 🤖
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-14 13:16:54 +03:00
can1357 b279db1790 test: refactored test suites to eliminate time-based sleeps and polling loops
- Replaced time-based sleeps and polling loops with event-driven promise resolvers and fake timers across agent and tool tests.
- Migrated test suites to share in-memory auth storage and fixtures using lifecycle hooks.
- Updated catalog model definitions, metadata, and configurations.
2026-08-13 19:32:22 +02:00
Ethan Cawse 4c71e92e3e fix(coding-agent): tolerate legacy image metadata 2026-08-12 09:13:03 -04:00
Ethan Cawse f43467f048 fix(coding-agent): preserve image normalization slots 2026-08-12 08:51:16 -04:00
Ethan Cawse 001460ee8a fix(coding-agent): normalize WebP on provider path 2026-08-12 08:36:28 -04:00
can1357 e9888367d1 refactor: migrated packages to internal utility modules and removed external dependencies
- Implemented in-house, zero-dependency utility modules in `pi-utils` covering DOM manipulation, markdown parsing, templating, browser automation helpers, and terminal buffers.
- Migrated packages across the repository to consume the new internal utilities and `omptype` schema validators instead of external dependencies.
- Removed multiple external runtime and development dependencies including Zod, Marked, LRU cache, Turndown, and Puppeteer browser packages.
2026-08-05 13:39:09 +02:00
can1357 a872d77068 chore: cleanup dumb tests 2026-08-02 20:39:23 +02:00
roboomp 838d120249 fix(coding-agent): reused effective prompt cache key
- Reused the agent's explicit or inherited cache identity for ephemeral side turns.
- Forwarded the same effective key through manual and automatic native compaction.
- Added regression coverage for all three secondary request paths.

Fixes #7218
2026-08-01 03:44:59 +00:00
Larry Gordon a50bcd5fed fix(extensions): wire invokeTool to the extension path as same-tool delegation
Addresses PR review. The initial version put invokeTool on AgentToolContext
via ToolContextStore, but the extension execute path (RegisteredToolAdapter)
builds its own ExtensionContext and never saw it, so the documented
registerTool wrapper use case did not work. It also allowed arbitrary
cross-tool targets (bypassing the target's approval policy), used a
session-global recursion counter that tripped on concurrent independent
delegations, and missed discoverable built-ins that xdev partitioning moves
out of the tool array.

Rework:
- Move invokeTool onto ExtensionContext, and bind it in RegisteredToolAdapter
  to the tool's own name, so a re-registered built-in actually receives it.
- Make delegation same-tool only: invokeTool takes just (params, options) and
  runs the native built-in of the caller's own name. It cannot reach an
  arbitrary target, so it cannot escalate past the approval already granted
  for the call, and the native call is not re-gated.
- Track recursion depth per call chain (threaded through invokeNativeTool and
  createContext) instead of session-global state, so concurrent delegations
  do not interfere.
- Seed the native resolver from the xdev registry when present (it retains
  discoverable built-ins like browser), else the built-in registry.

Replaces the ToolContextStore-level unit test with an end-to-end test that
registers a built-in wrapper through the extension/session path and asserts
the native tool runs the wrapper's delegated input.
2026-07-30 10:35:12 -07:00
can1357 daeb683528 feat(agent): restructured tool call dispatch to validate arguments earlier
- Added `prepareToolCallDispatch` and `PreparedToolCall` to handle argument validation and `beforeToolCall` before message snapshotting.
- Implemented `preparedDispatchByMessage` WeakMap to store pre-dispatch results for streamed messages.
- Updated `executeToolCalls` to consume pre-computed dispatch preparation results.
- Updated documentation and changelog to specify `beforeToolCall` timing on the streamed path.
2026-07-27 23:01:50 +02:00
can1357 da6d11de0e feat(agent): introduced prepareToolCall phase supporting argument replacement
- Added a prepareToolCall phase to the agent loop running before tool scheduling for validation and hooks.
- Updated BeforeToolCallContext and result types to support argument replacement instead of in-place mutation.
- Updated coding-agent extension handling and runner to track emitted tool calls and re-evaluate approvals on input revisions.
- Added comprehensive test coverage for argument replacement, concurrency resolution, and schema validation.
2026-07-27 22:55:20 +02:00
can1357 811cb77c52 feat(coding-agent): updated steering interjection format to system notice
- Restructured the user interjection prompt to use a system-notice envelope instead of nested message tags.
- Updated associated tests to verify the new system-notice formatting for steering messages.
2026-07-27 17:06:40 +02:00
can1357 995814b499 test(coding-agent): stubbed agent.continue in test to isolate queue observation
- Stubbed agent.continue to prevent idle-queue drain from consuming steer before inspection.
2026-07-24 02:48:00 +02:00
roboomp 9269823d16 fix(coding-agent): shared codex state for btw websockets
- Forwarded the session provider state map to ephemeral side-channel turns so Codex can allocate websocket transport state for the side request session id.
- Extended the /btw side-channel regression to assert providerSessionState reaches the stream options with the websocket preference.

Fixes #5213
2026-07-11 17:46:28 +00:00
roboomp 2c161d2a8f fix(coding-agent): preserved btw codex websocket routing
- Preserved the session websocket preference for ephemeral /btw side-channel turns so Codex websocket-only models do not fall back to SSE.
- Prioritized active /btw and /omfg panels in Esc handling before loop, maintenance, and main-turn interrupts.
- Added regression coverage for side-channel websocket options and /btw Escape priority.

Fixes #5213
2026-07-11 17:31:37 +00:00
roboomp edaaec398c fix(task): routed side requests through provider cap
Passed the provider-capped stream wrapper into AgentSession side-channel requests so /btw, /omfg, IRC auto-replies, and handoff generation share the same per-provider concurrency limit as normal turns.

Added focused coverage for runEphemeralTurn and handoff generation using the configured side stream function.
2026-06-28 20:57:13 +00:00
roboomp a2471339a7 test(coding-agent): cover subagent append-only context rewrites
Add a createAgentSession-based subagent regression for issue #3406. The test
runs a taskDepth=1 session against a loopback llama.cpp-style model so
provider.appendOnlyContext auto-enables through the SDK path used by task
subagents.

A real context extension rewrites the prior assistant turn on the second
subagent request. The captured provider contexts assert the first request's user
message object is reused in the second request, proving the append-only log kept
the stable prefix instead of clearing and re-rendering it for subagents.

Fixes #3406
2026-06-24 23:00:19 +00:00
can1357 7302a7ae96 feat(coding-agent): improved secret obfuscation and data protection
- Refined obfuscation logic to use granular, typed transformations instead of generic object traversal.
- Enforced an 8-character minimum for secret patterns and restricted redaction to user-authored content to prevent false positives.
- Preserved system prompts, tool schemas, and opaque remote replay data to maintain provider context and data integrity.
- Integrated protected snapshot exports with targeted redaction to safeguard sensitive information in shared sessions.
2026-06-22 01:13:52 +02:00
can1357 b91a15cbcf fix(coding-agent): ensured side-channel turns obfuscate secrets and tools
- Verified that side-channel turns maintain stable prompt cache parity with main turns.
- Applied secret and tool obfuscation to ephemeral assistant side-channel data to prevent leakage.
- Updated `Agent` and `AgentSession` test suites to validate consistency under native dialect environments.
2026-06-20 23:24:41 +02:00
can1357 b5437c2cad feat(coding-agent): improved prompt caching for ephemeral side-channel requests
- Added `buildSideRequestContext` to the `Agent` class to generate prompt-cache-friendly provider contexts.
- Updated ephemeral side-channel turns to forward the full tool catalog to maintain prompt cache hit rates.
- Injected a `developer` role reminder into ephemeral turns to instruct the model to suppress tool calls.
- Implemented automatic post-processing to strip any tool calls from ephemeral turn responses.
- Exported message and dialect helper functions in `agent-loop.ts` to support context construction.
2026-06-20 23:19:10 +02:00
can1357 ffc842ee7c fix(agent): reset promoted memory prompt on session fork
fork() reset mnemopi conversation tracking directly but skipped the shared new-transcript reset, so the folded/promoted first-turn memory stayed in #baseSystemPrompt. The next turn re-recalled and the change-detection saw no diff, taking the fallback promotion path and injecting the <memories> block twice into the forked session prompt. Route fork() through #resetMemoryContextForNewTranscript() like the other reset paths and add a regression test asserting the forked prompt contains recalled memory exactly once.
2026-06-20 22:16:58 +02:00
roboomp 1b197956a4 fix(agent): reset memory prompts on new transcripts
Restored and refreshed promoted memory prompts through the shared new-transcript reset path used by new sessions, handoff, branch, /btw, and cross-session switches.\n\nAdded coverage for newSession after first-turn memory recall so stale recalled memories cannot leak into the next transcript when recall returns no context.\n\nFixes #3111
2026-06-20 08:50:30 +00:00
roboomp 7d7cc1d1ba fix(agent): cleared promoted memory on session switch
Reset memory recall state before rebuilding the prompt during session switches, and clear fallback-promoted memory prompts when moving to another session.\n\nAdded a regression test that switches sessions after first-turn memory recall and verifies the next session does not receive stale memories.\n\nFixes #3111
2026-06-20 08:45:25 +00:00
roboomp 3d864fa763 fix(agent): preserved memory prompt cache
Promoted first-turn memory recall into the stable base prompt so append-only sessions do not drop the memory block on the next turn and rebuild the provider prefix.\n\nAdded a regression test covering a memory backend that recalls once before the first model request.\n\nFixes #3111
2026-06-20 08:32:48 +00:00
can1357 80a0a1b8a8 feat(utils): replaced createAbortableStream with abortableSource
- Introduced `abortableSource` as a lighter, direct-reader async generator.
- Removed the `createAbortableStream` public API to eliminate unnecessary stream wrapper layers.
- Updated internal stream processing to use `abortableSource` for improved memory and performance.
2026-06-19 16:06:18 +02:00
can1357 5168e6d6af Merge PR #2791: fix(tool): resolve pasted image attachments in inspect_image (@roboomp)
# Conflicts:
#	packages/coding-agent/src/tools/inspect-image.ts
2026-06-19 00:59:03 +02:00
can1357 a0cffe4814 feat: updated model-aware API-key resolution and antigravity endpoint failover
- Updated getApiKey signatures to accept a Model and return ApiKey or ApiKeyResolver.
- Updated stream key handling to resolve credentials per model and use seedApiKeyResolver for retries.
- Added antigravityEndpointMode setting with auto/production/sandbox endpoint selection.
- Added 429/5xx endpoint failover for Gemini stream, usage, search, and image calls.
2026-06-17 12:24:21 +02:00
roboomp 4c793d8f88 fix(tool): limited image attachment lookup
Restricted inspect_image attachment handles to user/developer submitted image messages so later tool-result images cannot replace pasted Image #N references. Added regression coverage for eval-style tool result image blocks after a user attachment.
2026-06-16 18:22:18 +00:00
can1357 e3501e3f76 chore: fix merge issues 2026-06-10 08:35:51 +02:00
can1357 ec81b927fa fix(coding-agent): redact ephemeral side-channel context and preserved remote compaction history
runEphemeralTurn (IRC//btw) called streamSimple directly with the raw
system prompt, bypassing the SDK-level obfuscateProviderContext wrapper;
and #obfuscatePreparationForProvider skipped previousPreserveData, so a
pre-fix openaiRemoteCompaction.replacementHistory could resend raw
secrets on the next remote compaction.

Addresses review feedback on #2147.
2026-06-10 08:26:02 +02:00
can1357 ae415199dc feat: added build-time compatibility in ModelSpec/buildModel pipeline
- Centralized catalog and registry handling on `ModelSpec` and `buildModel`, resolving compatibility at model build time.
- Removed runtime compatibility detectors and switched provider request flows to direct `model.compat` reads.
- Added compat fields (`supportsReasoningParams`, `alwaysSendMaxTokens`, `strictResponsesPairing`, `whenThinking`).
- Persisted explicit compatibility overrides through `compatConfig` in discovery and cache merge paths.
2026-06-10 06:20:51 +02:00
can1357 462c2b749c fix(coding-agent/task): show agent type in task result header
Append the dispatched agent type to the task result frame header so it reads `Task 16 agents: Reviewer` instead of just `Task 16 agents`.
2026-06-08 14:22:49 +02:00
can1357 0753a7a433 feat(agent): removed max tool-call caps from agent loop and session flow
- Removed `maxToolCallsPerTurn` from `AgentOptions`, `AgentLoopConfig`, and config serialization.
- Removed stream-loop cap enforcement, including the `toolcall_end` abort path and capped assistant messages.
- Removed Anthropic Opus 4.8 batch-cap resolver and agent-session sync logic from coding-agent.
- Updated tests and changelogs to align with uncapped tool-call behavior and dropped cap-specific cases.
2026-06-08 14:15:46 +02:00
can1357 4a9ee14e33 feat(coding-agent): wrapped mid-turn steers in wire-only envelope
- Marked steering user messages and wrapped them pre-LLM so the model sees a `` envelope.
- Kept transcripts and persisted history with the user's original raw text.
- Restored `AssistantMessageComponent` stable-prefix completion API.
2026-06-04 17:41:56 +02:00
can1357 ae905fb3cf feat(agent): added agent tool-call cap enforcement to stream loop
- Added `maxToolCallsPerTurn` support to `AgentOptions` and `AgentLoopConfig`, with Agent getter/setter and serialized state wiring.
- Implemented stream-loop cap handling by normalizing bad values and halting after `toolcall_end` reaches the limit.
- Added `ANTHROPIC_TOOL_CALL_BATCH_CAP`=8 and wired session cap sync on init, model changes, and restore.
- Added tests that truncated a 10-call stream to 8 tool calls, and verified non-Claude models resolve no cap.
2026-05-30 04:47:58 +02:00
can1357 c5055d6623 feat(ai): added OpenRouter routing-variant suffix support
- Added `openrouterVariant` option to `SimpleStreamOptions` and `OpenAICompletionsOptions` to append routing suffixes (`:nitro`, `:floor`, `:online`, `:exacto`) to OpenRouter model IDs at request time.
- Skips appending when the model ID already carries an explicit colon-suffix.
- Exposed `providers.openrouterVariant` setting in the coding-agent UI under Settings → Providers.
- Plumbed through `pi-native-server` forwarder and `AgentSession` options preparation.
2026-05-27 18:41:47 +02:00
can1357 bb4c9cae1e feat(coding-agent): added configurable IRC timeout with AbortSignal cancellation
- Added configurable IRC message timeout setting with 120-second default to prevent indefinite hangs.
- Implemented timeout enforcement for IRC send operations using AbortSignal-based cancellation.
- Modified Python tool bridge to route concurrent evaluations using per-run identifiers alongside session IDs.
- Enhanced test coverage for IRC timeout behavior, tool validation, and ephemeral cache key separation.
2026-05-26 14:56:49 +02:00
can1357 9f386dd6e5 feat(ai,coding-agent): raw SSE diagnostics + steady-state idle watchdog
Adds an opt-in onSseEvent callback across HTTP-streaming providers (Anthropic, OpenAI Responses/Completions, Azure OpenAI Responses, OpenAI Codex SSE, Google Gemini CLI, GitLab Duo, Kimi, Synthetic) so callers can inspect raw SSE frames without altering parsed output. Provider fetch wrapping only tees response bodies when an observer is wired; standalone packages/ai consumers without onSseEvent are not penalized.

Adds streamIdleTimeoutMs (env: PI_STREAM_IDLE_TIMEOUT_MS, with PI_OPENAI_STREAM_IDLE_TIMEOUT_MS as a backward-compatible alias). Anthropic now enforces a steady-state idle watchdog (default 120s) in addition to the first-event watchdog. OpenAI Responses, Azure Responses, and Codex (SSE + WebSocket) gain a semantic-progress predicate so response.in_progress-style keepalives no longer keep stalled tool calls alive forever.

Adds a coding-agent debug-panel raw SSE viewer backed by a per-session bounded buffer (1000 records / 512KB) that AgentSession populates unconditionally so users can post-hoc inspect a stuck stream from the TUI.
2026-05-10 04:53:41 +02:00
can1357 8c323666be feat: added ordered systemPrompt arrays and normalized context prompts
- Converted systemPrompt APIs and state types to ordered `string[]` across agent, AI, and coding-agent surfaces.
- Added `normalizeSystemPrompts` and applied it to context normalization before building provider request payloads.
- Updated AI providers to emit separate normalized prompt blocks/messages instead of a single merged system prompt.
- Removed dedicated `projectPrompt` state and remapped that context into system-context buckets in session, dump, and token accounting.
- Aligned tests and changelogs to pass and assert `systemPrompt` as arrays with ordered prompt semantics.
2026-05-04 15:20:26 +02:00
can1357 ed2fd6e3f3 feat(coding-agent): added edit tool consolidation via vim handlers
- Removed the standalone vim tool and normalized built-in/requested tooling to edit.
- Updated session and SDK tool activation to dedupe lowercase names and track edit state via the edit key.
- Added vim-mode argument detection and delegated edit rendering/execution into Vim handlers under edit.
- Updated Vim step handling to auto-reorder numeric-positioned commands, including cc/C/S/s/i/I/A cases.
- Renamed prompt/changelog text and test expectations to reflect edit-only tool naming and usage.
2026-04-14 10:49:53 +02:00
can1357 9f9433c5ca feat(coding-agent): added contextual vim ex parsing for .,$,+,- addresses
- Added contextual Vim ex parsing for `.,$`, `+/-` addresses, copy/move destinations, and `del/ya` aliases.
- Added Vim engine handling for clamped ranges, no-op `update`, and register-aware `yank`/`put` command execution.
- Added regression tests for explicit ranges, yank/put, inline-cursor rendering, and `message_update` ordering.
- Updated session event flow by queuing `message_update` events, changed websocket default to `off`, and documented Unreleased notes.
2026-04-13 22:52:26 +02:00
maximhar 952db9fd93 feat: add ephemeral /btw side-question panel (#399)
* feat: add ephemeral /btw side-question panel

* fix: preserve /btw live context and payload hooks

* fix: send /btw question through session pipeline
2026-03-14 10:42:26 +01:00