Commit Graph
353 Commits
Author SHA1 Message Date
can1357 67f6518e42 feat: enhanced tool robustness, improve authentication flow, and update API parameters
- Implement JSON repair and strict argument validation to sanitize raw payloads and redact sensitive information from agent event logs.
- Add automatic authentication fallback for benchmark model resolution to ensure consistent performance testing across providers.
- Refactor search tool API parameters by replacing `i` with a case-sensitive `case` boolean flag for clarity.
- Update session history formatting to ensure empty objects are consistently serialized as `{}` instead of empty strings.
2026-06-19 16:46:07 +02:00
can1357 96151e6c30 feat: implemented tool description pruning to reduce token usage
- Added utility functions to strip descriptions from JSON schemas and tool definitions for optimized token output.
- Integrated `pruneToolDescriptions` configuration across agent loops and sessions to enable optional schema pruning.
- Updated agent context and snapshot logic to propagate pruning settings and maintain fingerprinting integrity.
- Verified schema structural integrity and removal of annotation descriptions through new unit tests.
2026-06-19 06:55:19 +02:00
roboomp 04d23eff0f fix(ai): preserved valid empty tool params
Only prune optional empty strings when the property schema rejects the explicit value, preserving valid empty strings used as tool arguments.
2026-06-18 14:47:03 +00:00
roboomp bdfa8c0804 fix(ai): pruned optional empty tool params
Treat empty strings on optional tool arguments as omitted before schema validation so MCP calls do not fail pattern or type checks for model-filled placeholders.

Fixes #2981
2026-06-18 14:38:18 +00:00
can1357 291b3c74c2 feat: enhanced model reasoning, schema normalization, and loop guarding
- Integrated comprehensive loop guard support for DeepSeek and assistant prose patterns, including configurable stream checks.
- Implemented Moonshot Flavored JSON Schema (MFJS) normalization for improved tool compatibility and enum type inference.
- Added support for Ollama reasoning effort backfilling and Grok-specific service tier cost tracking across providers.
- Expanded model catalog with new entries and unified compatibility logic for improved OpenRouter API integration.
2026-06-18 04:51:43 +02:00
can1357 ee90bca4e6 feat(ai): integrated ark json ast parsing and normalization into the wire schema pipelines
- Adds conversion utilities to detect and parse Ark JSON AST models into wire-compatible schemas.
- Extracted inline JSDoc-style comments appended to object keys inside Ark ASTs to assign descriptions correctly.
- Cascades normalization of property comments down child schemas within the schema processing pipelines.
- Upgrades fallback JSON schema resolution to auto-detect and convert embedded Ark AST maps.
2026-06-18 01:57:23 +02:00
can1357 0386d44fec refactor(ai): replaced abort signal timeouts with clearable fetch timers
- Prevents absolute `AbortSignal.timeout` from cutting off active stream bodies by introducing a clearable pre-response timer.
- Clears the watchdog timer for Bedrock, Gemini, Ollama, and Codex providers once headers are received.
- Restores regular caller abort signaling capability on the combined fetch stream.
- Adds comprehensive fake-timer tests to cover the timeout arming and clearing lifecycle.
2026-06-18 01:57:23 +02:00
can1357 7c295faa52 feat: added native support for ArkType schemas alongside Zod
- Added native support for parsing, normalized validation, and serialization of ArkType schemas throughout the agent pipeline.
- Implemented pruning of unconstrained union branches and normalization helpers to handle unrepresentable strict-mode branches.
- Patched ArkType's schema package to preserve declared object key order during serialization.
- Integrated ArkType schemas into `agent-loop` and migrated coding agent tool parameters to ArkType format.
2026-06-18 00:59:56 +02:00
can1357 a050474af7 feat: migrated validation schemas and tool definitions from Zod to ArkType
- Migrated all wire protocol, schema definitions, and tools validation from Zod to ArkType across multiple packages.
- Updated extension runtimes, custom tools loader, and TypeBox compatibility shim to expose and use ArkType instances.
- Added a comprehensive ArkType migration guide, validation parity tests, and helper utilities.
- Removed redundant PDF asset routing and parsing implementations from the read tool.
2026-06-18 00:59:53 +02:00
can1357 d4317d3d20 feat(ai): consolidated OpenAI-family streaming and add OpenRouter API support
This change introduces a new `openrouter` API type and extensively refactors OpenAI-family streaming providers, centralizing shared logic and improving robustness.

