Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(ai): make Patrol readiness probes representative of the Patrol runtime

[email protected]eb665b2a0d72
diff --git a/docs/AI.md b/docs/AI.md
index 7c2e626d4f..33d6447761 100644
--- a/docs/AI.md
+++ b/docs/AI.md
@@ -502,6 +502,16 @@ Patrol-shaped context fixtures, a multi-turn tool-result continuation, and
projected loop latency. Provider calls respect the configured cost budget and
their token counts are recorded under the `patrol_readiness` usage category.
+Probes run with the runtime the fixtures require rather than provider server
+defaults: an explicit runtime context window sized to the haystack fixtures
+(sent as `num_ctx` on Ollama and clamped to the model's trained window), a
+pinned temperature of 0, a generation budget that absorbs `<think>` reasoning
+from thinking models, and the same inter-chunk stream stall allowance as the
+real Patrol loop. When an evaluation fails, the result carries per-scenario
+evaluation detail (probe and validator errors, including the provider's stop
+reason such as `done_reason=length`) so the failure is diagnosable from the
+UI and the API snapshot.
+
Results are reported separately for **Watch only** and **Ask first**. A short
synthetic evaluation never certifies **Safe auto-fix** or **Autopilot**; those
modes remain `not_assessed` until an extended governed canary is available.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 2a27e2cc7a..7717e44eea 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -6255,6 +6255,18 @@ Ordinary Assistant success plus missing Patrol tools is a warning and
admission remains fail closed. Local Ollama and custom OpenAI-compatible health,
catalog and preflight operations honor the configured request timeout so cold
model loads are not truncated by the hosted-provider 30-second check budget.
+Advisor probes must pin the runtime they are testing rather than inherit
+provider server defaults: a runtime context window sized to the haystack
+fixtures (forwarded as `num_ctx` on Ollama and clamped to the model's trained
+window), an explicitly forwarded temperature 0, a generation budget that
+absorbs thinking-model reasoning, and the same inter-chunk stream stall
+allowance as the Patrol loop the advisor certifies. Adapters must forward an
+explicitly pinned zero temperature and synthesise tool-call IDs when a
+compatible server omits them (llama.cpp) instead of failing tool protocol on
+transport shape. Probe and validator errors, including the provider stop
+reason, must be logged and surfaced in the readiness result's `details`
+evidence rather than discarded, and a transport-level probe failure keeps its
+specific diagnosis instead of the generic capability wording.
That same browser-owned chat read model must keep target normalization helper-
driven. Assistant shells may still derive legacy VM identifiers or display
labels for read-only targeting, but they must do so through shared helpers and
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 83d13e5c23..29f0c110ee 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -3624,6 +3624,10 @@ context-quality, and latency dimensions plus per-autonomy-mode suitability;
`patrol_model_readiness`. Advisor execution must remain cancellable, use the
same settings-write permission boundary as other AI diagnostics, and avoid
returning prompts, tool transcripts, credentials, or infrastructure data.
+Failed evaluations carry per-scenario probe and validator evidence in
+`details` (synthetic scenario names, validator messages, and provider stop
+reasons only — never fixture prompts or infrastructure content) so operators
+can diagnose a failure from the snapshot alone.
Every mobile-facing contract change must update the canonical manifest,
regenerate both repositories, keep the mobile consumer minimum compatible, and
diff --git a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
index a51d0aaa14..d9645f30ad 100644
--- a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
+++ b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
@@ -288,6 +288,14 @@ export const PatrolModelReadinessControl: Component<{ state: AISettingsState }>
<Show when={r().recommendation}>
<p class="text-[11px] mt-1 opacity-90">{r().recommendation}</p>
</Show>
+ <Show when={(r().details?.length ?? 0) > 0}>
+ <div class="mt-1">
+ <p class="text-[11px] font-medium">Evaluation detail</p>
+ <ul class="mt-0.5 list-disc pl-4 text-[10px] opacity-80">
+ <For each={r().details}>{(item) => <li>{item}</li>}</For>
+ </ul>
+ </div>
+ </Show>
<Show when={r().metadata?.context_window || r().metadata?.quantization_level}>
<p class="text-[11px] mt-1 opacity-70">
<Show when={r().metadata?.context_window}>
diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
index dc48920c88..00df9c8df2 100644
--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
@@ -1222,6 +1222,61 @@ describe('AISettings provider save failure context', () => {
);
});
+ it('surfaces per-scenario evaluation detail for a failed readiness run (issues #1624/#1614)', async () => {
+ getSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ enabled: true,
+ configured: true,
+ model: 'ollama:qwen3:8b',
+ patrol_model: 'ollama:qwen3:8b',
+ ollama_configured: true,
+ configured_providers: ['ollama'],
+ });
+ runPatrolModelReadinessMock.mockResolvedValue({
+ probe_version: 'patrol-readiness/v1',
+ success: false,
+ transport_healthy: true,
+ patrol_capable: false,
+ status: 'warning',
+ provider: 'ollama',
+ model: 'qwen3:8b',
+ duration_ms: 20_500,
+ summary:
+ 'The provider is healthy for ordinary chat, but the selected model did not demonstrate Patrol’s streaming tool protocol.',
+ details: [
+ 'Scenario "typed-tool" tool protocol: expected exactly one tool call, got 0 (the model hit the generation cap before finishing: done_reason=length)',
+ 'Scenario "backup-failure" tool protocol: nonce did not match',
+ ],
+ dimensions: {
+ connectivity: { status: 'pass', summary: 'Connected.' },
+ tool_protocol: { status: 'fail', summary: 'Failed.', attempts: 3, passed: 0 },
+ context_quality: { status: 'fail', summary: 'Failed.', attempts: 2, passed: 0 },
+ latency: { status: 'pass', summary: 'Passed.', warm_p50_ms: 1_000 },
+ },
+ modes: {
+ monitor: { status: 'not_suitable', summary: 'Protocol failed.' },
+ approval: { status: 'not_suitable', summary: 'Protocol failed.' },
+ assisted: { status: 'not_assessed', summary: 'Extended canary required.' },
+ full: { status: 'not_assessed', summary: 'Governed canary required.' },
+ },
+ recorded_at: '2026-07-13T08:00:00Z',
+ recorded_at_unix: 1783929600,
+ });
+
+ renderComponent('patrol');
+ fireEvent.click(await screen.findByRole('button', { name: 'Check Patrol model' }));
+
+ expect(
+ await screen.findByText('Provider connected; Patrol capability not verified'),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Evaluation detail')).toBeInTheDocument();
+ expect(
+ screen.getByText(/expected exactly one tool call, got 0/),
+ ).toBeInTheDocument();
+ expect(screen.getByText(/done_reason=length/)).toBeInTheDocument();
+ expect(screen.getByText(/nonce did not match/)).toBeInTheDocument();
+ });
+
it('cancels an in-flight local model readiness evaluation', async () => {
getSettingsMock.mockResolvedValue({
...baseSettings(),
diff --git a/frontend-modern/src/types/ai.ts b/frontend-modern/src/types/ai.ts
index 380c70094c..47ab13843b 100644
--- a/frontend-modern/src/types/ai.ts
+++ b/frontend-modern/src/types/ai.ts
@@ -193,6 +193,9 @@ export interface PatrolModelReadinessSnapshot {
cause?: string;
summary: string;
recommendation?: string;
+ // Per-scenario probe and validator evidence explaining a failed evaluation
+ // (e.g. "expected exactly one tool call, got 0").
+ details?: string[];
metadata?: {
fingerprint?: string;
family?: string;
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index c08abc2b38..e3f1bc9d3f 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -28,7 +28,13 @@ type parallelToolResult struct {
Err error
}
-const patrolProviderStreamIdleTimeout = 60 * time.Second
+// PatrolProviderStreamIdleTimeout bounds the gap between stream chunks on
+// Patrol provider turns. Exported so the Patrol model readiness advisor can
+// probe with the same stall allowance as the loop it advises about; a stricter
+// probe fails models the real Patrol loop would run fine (#1614).
+const PatrolProviderStreamIdleTimeout = 60 * time.Second
+
+const patrolProviderStreamIdleTimeout = PatrolProviderStreamIdleTimeout
func isRetryableProviderStreamError(err error) bool {
if err == nil {
diff --git a/internal/ai/issue1624_issue1614_patrol_readiness_test.go b/internal/ai/issue1624_issue1614_patrol_readiness_test.go
new file mode 100644
index 0000000000..8a5e43bac7
--- /dev/null
+++ b/internal/ai/issue1624_issue1614_patrol_readiness_test.go
@@ -0,0 +1,183 @@
+package ai
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// Issues #1624 (Ollama) and #1614 (llama.cpp): the readiness advisor probed
+// with the provider's server defaults — no runtime context request, pinned
+// temperature 0 dropped, a 256-token generation cap consumed by <think>
+// reasoning, and a stricter stream stall bound than the real Patrol loop —
+// and discarded every validator error, so capable models failed the check
+// with nothing actionable in the result.
+
+// requestCapturingReadinessProvider wraps the scripted provider behaviour
+// while recording every ChatRequest the advisor sends.
+type requestCapturingReadinessProvider struct {
+ scriptedReadinessProvider
+ requests []providers.ChatRequest
+}
+
+func (p *requestCapturingReadinessProvider) ChatStream(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ p.requests = append(p.requests, req)
+ return p.scriptedReadinessProvider.ChatStream(ctx, req, callback)
+}
+
+// cutOffReadinessProvider simulates a model that burns the whole generation
+// budget on reasoning and is cut off before emitting a tool call.
+type cutOffReadinessProvider struct {
+ scriptedReadinessProvider
+}
+
+func (p *cutOffReadinessProvider) ChatStream(_ context.Context, _ providers.ChatRequest, callback providers.StreamCallback) error {
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{StopReason: "length", InputTokens: 100, OutputTokens: 256}})
+ return nil
+}
+
+// failingReadinessProvider fails every streaming probe at the transport level.
+type failingReadinessProvider struct {
+ scriptedReadinessProvider
+ err error
+}
+
+func (p *failingReadinessProvider) ChatStream(context.Context, providers.ChatRequest, providers.StreamCallback) error {
+ return p.err
+}
+
+func TestIssue1624ReadinessProbesPinRuntimeContextTemperatureAndPatrolIdleTimeout(t *testing.T) {
+ provider := &requestCapturingReadinessProvider{scriptedReadinessProvider: scriptedReadinessProvider{contextWindow: 32768}}
+ result := runPatrolModelReadinessWithProvider(
+ context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,
+ )
+ if !result.Success {
+ t.Fatalf("expected successful readiness evaluation, got %+v", result)
+ }
+ if len(provider.requests) != 4 {
+ t.Fatalf("captured requests = %d, want 4", len(provider.requests))
+ }
+ for i, req := range provider.requests {
+ if req.MinContextTokens != patrolReadinessProbeContextTokens {
+ t.Fatalf("request %d MinContextTokens = %d, want %d (fixtures truncate at Ollama's 4096 default without it)", i, req.MinContextTokens, patrolReadinessProbeContextTokens)
+ }
+ if !req.TemperatureSet || req.Temperature != 0 {
+ t.Fatalf("request %d must pin temperature 0 explicitly, got set=%v value=%v", i, req.TemperatureSet, req.Temperature)
+ }
+ if req.MaxTokens != patrolReadinessProbeMaxTokens {
+ t.Fatalf("request %d MaxTokens = %d, want %d (256 was consumed by <think> reasoning)", i, req.MaxTokens, patrolReadinessProbeMaxTokens)
+ }
+ if req.StreamIdleTimeout != chat.PatrolProviderStreamIdleTimeout {
+ t.Fatalf("request %d StreamIdleTimeout = %s, want the Patrol loop's %s", i, req.StreamIdleTimeout, chat.PatrolProviderStreamIdleTimeout)
+ }
+ }
+ // Fixtures must actually fit the requested runtime context.
+ for _, scenario := range patrolReadinessScenarios() {
+ if approxTokens := len(scenario.prompt) / 3; approxTokens+patrolReadinessProbeMaxTokens > patrolReadinessProbeContextTokens {
+ t.Fatalf("scenario %q (~%d tokens) does not fit the requested %d-token runtime context", scenario.name, approxTokens, patrolReadinessProbeContextTokens)
+ }
+ }
+}
+
+func TestIssue1624ReadinessClampsRuntimeContextToTrainedWindow(t *testing.T) {
+ provider := &requestCapturingReadinessProvider{scriptedReadinessProvider: scriptedReadinessProvider{contextWindow: 12000}}
+ runPatrolModelReadinessWithProvider(
+ context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,
+ )
+ if len(provider.requests) == 0 {
+ t.Fatal("expected captured probe requests")
+ }
+ for i, req := range provider.requests {
+ if req.MinContextTokens != 12000 {
+ t.Fatalf("request %d MinContextTokens = %d, want the model's trained window 12000", i, req.MinContextTokens)
+ }
+ }
+}
+
+func TestIssue1624ReadinessSurfacesValidatorErrorsAndDoneReason(t *testing.T) {
+ provider := &cutOffReadinessProvider{}
+ result := runPatrolModelReadinessWithProvider(
+ context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,
+ )
+ if result.Success || result.Dimensions.ToolProtocol.Passed != 0 {
+ t.Fatalf("expected failed tool protocol, got %+v", result)
+ }
+ if len(result.Details) == 0 {
+ t.Fatalf("validator errors must be surfaced in Details, got none: %+v", result)
+ }
+ joined := strings.Join(result.Details, "\n")
+ if !strings.Contains(joined, "expected exactly one tool call, got 0") {
+ t.Fatalf("Details must carry the validator error, got: %s", joined)
+ }
+ if !strings.Contains(joined, "done_reason=length") {
+ t.Fatalf("Details must surface the generation-cap stop reason, got: %s", joined)
+ }
+}
+
+func TestIssue1614ReadinessWrongProtocolDetailsNameEachScenario(t *testing.T) {
+ provider := &scriptedReadinessProvider{contextWindow: 32768, wrongProtocol: true}
+ result := runPatrolModelReadinessWithProvider(
+ context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,
+ )
+ if len(result.Details) < 3 {
+ t.Fatalf("expected a detail per failing scenario, got %v", result.Details)
+ }
+ joined := strings.Join(result.Details, "\n")
+ for _, scenario := range []string{"typed-tool", "backup-failure", "storage-pressure"} {
+ if !strings.Contains(joined, scenario) {
+ t.Fatalf("Details missing scenario %q: %s", scenario, joined)
+ }
+ }
+}
+
+func TestIssue1614ReadinessProbeFailureKeepsSpecificDiagnosis(t *testing.T) {
+ provider := &failingReadinessProvider{err: errors.New("stream chunk timed out after 12s")}
+ result := runPatrolModelReadinessWithProvider(
+ context.Background(), readinessTestConfig(), config.AIProviderOllama, "test-model", "ollama:test-model", provider,
+ )
+ failure := patrolRuntimeFailureFromError(provider.err)
+ if result.Summary != failure.Summary {
+ t.Fatalf("probe failure summary was overwritten: got %q, want %q", result.Summary, failure.Summary)
+ }
+ if result.Recommendation != failure.Recommendation {
+ t.Fatalf("probe failure recommendation was overwritten: got %q, want %q", result.Recommendation, failure.Recommendation)
+ }
+ if result.Cause != failure.Cause {
+ t.Fatalf("probe failure cause was overwritten: got %q, want %q", result.Cause, failure.Cause)
+ }
+ if len(result.Details) == 0 || !strings.Contains(strings.Join(result.Details, "\n"), "probe failed") {
+ t.Fatalf("probe error must be surfaced in Details, got %v", result.Details)
+ }
+}
+
+func TestIssue1624ReadinessDetailsSurviveCacheCloneAndPersistence(t *testing.T) {
+ persistence := config.NewConfigPersistence(t.TempDir())
+ cfg := readinessTestConfig()
+ service := NewService(persistence, nil)
+ service.cfg = cfg
+
+ result := emptyPatrolModelReadinessResult()
+ result.Provider = config.AIProviderOllama
+ result.Model = "test-model"
+ result.Details = []string{`Scenario "typed-tool" tool protocol: nonce did not match`}
+ result.CacheKey = patrolModelReadinessCacheKey(cfg, result.Provider, result.Model)
+ service.recordPatrolModelReadiness(result, time.Now())
+
+ reloaded := NewService(persistence, nil)
+ reloaded.cfg = cfg
+ cached, _ := reloaded.CachedPatrolModelReadiness()
+ if cached == nil || len(cached.Details) != 1 || cached.Details[0] != result.Details[0] {
+ t.Fatalf("Details must survive persistence and clone, got %+v", cached)
+ }
+ cached.Details[0] = "mutated"
+ again, _ := reloaded.CachedPatrolModelReadiness()
+ if again.Details[0] != result.Details[0] {
+ t.Fatal("cached Details must be cloned, not shared with callers")
+ }
+}
diff --git a/internal/ai/patrol_model_readiness.go b/internal/ai/patrol_model_readiness.go
index 8ba1b014dc..8680c337bf 100644
--- a/internal/ai/patrol_model_readiness.go
+++ b/internal/ai/patrol_model_readiness.go
@@ -15,6 +15,7 @@ import (
"sync"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
@@ -41,6 +42,20 @@ const (
patrolReadinessReceiptTool = "readiness_confirm_result"
patrolReadinessMinimumContext = 8192
patrolReadinessWatchEnvelope = 4 * time.Minute
+
+ // patrolReadinessProbeContextTokens is the runtime context requested for
+ // probe requests on providers with a runtime context control (Ollama
+ // num_ctx). The haystack fixtures are ~25KB (~7-9k tokens) before tool
+ // schemas and generation budget; without an explicit num_ctx Ollama runs
+ // at its server default (typically 4096) and silently truncates the
+ // prompt, capping context quality regardless of the model (#1624).
+ patrolReadinessProbeContextTokens = 16384
+
+ // patrolReadinessProbeMaxTokens caps probe generation. Thinking models
+ // (qwen3) spend reasoning tokens against this budget before emitting the
+ // tool call — Ollama counts <think> output toward num_predict — so the
+ // previous 256-token cap could cut the model off mid-reasoning (#1624).
+ patrolReadinessProbeMaxTokens = 2048
)
// PatrolModelReadinessDimension is one independently reported piece of
@@ -96,23 +111,27 @@ type PatrolModelReadinessResult struct {
// TransportHealthy records provider/model reachability independently from
// PatrolCapable. A model can serve ordinary Assistant chat while failing
// Patrol's stricter streaming tool protocol.
- TransportHealthy bool `json:"transport_healthy"`
- PatrolCapable bool `json:"patrol_capable"`
- Status string `json:"status"`
- Provider string `json:"provider,omitempty"`
- Model string `json:"model,omitempty"`
- DurationMs int64 `json:"duration_ms"`
- MaxVerifiedMode string `json:"max_verified_mode,omitempty"`
- Cause PatrolFailureCause `json:"cause,omitempty"`
- Summary string `json:"summary"`
- Recommendation string `json:"recommendation,omitempty"`
- Metadata *PatrolModelReadinessMetadata `json:"metadata,omitempty"`
- Dimensions PatrolModelReadinessDimensions `json:"dimensions"`
- Modes PatrolModelReadinessModes `json:"modes"`
- CacheKey string `json:"-"`
- inputTokens int
- outputTokens int
- providerCalls int
+ TransportHealthy bool `json:"transport_healthy"`
+ PatrolCapable bool `json:"patrol_capable"`
+ Status string `json:"status"`
+ Provider string `json:"provider,omitempty"`
+ Model string `json:"model,omitempty"`
+ DurationMs int64 `json:"duration_ms"`
+ MaxVerifiedMode string `json:"max_verified_mode,omitempty"`
+ Cause PatrolFailureCause `json:"cause,omitempty"`
+ Summary string `json:"summary"`
+ Recommendation string `json:"recommendation,omitempty"`
+ // Details carries per-scenario probe and validator evidence ("expected
+ // exactly one tool call, got 0", "nonce did not match"). Without it a
+ // failed evaluation is undiagnosable from the result alone (#1624, #1614).
+ Details []string `json:"details,omitempty"`
+ Metadata *PatrolModelReadinessMetadata `json:"metadata,omitempty"`
+ Dimensions PatrolModelReadinessDimensions `json:"dimensions"`
+ Modes PatrolModelReadinessModes `json:"modes"`
+ CacheKey string `json:"-"`
+ inputTokens int
+ outputTokens int
+ providerCalls int
}
type patrolModelReadinessCache struct {
@@ -153,6 +172,9 @@ func clonePatrolModelReadinessResult(result *PatrolModelReadinessResult) *Patrol
return nil
}
clone := *result
+ if result.Details != nil {
+ clone.Details = append([]string(nil), result.Details...)
+ }
if result.Metadata != nil {
metadata := *result.Metadata
metadata.Capabilities = append([]string(nil), result.Metadata.Capabilities...)
@@ -433,6 +455,7 @@ type patrolReadinessScenario struct {
type patrolReadinessProbeOutcome struct {
toolCalls []providers.ToolCall
+ stopReason string
duration time.Duration
firstResponse time.Duration
inputTokens int
@@ -507,6 +530,17 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
var continuationSource patrolReadinessProbeOutcome
var continuationScenario patrolReadinessScenario
var probeErr error
+ var details []string
+
+ // Probes must run with the runtime the fixtures need, not the provider's
+ // server defaults: an explicit context window sized to the haystack, the
+ // pinned zero temperature forwarded, and the same stream stall allowance
+ // as the real Patrol loop (#1624, #1614). The runtime context request is
+ // clamped to the model's trained window when the runtime reports one.
+ probeContextTokens := patrolReadinessProbeContextTokens
+ if result.Metadata != nil && result.Metadata.ContextWindow > 0 && result.Metadata.ContextWindow < probeContextTokens {
+ probeContextTokens = result.Metadata.ContextWindow
+ }
for _, scenario := range scenarios {
req := providers.ChatRequest{
@@ -514,10 +548,13 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
System: "You are running a synthetic Pulse Patrol readiness evaluation. " +
"Use exactly one appropriate readiness tool. Never call readiness_apply_change. " +
"Do not answer in prose. Copy identifiers and the nonce exactly from the fixture.",
- Messages: []providers.Message{{Role: "user", Content: scenario.prompt}},
- Tools: tools,
- MaxTokens: 256,
- Temperature: 0,
+ Messages: []providers.Message{{Role: "user", Content: scenario.prompt}},
+ Tools: tools,
+ MaxTokens: patrolReadinessProbeMaxTokens,
+ Temperature: 0,
+ TemperatureSet: true,
+ MinContextTokens: probeContextTokens,
+ StreamIdleTimeout: chat.PatrolProviderStreamIdleTimeout,
}
if providerName == config.AIProviderGemini {
req.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceRequired}
@@ -528,15 +565,39 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
result.outputTokens += outcome.outputTokens
if err != nil {
probeErr = err
+ details = append(details, fmt.Sprintf("Scenario %q probe failed: %v", scenario.name, err))
+ log.Warn().Err(err).
+ Str("scenario", scenario.name).
+ Str("provider", providerName).
+ Str("model", model).
+ Msg("Patrol readiness streaming probe failed")
break
}
durations = append(durations, outcome.duration)
firstResponses = append(firstResponses, outcome.firstResponse)
- if validatePatrolReadinessProtocol(outcome.toolCalls, scenario.nonce) == nil {
+ protocolErr := validatePatrolReadinessProtocol(outcome.toolCalls, scenario.nonce)
+ if protocolErr == nil {
toolPassed++
+ } else {
+ details = append(details, fmt.Sprintf("Scenario %q tool protocol: %v%s", scenario.name, protocolErr, patrolReadinessStopReasonNote(outcome.stopReason)))
+ log.Warn().Err(protocolErr).
+ Str("scenario", scenario.name).
+ Str("stop_reason", outcome.stopReason).
+ Str("provider", providerName).
+ Str("model", model).
+ Msg("Patrol readiness scenario failed tool-protocol validation")
}
- if scenario.context && validatePatrolReadinessCall(outcome.toolCalls, scenario) == nil {
- contextPassed++
+ if scenario.context {
+ if contextErr := validatePatrolReadinessCall(outcome.toolCalls, scenario); contextErr == nil {
+ contextPassed++
+ } else if protocolErr == nil {
+ details = append(details, fmt.Sprintf("Scenario %q context quality: %v", scenario.name, contextErr))
+ log.Warn().Err(contextErr).
+ Str("scenario", scenario.name).
+ Str("provider", providerName).
+ Str("model", model).
+ Msg("Patrol readiness scenario failed context validation")
+ }
}
if scenario.name == "storage-pressure" {
continuationSource = outcome
@@ -562,9 +623,12 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
{Role: "assistant", ToolCalls: []providers.ToolCall{call}},
{Role: "user", ToolResult: &providers.ToolResult{ToolUseID: call.ID, Content: string(toolResult)}},
},
- Tools: []providers.Tool{patrolReadinessReceiptDefinition()},
- MaxTokens: 128,
- Temperature: 0,
+ Tools: []providers.Tool{patrolReadinessReceiptDefinition()},
+ MaxTokens: patrolReadinessProbeMaxTokens,
+ Temperature: 0,
+ TemperatureSet: true,
+ MinContextTokens: probeContextTokens,
+ StreamIdleTimeout: chat.PatrolProviderStreamIdleTimeout,
}
if providerName == config.AIProviderGemini {
followup.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceRequired}
@@ -575,10 +639,24 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
result.outputTokens += outcome.outputTokens
if err != nil {
probeErr = err
+ details = append(details, fmt.Sprintf("Multi-turn continuation probe failed: %v", err))
+ log.Warn().Err(err).
+ Str("provider", providerName).
+ Str("model", model).
+ Msg("Patrol readiness continuation probe failed")
} else {
durations = append(durations, outcome.duration)
firstResponses = append(firstResponses, outcome.firstResponse)
- continuationObserved = validatePatrolReadinessReceipt(outcome.toolCalls, continuationScenario.nonce, findingID) == nil
+ receiptErr := validatePatrolReadinessReceipt(outcome.toolCalls, continuationScenario.nonce, findingID)
+ continuationObserved = receiptErr == nil
+ if receiptErr != nil {
+ details = append(details, fmt.Sprintf("Multi-turn continuation: %v%s", receiptErr, patrolReadinessStopReasonNote(outcome.stopReason)))
+ log.Warn().Err(receiptErr).
+ Str("stop_reason", outcome.stopReason).
+ Str("provider", providerName).
+ Str("model", model).
+ Msg("Patrol readiness continuation failed receipt validation")
+ }
}
}
@@ -593,11 +671,11 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
toolSummary += " Initial tool use passed, but multi-turn continuation was not verified."
}
}
+ var probeFailure *patrolRuntimeFailure
if probeErr != nil {
failure := patrolRuntimeFailureFromError(probeErr)
- result.Cause = failure.Cause
+ probeFailure = &failure
toolSummary = failure.Summary
- result.Recommendation = failure.Recommendation
}
result.Dimensions.ToolProtocol = PatrolModelReadinessDimension{
Status: toolStatus,
@@ -678,6 +756,13 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
result.Cause = PatrolFailureCauseModelToolSupportUnverified
result.Summary = "The provider is healthy for ordinary chat, but the selected model did not demonstrate Patrol's streaming tool protocol."
result.Recommendation = "Keep using this route for ordinary Assistant chat, or choose a Patrol model with reliable streaming tool use."
+ // A transport-level probe failure carries a specific diagnosis; do not
+ // let the generic capability wording overwrite it (#1614).
+ if probeFailure != nil {
+ result.Cause = probeFailure.Cause
+ result.Summary = probeFailure.Summary
+ result.Recommendation = probeFailure.Recommendation
+ }
if contextStatus == PatrolModelReadinessFail && toolStatus == PatrolModelReadinessPass {
result.Cause = PatrolFailureCauseContextQualityFailed
result.Summary = "The selected model did not pass Patrol's context-quality evaluation."
@@ -701,10 +786,26 @@ func runPatrolModelReadinessWithProvider(ctx context.Context, cfg *config.AIConf
result.Summary = "Verified for Watch only and Ask first on this install."
}
}
+ result.Details = details
result.DurationMs = time.Since(started).Milliseconds()
return result
}
+// patrolReadinessStopReasonNote annotates a validation failure with the
+// provider's stop reason when it explains the failure — a "length" stop means
+// the model exhausted the generation budget (commonly on <think> reasoning)
+// before completing the tool call (#1624).
+func patrolReadinessStopReasonNote(stopReason string) string {
+ switch stopReason {
+ case "", "tool_use", "end_turn", "stop":
+ return ""
+ case "length":
+ return " (the model hit the generation cap before finishing: done_reason=length)"
+ default:
+ return fmt.Sprintf(" (done_reason=%s)", stopReason)
+ }
+}
+
func patrolReadinessScenarios() []patrolReadinessScenario {
protocolNonce := newPatrolReadinessNonce()
backupNonce := newPatrolReadinessNonce()
@@ -826,11 +927,13 @@ func runPatrolReadinessStreamProbe(ctx context.Context, provider providers.Strea
case "done":
if data, ok := event.Data.(providers.DoneEvent); ok {
outcome.toolCalls = append([]providers.ToolCall(nil), data.ToolCalls...)
+ outcome.stopReason = data.StopReason
outcome.inputTokens = data.InputTokens
outcome.outputTokens = data.OutputTokens
outcome.completionEvent = true
} else if data, ok := event.Data.(*providers.DoneEvent); ok && data != nil {
outcome.toolCalls = append([]providers.ToolCall(nil), data.ToolCalls...)
+ outcome.stopReason = data.StopReason
outcome.inputTokens = data.InputTokens
outcome.outputTokens = data.OutputTokens
outcome.completionEvent = true
diff --git a/internal/ai/providers/issue1614_openai_toolcall_id_test.go b/internal/ai/providers/issue1614_openai_toolcall_id_test.go
new file mode 100644
index 0000000000..2f8afa5863
--- /dev/null
+++ b/internal/ai/providers/issue1614_openai_toolcall_id_test.go
@@ -0,0 +1,111 @@
+package providers
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Issue #1614: llama.cpp's /v1/chat/completions commonly returns tool_calls
+// without an id. The Ollama adapter synthesises one, but the OpenAI-compatible
+// adapter copied the empty id through (streaming) or rejected the response
+// outright (buffered), so the Patrol readiness validator failed tool protocol
+// 0/3 regardless of the model's actual tool-calling ability.
+
+func TestIssue1614StreamFinalizerSynthesisesMissingToolCallIDs(t *testing.T) {
+ builders := map[int]*openaiStreamToolCallBuilder{
+ 0: {id: "", name: "readiness_record_observation"},
+ 1: {id: "server-provided", name: "readiness_confirm_result"},
+ }
+ builders[0].args.WriteString(`{"nonce":"abc"}`)
+ builders[1].args.WriteString(`{}`)
+
+ toolCalls := finalizeOpenAIStreamToolCalls(builders)
+ if len(toolCalls) != 2 {
+ t.Fatalf("tool calls = %d, want 2", len(toolCalls))
+ }
+ if strings.TrimSpace(toolCalls[0].ID) == "" {
+ t.Fatal("missing server id must be synthesised, got empty")
+ }
+ if toolCalls[1].ID != "server-provided" {
+ t.Fatalf("server-provided id must be preserved, got %q", toolCalls[1].ID)
+ }
+ if toolCalls[0].ID == toolCalls[1].ID {
+ t.Fatal("synthesised ids must not collide with other calls")
+ }
+}
+
+func TestIssue1614StreamedToolCallWithoutIDGetsSynthesisedID(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ _, _ = w.Write([]byte(
+ `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"readiness_record_observation","arguments":"{\"nonce\":"}}]}}]}` + "\n\n" +
+ `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"abc\"}"}}]}}]}` + "\n\n" +
+ `data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}` + "\n\n" +
+ "data: [DONE]\n\n"))
+ }))
+ defer server.Close()
+
+ client := NewOpenAICompatibleClient("openai", "", "local-model", server.URL, 5*time.Second)
+ var done DoneEvent
+ err := client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "probe"}},
+ }, func(event StreamEvent) {
+ if event.Type == "done" {
+ done = event.Data.(DoneEvent)
+ }
+ })
+ if err != nil {
+ t.Fatalf("ChatStream: %v", err)
+ }
+ if len(done.ToolCalls) != 1 {
+ t.Fatalf("tool calls = %d, want 1", len(done.ToolCalls))
+ }
+ call := done.ToolCalls[0]
+ if strings.TrimSpace(call.ID) == "" {
+ t.Fatalf("llama.cpp-style tool call without id must get a synthesised id: %+v", call)
+ }
+ if call.Name != "readiness_record_observation" || call.Input["nonce"] != "abc" {
+ t.Fatalf("unexpected tool call: %+v", call)
+ }
+}
+
+func TestIssue1614BufferedToolCallWithoutIDGetsSynthesisedID(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"model":"local-model","choices":[{"message":{"role":"assistant","tool_calls":[{"type":"function","function":{"name":"readiness_record_observation","arguments":"{\"nonce\":\"abc\"}"}}]},"finish_reason":"tool_calls"}]}`))
+ }))
+ defer server.Close()
+
+ client := NewOpenAICompatibleClient("openai", "", "local-model", server.URL, 5*time.Second)
+ response, err := client.Chat(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "probe"}},
+ })
+ if err != nil {
+ t.Fatalf("Chat: %v", err)
+ }
+ if len(response.ToolCalls) != 1 {
+ t.Fatalf("tool calls = %d, want 1", len(response.ToolCalls))
+ }
+ if strings.TrimSpace(response.ToolCalls[0].ID) == "" {
+ t.Fatalf("buffered tool call without id must get a synthesised id: %+v", response.ToolCalls[0])
+ }
+}
+
+func TestIssue1614BufferedToolCallWithoutNameStillRejected(t *testing.T) {
+ response := openaiResponse{
+ Choices: []openaiChoice{{
+ Message: openaiRespMsg{
+ Role: "assistant",
+ ToolCalls: []openaiToolCall{{ID: "call-1", Function: openaiToolFunction{Name: "", Arguments: "{}"}}},
+ },
+ FinishReason: "tool_calls",
+ }},
+ }
+ if _, err := convertOpenAIResponse(response); err == nil {
+ t.Fatal("a tool call without a function name must still be rejected")
+ }
+}
diff --git a/internal/ai/providers/issue1624_ollama_probe_options_test.go b/internal/ai/providers/issue1624_ollama_probe_options_test.go
new file mode 100644
index 0000000000..d149812ce7
--- /dev/null
+++ b/internal/ai/providers/issue1624_ollama_probe_options_test.go
@@ -0,0 +1,159 @@
+package providers
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+// Issue #1624: the Patrol readiness advisor failed capable Ollama models
+// because the adapter never sent num_ctx (so large fixtures truncated at the
+// server's 4096-token default), dropped an explicitly pinned temperature 0
+// (falling back to Ollama's 0.8 default against a nonce-exact validator),
+// and discarded done_reason so a generation-cap cutoff was undiagnosable.
+
+func decodeCapturedOllamaRequest(t *testing.T, body []byte) map[string]interface{} {
+ t.Helper()
+ var request map[string]interface{}
+ if err := json.Unmarshal(body, &request); err != nil {
+ t.Fatalf("decode captured request: %v", err)
+ }
+ return request
+}
+
+func newCapturingOllamaServer(t *testing.T, response string, captured *[]byte) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Errorf("read request body: %v", err)
+ }
+ *captured = body
+ w.Header().Set("Content-Type", "application/x-ndjson")
+ _, _ = w.Write([]byte(response))
+ }))
+}
+
+func TestIssue1624OllamaStreamForwardsNumCtxAndPinnedZeroTemperature(t *testing.T) {
+ var captured []byte
+ server := newCapturingOllamaServer(t,
+ `{"message":{"role":"assistant","content":"ok"},"done":true,"done_reason":"stop","prompt_eval_count":10,"eval_count":5}`+"\n",
+ &captured)
+ defer server.Close()
+
+ client, err := NewOllamaClient("test-model", server.URL, "", "", 30*time.Second)
+ if err != nil {
+ t.Fatalf("NewOllamaClient: %v", err)
+ }
+ err = client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "probe"}},
+ MaxTokens: 2048,
+ Temperature: 0,
+ TemperatureSet: true,
+ MinContextTokens: 16384,
+ }, func(StreamEvent) {})
+ if err != nil {
+ t.Fatalf("ChatStream: %v", err)
+ }
+
+ request := decodeCapturedOllamaRequest(t, captured)
+ options, ok := request["options"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("request carried no options: %s", captured)
+ }
+ if got := options["num_ctx"]; got != float64(16384) {
+ t.Fatalf("num_ctx = %v, want 16384", got)
+ }
+ if got := options["num_predict"]; got != float64(2048) {
+ t.Fatalf("num_predict = %v, want 2048", got)
+ }
+ temperature, present := options["temperature"]
+ if !present {
+ t.Fatalf("pinned temperature 0 was dropped from the request: %s", captured)
+ }
+ if temperature != float64(0) {
+ t.Fatalf("temperature = %v, want 0", temperature)
+ }
+}
+
+func TestIssue1624OllamaChatForwardsNumCtxAndPinnedZeroTemperature(t *testing.T) {
+ var captured []byte
+ server := newCapturingOllamaServer(t,
+ `{"message":{"role":"assistant","content":"ok"},"done":true,"done_reason":"stop"}`,
+ &captured)
+ defer server.Close()
+
+ client, err := NewOllamaClient("test-model", server.URL, "", "", 30*time.Second)
+ if err != nil {
+ t.Fatalf("NewOllamaClient: %v", err)
+ }
+ if _, err := client.Chat(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "probe"}},
+ Temperature: 0,
+ TemperatureSet: true,
+ MinContextTokens: 8192,
+ }); err != nil {
+ t.Fatalf("Chat: %v", err)
+ }
+
+ request := decodeCapturedOllamaRequest(t, captured)
+ options, ok := request["options"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("request carried no options: %s", captured)
+ }
+ if got := options["num_ctx"]; got != float64(8192) {
+ t.Fatalf("num_ctx = %v, want 8192", got)
+ }
+ if got, present := options["temperature"]; !present || got != float64(0) {
+ t.Fatalf("temperature = %v (present=%v), want explicit 0", got, present)
+ }
+}
+
+func TestIssue1624OllamaUnpinnedZeroTemperatureStaysServerDefault(t *testing.T) {
+ request := ChatRequest{MaxTokens: 100}
+ options := ollamaOptionsForRequest(request)
+ if options == nil {
+ t.Fatal("expected options for MaxTokens")
+ }
+ if options.Temperature != nil {
+ t.Fatalf("unpinned zero temperature must not be forwarded, got %v", *options.Temperature)
+ }
+ if options.NumCtx != 0 {
+ t.Fatalf("num_ctx must stay unset without MinContextTokens, got %d", options.NumCtx)
+ }
+ if ollamaOptionsForRequest(ChatRequest{}) != nil {
+ t.Fatal("a request pinning nothing must not send options")
+ }
+}
+
+func TestIssue1624OllamaStreamSurfacesLengthDoneReason(t *testing.T) {
+ var captured []byte
+ server := newCapturingOllamaServer(t,
+ `{"message":{"role":"assistant","content":"partial"},"done":false}`+"\n"+
+ `{"message":{"role":"assistant","content":""},"done":true,"done_reason":"length","prompt_eval_count":10,"eval_count":256}`+"\n",
+ &captured)
+ defer server.Close()
+
+ client, err := NewOllamaClient("test-model", server.URL, "", "", 30*time.Second)
+ if err != nil {
+ t.Fatalf("NewOllamaClient: %v", err)
+ }
+ var done DoneEvent
+ err = client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "probe"}},
+ }, func(event StreamEvent) {
+ if event.Type == "done" {
+ done = event.Data.(DoneEvent)
+ }
+ })
+ if err != nil {
+ t.Fatalf("ChatStream: %v", err)
+ }
+ if done.StopReason != "length" {
+ t.Fatalf("stop reason = %q, want the provider's done_reason %q surfaced", done.StopReason, "length")
+ }
+}
diff --git a/internal/ai/providers/ollama.go b/internal/ai/providers/ollama.go
index 77e8540138..82035f7b7e 100644
--- a/internal/ai/providers/ollama.go
+++ b/internal/ai/providers/ollama.go
@@ -168,8 +168,38 @@ type ollamaToolFunction struct {
}
type ollamaOptions struct {
- NumPredict int `json:"num_predict,omitempty"`
- Temperature float64 `json:"temperature,omitempty"`
+ // NumCtx is the runtime context window for this request. Without it
+ // Ollama serves the model at its server default (typically 4096 tokens)
+ // even when the model's trained window is far larger, silently dropping
+ // the oldest prompt tokens (#1624).
+ NumCtx int `json:"num_ctx,omitempty"`
+ NumPredict int `json:"num_predict,omitempty"`
+ // Temperature is a pointer so an explicit 0 survives serialization;
+ // omitempty on a plain float64 would drop it and Ollama would fall back
+ // to its 0.8 default (#1624).
+ Temperature *float64 `json:"temperature,omitempty"`
+}
+
+// ollamaOptionsForRequest maps provider-neutral sampling and context controls
+// onto Ollama's options payload. Returns nil when the request pins nothing so
+// the server defaults apply unchanged.
+func ollamaOptionsForRequest(req ChatRequest) *ollamaOptions {
+ sendTemperature := req.TemperatureSet || req.Temperature > 0
+ if req.MaxTokens <= 0 && !sendTemperature && req.MinContextTokens <= 0 {
+ return nil
+ }
+ options := &ollamaOptions{}
+ if req.MaxTokens > 0 {
+ options.NumPredict = req.MaxTokens
+ }
+ if sendTemperature {
+ temperature := req.Temperature
+ options.Temperature = &temperature
+ }
+ if req.MinContextTokens > 0 {
+ options.NumCtx = req.MinContextTokens
+ }
+ return options
}
// ollamaResponse is the response from the Ollama API
@@ -277,15 +307,7 @@ func (c *OllamaClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
}
}
- if req.MaxTokens > 0 || req.Temperature > 0 {
- ollamaReq.Options = &ollamaOptions{}
- if req.MaxTokens > 0 {
- ollamaReq.Options.NumPredict = req.MaxTokens
- }
- if req.Temperature > 0 {
- ollamaReq.Options.Temperature = req.Temperature
- }
- }
+ ollamaReq.Options = ollamaOptionsForRequest(req)
body, err := json.Marshal(ollamaReq)
if err != nil {
@@ -448,15 +470,7 @@ func (c *OllamaClient) ChatStream(ctx context.Context, req ChatRequest, callback
}
}
- if req.MaxTokens > 0 || req.Temperature > 0 {
- ollamaReq.Options = &ollamaOptions{}
- if req.MaxTokens > 0 {
- ollamaReq.Options.NumPredict = req.MaxTokens
- }
- if req.Temperature > 0 {
- ollamaReq.Options.Temperature = req.Temperature
- }
- }
+ ollamaReq.Options = ollamaOptionsForRequest(req)
body, err := json.Marshal(ollamaReq)
if err != nil {
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.go
index 49483d0bc2..11aa8555d7 100644
--- a/internal/ai/providers/openai.go
+++ b/internal/ai/providers/openai.go
@@ -343,16 +343,16 @@ func convertOpenAIResponse(openaiResp openaiResponse) (*ChatResponse, error) {
}
if len(choice.Message.ToolCalls) > 0 {
result.StopReason = "tool_use"
- for _, tc := range choice.Message.ToolCalls {
- if strings.TrimSpace(tc.ID) == "" || strings.TrimSpace(tc.Function.Name) == "" {
- return nil, fmt.Errorf("tool call is missing an id or function name")
+ for index, tc := range choice.Message.ToolCalls {
+ if strings.TrimSpace(tc.Function.Name) == "" {
+ return nil, fmt.Errorf("tool call is missing a function name")
}
input, ok := agentcapabilities.ParseProviderToolInput(tc.Function.Arguments)
if !ok {
return nil, fmt.Errorf("tool call %q returned invalid arguments", tc.Function.Name)
}
result.ToolCalls = append(result.ToolCalls, ToolCall{
- ID: tc.ID,
+ ID: openaiToolCallID(tc.ID, tc.Function.Name, index),
Name: tc.Function.Name,
Input: input,
})
@@ -903,7 +903,7 @@ func finalizeOpenAIStreamToolCalls(builders map[int]*openaiStreamToolCallBuilder
input := agentcapabilities.ProviderToolInputOrRaw(builder.args.String())
toolCalls = append(toolCalls, ToolCall{
- ID: builder.id,
+ ID: openaiToolCallID(builder.id, builder.name, index),
Name: builder.name,
Input: input,
})
@@ -912,6 +912,18 @@ func finalizeOpenAIStreamToolCalls(builders map[int]*openaiStreamToolCallBuilder
return toolCalls
}
+// openaiToolCallID returns the server-provided tool-call ID, synthesising one
+// when the server omits it. llama.cpp's /v1/chat/completions commonly returns
+// tool_calls without an id; downstream continuation and the Patrol readiness
+// validator require a non-empty ID, so mirror the Ollama adapter's synthesis
+// instead of failing tool protocol outright (#1614).
+func openaiToolCallID(id, name string, index int) string {
+ if trimmed := strings.TrimSpace(id); trimmed != "" {
+ return trimmed
+ }
+ return fmt.Sprintf("openai_%s_%d", name, index)
+}
+
func normalizeOpenAIStreamStopReason(finishReason string, toolCalls []ToolCall) string {
stopReason := finishReason
if len(toolCalls) > 0 {
diff --git a/internal/ai/providers/provider.go b/internal/ai/providers/provider.go
index 21c745783a..ac3596741f 100644
--- a/internal/ai/providers/provider.go
+++ b/internal/ai/providers/provider.go
@@ -91,16 +91,27 @@ func (e ReasoningEffort) Valid() bool {
// ChatRequest represents a request to the AI provider
type ChatRequest struct {
- Messages []Message `json:"messages"`
- Model string `json:"model"`
- ExecutionID string `json:"execution_id,omitempty"` // Stable higher-level run ID shared across related provider turns
- MaxTokens int `json:"max_tokens,omitempty"`
- ReasoningEffort ReasoningEffort `json:"reasoning_effort,omitempty"`
- Temperature float64 `json:"temperature,omitempty"`
- System string `json:"system,omitempty"` // System prompt (Anthropic style)
- Tools []Tool `json:"tools,omitempty"` // Available tools
- ToolChoice *ToolChoice `json:"tool_choice,omitempty"` // nil = model-owned automatic selection; none = text-only safety brake; required = provider-native forced tool use where supported
- StreamIdleTimeout time.Duration `json:"-"` // Optional use-case-specific inter-chunk stall allowance; provider request payloads must not serialize it.
+ Messages []Message `json:"messages"`
+ Model string `json:"model"`
+ ExecutionID string `json:"execution_id,omitempty"` // Stable higher-level run ID shared across related provider turns
+ MaxTokens int `json:"max_tokens,omitempty"`
+ ReasoningEffort ReasoningEffort `json:"reasoning_effort,omitempty"`
+ Temperature float64 `json:"temperature,omitempty"`
+ // TemperatureSet marks Temperature as an explicit request value. Adapters
+ // treat a zero Temperature without this flag as "unset" and let the
+ // provider default apply; probes that pin temperature 0 for deterministic
+ // output (#1624) need the zero forwarded rather than dropped.
+ TemperatureSet bool `json:"-"`
+ // MinContextTokens asks providers with a runtime context-size control
+ // (Ollama num_ctx) to serve the request with at least this many context
+ // tokens. Ollama otherwise loads models at its server default (typically
+ // 4096) regardless of the model's trained window and silently truncates
+ // large prompts (#1624). Providers without such a control ignore it.
+ MinContextTokens int `json:"-"`
+ System string `json:"system,omitempty"` // System prompt (Anthropic style)
+ Tools []Tool `json:"tools,omitempty"` // Available tools
+ ToolChoice *ToolChoice `json:"tool_choice,omitempty"` // nil = model-owned automatic selection; none = text-only safety brake; required = provider-native forced tool use where supported
+ StreamIdleTimeout time.Duration `json:"-"` // Optional use-case-specific inter-chunk stall allowance; provider request payloads must not serialize it.
}
func (r ChatRequest) NormalizeCollections() ChatRequest {