Key changes include:
- **Unified OpenAI-family Logic:** Consolidated core utilities, compat resolution, request shaping, and stream processing into `openai-shared.ts`, reducing duplication across `openai-completions`, `openai-responses`, and `openai-codex-responses`.
- **OpenRouter API Type:** Introduced a dedicated `openrouter` API type with dual-surface compatibility, allowing it to dispatch requests as either OpenAI Chat Completions or Responses.
- **Enhanced Provider Integration:**
    - Improved Perplexity search to leverage shared OpenAI streaming transports, including API-key fallback to OpenRouter and support for Perplexity's Responses API.
    - Integrated xAI-specific logic directly into the shared `stream.ts` dispatch, removing the dedicated `xai-responses` provider.
    - Refined credential parsing for Google Gemini CLI and handling of Azure deployment names.
- **Robustness & Consistency:** Improved error handling for Codex, standardized output token parameter resolution, and ensured consistent application of reasoning suppression across all Chat Completions dialects.
- **New Documentation:** Added `provider-endpoint-constraints.md` to detail endpoint-specific behaviors and quirks for various providers.
- **Telemetry & Debugging:** Extended telemetry propagation to advisor calls and overflow compaction tasks. Improved debugging for Codex WebSocket failures and stream error messages.
- **Tooling & Security:** Updated browser stealth scripts to prevent detection and added a new `ts-no-inline-cast-access` TTSR rule.
2026-06-17 21:36:48 +02:00
can1357 0d9ec354e7 fix: fixed Gemini thinking-loop handling across streaming dispatch paths
- Added Gemini thinking-loop detection helpers for near-duplicate and verbatim output checks.
- Wrapped `stream`, `streamPiNative`, and `streamSimple` dispatches with the loop guard.
- Emitted retryable empty-content loop errors and stopped completion events on loop hits.
- Added `enableGeminiThinkingLoopGuard` options for OpenAI compatibility with Gemini defaults and overrides.
2026-06-17 13:44:33 +02:00
Can BölükandGitHub 623653dc03 Merge branch 'main' into fix/google-oauth-validation-url 2026-06-17 11:36:40 +02:00
can1357 bcf29b9d1b fix(ai): fixed nested JSON coercion for tool argument values
- Enabled recursive parsing in `tryParseJsonForTypes` to coerce double-encoded JSON strings.
- Updated `coerceArgsFromIssues` to parse object/array JSON strings before singleton-array fallback.
- Prevented malformed container strings from being wrapped into arrays so validation returns array errors directly.
2026-06-17 09:43:39 +02:00
roboompandcan1357 d35d1c1883 fix(ai): loosened openai pattern property fallback
Rewrote unsupported lookaround patternProperties keys to a supported catch-all pattern instead of dropping their value schemas, preserving dynamic-key tool arguments when additionalProperties is false.

Extended sanitizer and Codex conversion regression coverage for the closed dynamic-key case.

Fixes #2784
2026-06-17 00:23:37 +02:00
igasmi 7497d50d93 fix(ai): surface Google OAuth account-verification URL on VALIDATION_REQUIRED login 2026-06-16 17:48:58 -04:00
roboomp e4444a0fe7 fix(ai): normalized stripped openai schemas
Converted schema nodes emptied by OpenAI Responses lookaround stripping to boolean true so pattern-only nodes keep the existing empty-schema semantics.

Extended sanitizer and Codex regression coverage for pattern-only property and propertyNames schemas.

Fixes #2784
2026-06-16 15:54:50 +00:00
roboomp 965afbe377 fix(ai): stripped openai pattern property lookarounds
Dropped unsupported lookaround regex keys from OpenAI Responses patternProperties maps while preserving ordinary property names and supported regex keys.

Extended sanitizer and Codex tool conversion coverage for patternProperties.

Fixes #2784
2026-06-16 15:42:32 +00:00
roboomp a93a6c3908 fix(ai): stripped openai responses regex lookarounds
Removed JSON Schema pattern values containing regex lookaround from OpenAI Responses/Codex tool schemas so incompatible MCP tools do not poison the request.

Added schema-normalization and Codex conversion regression coverage for Figma-style fileKey patterns.

Fixes #2784
2026-06-16 15:24:54 +00:00
roboompandcan1357 3e1c51b4f4 fix(ai): classified ollama context-fill errors
Recognized the empty Ollama finish_reason:length guidance as context overflow so coding-agent promotion and compaction recovery still run after surfacing the actionable error.

Added overflow utility coverage for the Ollama prompt-filled-context wording.
2026-06-16 15:33:26 +02:00
Asaf Mahlev 86523bc7cc fix(openai-responses): quarantine invalid tool schemas instead of failing the turn
One MCP tool whose input schema can't be emitted as a valid strict tool schema
for the active provider made the whole request 400, so the assistant couldn't
respond at all (#2652). `convertTools` now validates each tool's emitted
parameter schema for enum/const-vs-type contradictions that pass structural
JSON-Schema validation but the provider rejects (a non-null enum on a
type:"null" node; an enum on an array node), and drops just the offending tool
with a `logger.warn` naming the tool + schema path, keeping the rest of the
request valid.

- New `findStrictToolSchemaViolation` in utils/schema: a semantic enum/const-vs-
  type checker. The existing `isValidJsonSchema` is structural-only and accepts
  these contradictions, which is exactly why they reach the provider.
- Tests: the three reported shapes (nullable-enum, enum-on-array, anyOf/const),
  nested-path reporting, valid combinations incl. nullable unions, and the
  convertTools quarantine (bad tool dropped, others survive).
2026-06-16 02:26:35 +03:00
can1357 c341fe99a8 Merge PR #1837: fix(ai): preserve nullable enum tool schemas 2026-06-15 19:46:10 +02:00
can1357 e59a5f9ac3 Merge PR #1789: fix(ai): parse JSON-encoded array strings against union(string, array) tool schemas 2026-06-15 19:46:10 +02:00
can1357 57783e68ed fix(ai): fixed unterminated thinking blocks at stream boundaries
- Dialect scanners for DeepSeek, Gemini, Gemma, GLM, Kimi, Pi, and Qwen3 now emit thinkingEnd on final chunks when a thinking state is still open.
- Markup healing was changed to return event streams with synthesized tool-call events removed, and OpenAI/Ollama streaming now uses this path when tool_calls are already structured.
- OpenAI completions streaming now suppresses healed thinking output when explicit reasoning content is present, with new tests covering unterminated and duplicate-thinking scenarios.
2026-06-15 14:56:16 +02:00
can1357 e1814d9a08 refactor: renamed grammar module to dialect with unified transcript rendering
- Renamed ToolCallSyntax type to Dialect and Grammar interface to DialectDefinition across all packages.
- Moved grammar directory to dialect and updated all import paths in agent, ai, catalog, and coding-agent packages.
- Added renderTranscript and renderThinking methods to DialectDefinition, enabling native dialect-aware conversation serialization.
- Consolidated rendering utilities into new dialect/rendering.ts with shared helpers for ChatML, legacy text, and dialect-specific formatting.
- Updated conversation serialization in agent and coding-agent to use dialect.renderTranscript() for native turn envelope rendering.
2026-06-15 13:58:12 +02:00
can1357 8b7dd10a8a feat: added native tool inventory rendering with TypeScript signatures
- Added `jsonSchemaToTypeScript` and `renderToolInventory` to generate tool blocks with TypeScript signatures.
- Added `examples` and `TSchema` fields to dump-tool metadata and passed them through prompt rendering.
- Changed Harmony invocation rendering to omit `<|constrain|>json` markers in tool call payloads.
- Added compact native tool list-mode inventory rendering with full `# Tool:` output elsewhere.
2026-06-15 08:12:58 +02:00
can1357 fbba331f8a feat(cross-cutting): added multi-syntax in-band tool-call support for runtime tool conversion
- Added optional Agent and SDK tool-call syntax controls (`toolCallSyntax`, `PI_OWNED_TOOLS`) for owned calls.
- Added in-band grammar scanners and renderers for Anthropic, DeepSeek, GLM, Hermes, Kimi, PI, and Qwen3.
- Added supportsTools propagation and model schema updates to route unsupported models to fallback syntax.
- Replaced stream-markup parsing with syntax-specific in-band scanners and event conversion.
2026-06-15 07:33:24 +02:00
roboomp 041f59d078 fix(ai): disabled bun native fetch timeout in streaming providers
Bun's fetch enforces a hard ~300s pre-response timeout that the caller's AbortSignal cannot lengthen. Every streaming provider's first-event/idle/SDK watchdog was silently capped by it, so cold large-context streams (multi-hundred-K prompts against slow-prefill backends) died at exactly 300s with TimeoutError.

- Added FetchWithRetryOptions.timeout (forwarded to fetch) so fetchWithRetry callers can pass Bun's timeout: false / numeric override directly.
- Passed timeout: false in openai-http, openai-codex-responses, amazon-bedrock, google-gemini-cli, ollama where each provider already constructs the fetch init.
- Added timeout to AnthropicFetchOptions and threaded timeout: false through buildAnthropicClientOptions's fetchOptions; anthropic-client already spreads fetchOptions into every fetch call.
- Allowed compat.streamIdleTimeoutMs: 0 in models.yml so the documented per-model disable knob matches the env-var escape hatch.

Verified with an out-of-tree smoke that stalls a local server 305s before responding: pre-fix the streaming provider died at ~300003ms with the Bun TimeoutError; post-fix the request completes (SUCCESS elapsed=305006ms). The smoke is discarded per directive.

Fixes #2422
2026-06-14 07:13:56 +00:00
can1357 6e8a56e24e fix(deps): migrated OpenAI providers to wire-based streaming and removed SDK dependency
- Replaced Azure and OpenAI provider calls with `postOpenAIStream` flow.
- Fixed stream error handling by retaining status, headers, and body on failures.
- Fixed stream parsing by handling raw JSON SSE frames and `[DONE]` events.
- Added `OpenAIHttpError` with parsed messages and timeout-aware retry behavior.
- Added remote-compaction tests for timeout, abort, and 500-fallback behavior.
2026-06-13 00:43:24 +02:00
can1357 99c9072427 feat: added one-shot AI request dump path support for debug workflows
- Added explicit request-debug path helpers in `packages/ai/src/utils/request-debug.ts` for one-shot dumps.
- Added `/debug dump-next-request`, `/debug dump-request`, and `/debug next-request` subcommands to arm next-request dumps.
- Changed `debug` handling in `packages/coding-agent/src/slash-commands/builtin-registry.ts` to execute args instead of always opening selector.
- Fixed explicit request-debug mode to resolve `~`/relative paths and create parent directories before logging.
- Fixed one-shot request-debug mode to consume its target after one call and overwrite existing response logs.
2026-06-12 04:46:53 +02:00
can1357 e31927eae9 feat(ai): added typed ProviderHttpError with per-provider subclasses 2026-06-12 02:33:45 +02:00
can1357 cbecab2be2 fix(ai): prevented OpenAI streams from hanging after terminal completion
- Added a terminal-aware async iterator that enforces a post-completion grace window, then ends iteration and optionally aborts the request.
- Wrapped OpenAI completions streaming with terminal detection of finish-reason and usage payloads so iteration stops once a response is logically complete.
- Stopped OpenAI Responses stream consumption at terminal response events instead of waiting for connection close timeouts.
2026-06-11 16:08:52 +02:00
can1357 e40c28146b fix(ai): reduced strict-mode retries by disabling strict tools after schema errors
- Tracked whether strict tool schemas were actually applied and used that flag when deciding strict-to-nonstrict retries.
- Recorded strict-tool failures in session state so later requests skip strict mode retries and avoid extra error rounds.
- Hardened strict schema normalization by flattening nested pure anyOf unions and expanded schema error matching for additional invalid-schema rejections.
2026-06-10 22:52:59 +02:00
roboomp 4428942b84 fix(ai): preserved constrained nullable unions
Only flatten optional anyOf schemas when the union wrapper has no sibling constraints that would exclude null.

Added a strict-schema regression for constrained anyOf properties so null remains an outer branch.
2026-06-10 20:18:39 +00:00
roboomp 4ccc9d7e88 fix(ai): flattened nullable strict unions
Flattened optional union tool schemas during strict enforcement so OpenRouter DeepSeek V4 no longer receives nested anyOf branches without a type.

Added schema-level and OpenRouter DeepSeek payload regressions for optional string-or-array tool parameters.

Fixes #2270
2026-06-10 20:13:54 +00:00
can1357 e14a63da6d feat(cross-cutting): centralized model compatibility handling with catalog resolvers
- Added catalog-level host/model predicates and compat resolvers.
- Extended compatibility types and model schema with timeout and replay flags.
- Replaced provider-specific heuristics with shared resolver-based checks.
- Updated host/identity and resolver tests to validate the new behavior.
2026-06-10 04:39:42 +02:00
can1357 1b9d9d0851 refactor(catalog)!: split model catalog from pi-ai
Move bundled models, model cache/manager, thinking metadata, effort helpers,
provider descriptors/discovery, wire constants, and model identity utilities
into the new @oh-my-pi/pi-catalog package.

Update pi-ai to keep provider runtime/auth concerns, move catalog provider
metadata into CATALOG_PROVIDERS, and migrate coding-agent, agent, stats, docs,
and tests to import catalog values from pi-catalog.

Split coding-agent model registry helpers into discovery, roles, and models
config modules while preserving registry orchestration.

BREAKING CHANGE: @oh-my-pi/pi-ai no longer exports catalog subpaths such as
/models, /model-cache, /model-manager, /model-thinking, /effort,
/provider-models*, discovery helpers, and provider wire constants; use the
matching @oh-my-pi/pi-catalog subpaths instead.
2026-06-10 04:06:57 +02:00
can1357 8a66c8786b fix(ai): surfaced Gemini stream errors and fixed Bedrock/AWS credential handling
in-band Gemini errors, promptFeedback blocks, and missing finishReason no longer report success; toolUse override stops masking SAFETY/MALFORMED finishes; schema normalization keeps DAG-shared subtrees while detecting true cycles; Google/AWS shared credential resolution detached from first caller's signal and bounded by own timeout; Bedrock keeps toolConfig under toolChoice none; eventstream cancels body on abnormal exit.
2026-06-10 01:26:31 +02:00
can1357 e6ca4d5763 fix(ai): hardened core stream, retry, and abort infrastructure
abort-aware auth retry loop preserving resolver errors; EventStream.end() can no longer strand .result(); Copilot retry honors Retry-After; DSML hold-back only triggers on real section prefixes and marks capped params explicitly; idle-iterator hoists racers with bounded reaction retention; validation errors truncate embedded args; removed dead leaky iterateUntilAbort.
2026-06-10 01:26:30 +02:00
can1357 f80d45aa6b fix(anthropic-provider): resolved Anthropic request and stream handling
- Added a 4-slot concurrency limiter for Anthropic multi-image resize work.
- Prioritized client-owned request fields and `claudeCodeVersion`-based `User-Agent` headers.
- Ignored terminal `message_delta` envelopes and treated missing `usage`/`delta` payloads as non-fatal.
- Stopped ping-only streams from consuming first-event watchdog logic and preserved timeout retries.
2026-06-09 23:17:26 +02:00
can1357 eb1a46baf5 feat: added injectable fetch transport across AI and coding network flows
- Added optional FetchImpl fields to compaction, proxy, AI, coding-agent, and mnemopi options.
- Threaded injected fetch implementations through OAuth, discovery, and search/LLM request flows.
- Removed exported hookFetch utility and its package entrypoint from utils.
- Replaced global-fetch test monkeypatching with per-test FetchImpl mocks across test suites.
2026-06-09 04:51:17 +02:00
can1357 31b6f0bf31 refactor(ai): consolidated provider config into single-source registry
- Derived descriptors, default-model map, env keys, login list, and refresh dispatch from one ProviderDefinition per provider.
- Disabled OpenAI Codex stream obfuscation and interrupted whitespace-only tool-call argument deltas.
- Derived auth-broker callback ports and paste-code login set from the registry.
2026-06-08 18:48:43 +02:00
can1357 8d13e5e8c9 chore(ai): updated model pricing and token limits
- Halved input, output, and cache-read costs for one model.
- Adjusted pricing and lowered maxTokens for two other models.
- Removed extra blank lines in api-key-validation.
2026-06-08 18:28:05 +02:00
can1357 05f2d0c75a feat(ai): added Anthropic-compatible API key validation
- Validated keys against the `/v1/messages` endpoint with base URL normalization.
- Added `anthropic-messages` strategy to API key login config.
- Emitted `message_stop` in stream timeout test fixtures.
2026-06-08 18:28:05 +02:00
can1357 421ff27eb6 fix(ai): scoped Anthropic fallback state and fixed iterator early-close cleanup
- Scoped Anthropic provider session state by base URL and model so strict-tools/fast-mode fallback state no longer leaks across unrelated endpoints or models, and fast-mode re-arming clears all matching scoped entries.
- Dropped stale strict fallback error messages after successful retries and only enabled adaptive thinking display for models that advertise support, avoiding unsupported-model 400 errors.
- Updated idle stream iteration to close the upstream iterator on non-continuing exits (including consumer early break) and added coverage for upstream closure behavior.
2026-06-08 14:44:13 +02:00
roboomp 070422bb95 fix(ai): corrected Zhipu API key placeholder
Zhipu Coding Plan keys are formatted '<id>.<secret>' (no 'sk-' prefix),
so the OAuth login prompt's 'sk-...' placeholder misled users into
thinking their pasted key was malformed.

Also extended the SECRET_PATTERNS redaction example in
docs/skills/authoring-hooks.md with the Zhipu shape and a comment noting
the list is not exhaustive, so hook authors referencing the example do
not silently miss Zhipu keys.

Fixes #2106
2026-06-08 11:18:31 +00:00
can1357 00e6e14cb4 feat: added reconstructed raw SSE capture for stream provider SDKs
- Added reconstructed SSE event emission for OpenAI, Azure, and Anthropic streams.
- Added raw SSE text to debug report bundles, including raw-sse.txt output.
- Included dropped-record metadata in raw SSE text when events were trimmed.
- Updated raw SSE and sse-debug tests for observer-based capture and safety checks.
2026-06-08 02:35:14 +02:00
roboomp 10fd51425b fix(ai): parsed minimax think tags across providers
Promoted MiniMax model/provider detection into stream markup healing so OpenCode Zen MiniMax streams use the existing thinking-tag parser instead of exposing raw tags.

Added a regression test for OpenCode Zen minimax-m3 chunks split across <think> boundaries.

Fixes #2049
2026-06-07 11:37:13 +00:00
can1357 b6d422ff65 fix(ai): memoized PI_REQ_DEBUG response-log close to avoid truncated body on cancel 2026-06-07 09:34:20 +02:00
can1357 90fca44c34 Merge remote-tracking branch 'origin/farm/621c6784/fix-anthropic-tool-arg-coercion' 2026-06-07 08:50:48 +02:00
roboomp 64e71e16fe fix(ai): scoped union branch tagging to combinator path
Only mark Zod and JSON Schema validation issues as union-branch when their own path matches the combinator's path so nested array fields inside a tag-selected branch keep their singleton-wrap repair.

Fixes #2026
2026-06-07 06:50:06 +00:00