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.

Resolve Assistant plain-text resource context

rcourtman0ad040bdf0b1
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 1975236a58..0ace78d912 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -654,6 +654,18 @@ runtime cost control, and shared AI transport surfaces.
tool call, must use the safe handle for scoped reads, must refuse raw
provider/config/environment/secret-bearing context expansion, and must not
leak configured forbidden resource details in content or tool inputs.
+ Plain-text resource references in live read, log, verification, or
+ command-intent Assistant prompts may use the same selected-resource handle
+ only after backend-owned canonical inventory resolution proves exactly one
+ resource match, including explicit target-kind wording such as host, node,
+ VM, container, or storage when inherited node labels would otherwise collide.
+ That path must register the resource in the session resolved context, mark it
+ as explicit current-turn access, and prepend a safe resource-context directive
+ that exposes `current_resource` but not raw aliases, hostnames, platform IDs,
+ paths, or other policy-redacted labels to external providers. Ambiguous or
+ non-live prompts must fail closed to normal model clarification/query
+ behavior; this is not a prompt-keyword router and must not choose, retry, or
+ execute the model's next investigative action.
Context-only resource handoff turns must be enforced at the tool-manifest
boundary, not only by prompt wording: unless the operator explicitly asks for
live runtime verification, a read attempt, or discovery execution, the
diff --git a/internal/ai/chat/plain_text_resource_context.go b/internal/ai/chat/plain_text_resource_context.go
new file mode 100644
index 0000000000..77456a4129
--- /dev/null
+++ b/internal/ai/chat/plain_text_resource_context.go
@@ -0,0 +1,550 @@
+package chat
+
+import (
+ "strings"
+ "unicode"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rs/zerolog/log"
+)
+
+type assistantPlainTextResourceMatch struct {
+ registration tools.ResourceRegistration
+ resourceType string
+ matchedReference string
+}
+
+var assistantPlainTextResourceTypes = []unifiedresources.ResourceType{
+ unifiedresources.ResourceTypeAgent,
+ unifiedresources.ResourceTypeVM,
+ unifiedresources.ResourceTypeSystemContainer,
+ unifiedresources.ResourceTypeAppContainer,
+ unifiedresources.ResourceTypeStorage,
+}
+
+var assistantPlainTextReferenceStopwords = map[string]struct{}{
+ "agent": {},
+ "app": {},
+ "container": {},
+ "current": {},
+ "data": {},
+ "deployment": {},
+ "docker": {},
+ "host": {},
+ "kubernetes": {},
+ "local": {},
+ "node": {},
+ "pod": {},
+ "resource": {},
+ "server": {},
+ "service": {},
+ "storage": {},
+ "system": {},
+ "vm": {},
+}
+
+func assistantPromptRequestsLiveResourceRead(prompt string) bool {
+ normalized := normalizeAssistantToolRoutingPrompt(prompt)
+ if normalized == "" {
+ return false
+ }
+ phraseSignals := []string{
+ "read only",
+ "look at",
+ "fresh verification",
+ "live runtime",
+ }
+ for _, signal := range phraseSignals {
+ if strings.Contains(normalized, signal) {
+ return true
+ }
+ }
+ termSignals := []string{
+ "run",
+ "execute",
+ "command",
+ "shell",
+ "bash",
+ "terminal",
+ "check",
+ "inspect",
+ "verify",
+ "fresh",
+ "live",
+ "log",
+ "logs",
+ "tail",
+ "journalctl",
+ "cat ",
+ "ls ",
+ "df ",
+ "du ",
+ "free ",
+ "uptime",
+ "systemctl",
+ }
+ haystack := " " + normalized + " "
+ for _, signal := range termSignals {
+ if strings.Contains(haystack, " "+strings.TrimSpace(signal)+" ") {
+ return true
+ }
+ }
+ return strings.Contains(prompt, "`")
+}
+
+func resolvePlainTextAssistantResourceReference(prompt string, provider tools.UnifiedResourceProvider) (assistantPlainTextResourceMatch, bool) {
+ liveIntent := assistantPromptRequestsLiveResourceRead(prompt)
+ if provider == nil || !liveIntent {
+ log.Debug().
+ Bool("has_provider", provider != nil).
+ Bool("live_intent", liveIntent).
+ Msg("[ChatService] Plain-text resource reference resolver skipped")
+ return assistantPlainTextResourceMatch{}, false
+ }
+ normalizedPrompt := normalizeAssistantPlainTextReference(prompt)
+ if normalizedPrompt == "" {
+ log.Debug().Msg("[ChatService] Plain-text resource reference resolver skipped empty prompt")
+ return assistantPlainTextResourceMatch{}, false
+ }
+
+ matches := make(map[string]assistantPlainTextResourceMatch)
+ scanned := 0
+ registered := 0
+ mentionedCount := 0
+ for _, resourceType := range assistantPlainTextResourceTypes {
+ for _, resource := range provider.GetByType(resourceType) {
+ scanned++
+ reg, ok := tools.CanonicalHandoffResourceRegistration(
+ provider,
+ resource.ID,
+ resource.Name,
+ string(unifiedresources.ContractResourceType(resource)),
+ plainTextResourceRegistrationNode(resource),
+ )
+ if !ok {
+ continue
+ }
+ registered++
+ matchedReference, mentioned := plainTextResourceMatchedReference(normalizedPrompt, plainTextResourceReferenceCandidates(resource, reg))
+ if !mentioned {
+ continue
+ }
+ mentionedCount++
+ key := plainTextResourceSelectionKey(reg, matchedReference)
+ match := assistantPlainTextResourceMatch{
+ registration: reg,
+ resourceType: string(unifiedresources.ContractResourceType(resource)),
+ matchedReference: matchedReference,
+ }
+ if existing, ok := matches[key]; !ok || plainTextResourceMatchPreferred(match, existing) {
+ matches[key] = match
+ }
+ }
+ }
+ matches = plainTextResourceMatchesForPromptTarget(matches, normalizedPrompt)
+ if len(matches) != 1 {
+ log.Debug().
+ Int("scanned", scanned).
+ Int("registered", registered).
+ Int("mentioned", mentionedCount).
+ Int("matches", len(matches)).
+ Msg("[ChatService] Plain-text resource reference was not resolved")
+ return assistantPlainTextResourceMatch{}, false
+ }
+ for _, match := range matches {
+ return match, true
+ }
+ return assistantPlainTextResourceMatch{}, false
+}
+
+func plainTextResourceMatchesForPromptTarget(matches map[string]assistantPlainTextResourceMatch, normalizedPrompt string) map[string]assistantPlainTextResourceMatch {
+ if len(matches) <= 1 {
+ return matches
+ }
+ preferredTypes := plainTextPromptPreferredResourceTypes(normalizedPrompt)
+ if len(preferredTypes) == 0 {
+ return matches
+ }
+ filtered := make(map[string]assistantPlainTextResourceMatch, len(matches))
+ for key, match := range matches {
+ if preferredTypes[match.resourceType] {
+ filtered[key] = match
+ }
+ }
+ if len(filtered) == 0 {
+ return matches
+ }
+ return filtered
+}
+
+func plainTextPromptPreferredResourceTypes(normalizedPrompt string) map[string]bool {
+ if assistantPromptContainsAny(normalizedPrompt, []string{
+ " storage ",
+ " datastore ",
+ " pool ",
+ " dataset ",
+ " disk ",
+ " volume ",
+ }) {
+ return map[string]bool{"storage": true}
+ }
+ if assistantPromptContainsAny(normalizedPrompt, []string{
+ " container ",
+ " containers ",
+ " lxc ",
+ " ct ",
+ " app ",
+ " service ",
+ }) {
+ return map[string]bool{
+ "system-container": true,
+ "app-container": true,
+ }
+ }
+ if assistantPromptContainsAny(normalizedPrompt, []string{
+ " vm ",
+ " vms ",
+ " virtual machine ",
+ " guest ",
+ }) {
+ return map[string]bool{"vm": true}
+ }
+ if assistantPromptContainsAny(normalizedPrompt, []string{
+ " host ",
+ " hosts ",
+ " node ",
+ " nodes ",
+ " server ",
+ " servers ",
+ " machine ",
+ " machines ",
+ }) {
+ return map[string]bool{"agent": true}
+ }
+ return nil
+}
+
+func attachPlainTextAssistantResourceContext(sessionID string, messages []Message, sessions *SessionStore, provider tools.UnifiedResourceProvider, readState unifiedresources.ReadState, prompt string) bool {
+ if sessions == nil {
+ return false
+ }
+ match, ok := resolvePlainTextAssistantResourceReference(prompt, provider)
+ if !ok {
+ if readStateProvider := plainTextUnifiedProviderFromReadState(readState); readStateProvider != nil {
+ match, ok = resolvePlainTextAssistantResourceReference(prompt, readStateProvider)
+ }
+ }
+ if !ok {
+ return false
+ }
+
+ resolvedCtx := sessions.GetResolvedContext(sessionID)
+ resolvedCtx.AddResolvedResource(match.registration)
+ resolved, found := resolvedCtx.GetResolvedResourceByAlias(match.registration.Name)
+ if !found || resolved == nil {
+ log.Debug().
+ Str("session_id", sessionID).
+ Str("resource_kind", match.registration.Kind).
+ Msg("[ChatService] Plain-text resource reference registration could not be re-read")
+ return false
+ }
+ resolvedCtx.MarkExplicitAccess(resolved.GetResourceID())
+ injectPlainTextResourceContextIntoLatestUserMessage(
+ messages,
+ buildPlainTextResourceContextDirective(match.resourceType),
+ rewritePlainTextResourceReferenceForModel(prompt, match.matchedReference),
+ )
+ log.Debug().
+ Str("session_id", sessionID).
+ Str("resource_id", resolved.GetResourceID()).
+ Str("resource_kind", match.registration.Kind).
+ Msg("[ChatService] Attached plain-text resource reference as current_resource")
+ return true
+}
+
+func plainTextUnifiedProviderFromReadState(readState unifiedresources.ReadState) tools.UnifiedResourceProvider {
+ if registry, ok := readState.(*unifiedresources.ResourceRegistry); ok && registry != nil {
+ return unifiedresources.NewUnifiedAIAdapter(registry)
+ }
+ if provider, ok := readState.(tools.UnifiedResourceProvider); ok {
+ return provider
+ }
+ return nil
+}
+
+func injectPlainTextResourceContextIntoLatestUserMessage(messages []Message, directive string, providerSafePrompt string) {
+ if len(messages) == 0 {
+ return
+ }
+ lastIdx := len(messages) - 1
+ if messages[lastIdx].Role != "user" {
+ return
+ }
+ directive = strings.TrimSpace(directive)
+ providerSafePrompt = strings.TrimSpace(providerSafePrompt)
+ if directive == "" && providerSafePrompt == "" {
+ return
+ }
+ parts := make([]string, 0, 2)
+ if directive != "" {
+ parts = append(parts, directive)
+ }
+ if providerSafePrompt != "" {
+ parts = append(parts, "Provider-safe user request:\n"+providerSafePrompt)
+ }
+ messages[lastIdx].Content = strings.Join(parts, "\n\n---\n")
+}
+
+func rewritePlainTextResourceReferenceForModel(prompt string, matchedReference string) string {
+ prompt = strings.TrimSpace(prompt)
+ if prompt == "" {
+ return "Use current_resource as the target for the user's requested live read."
+ }
+ matchedTokens := strings.Fields(normalizeAssistantPlainTextReference(matchedReference))
+ if len(matchedTokens) == 0 {
+ return "Use current_resource as the target for the user's requested live read."
+ }
+
+ tokens := plainTextPromptTokens(prompt)
+ for start := 0; start < len(tokens); start++ {
+ if start+len(matchedTokens) > len(tokens) {
+ break
+ }
+ matched := true
+ for offset, expected := range matchedTokens {
+ if tokens[start+offset].normalized != expected {
+ matched = false
+ break
+ }
+ }
+ if !matched {
+ continue
+ }
+ replaceStart := tokens[start].start
+ replaceEnd := tokens[start+len(matchedTokens)-1].end
+ return strings.TrimSpace(prompt[:replaceStart] + "current_resource" + prompt[replaceEnd:])
+ }
+
+ return "Use current_resource as the target for the user's requested live read."
+}
+
+type plainTextPromptToken struct {
+ normalized string
+ start int
+ end int
+}
+
+func plainTextPromptTokens(prompt string) []plainTextPromptToken {
+ var tokens []plainTextPromptToken
+ start := -1
+ var b strings.Builder
+ for idx, r := range prompt {
+ if unicode.IsLetter(r) || unicode.IsDigit(r) {
+ if start < 0 {
+ start = idx
+ b.Reset()
+ }
+ b.WriteRune(unicode.ToLower(r))
+ continue
+ }
+ if start >= 0 {
+ tokens = append(tokens, plainTextPromptToken{
+ normalized: b.String(),
+ start: start,
+ end: idx,
+ })
+ start = -1
+ b.Reset()
+ }
+ }
+ if start >= 0 {
+ tokens = append(tokens, plainTextPromptToken{
+ normalized: b.String(),
+ start: start,
+ end: len(prompt),
+ })
+ }
+ return tokens
+}
+
+func buildPlainTextResourceContextDirective(resourceType string) string {
+ resourceType = strings.TrimSpace(resourceType)
+ if resourceType == "" {
+ resourceType = "resource"
+ }
+ return strings.Join([]string{
+ "[Resource Context Handoff Instructions]",
+ "Source: Pulse resource reference resolution",
+ "Selected Resource: Pulse resolved one unambiguous user-referenced resource as the attached resource for this turn. Do not ask which server, service, container, VM, or resource the user means.",
+ "Provider-Safe Target Rewrite: If the user question below contains a redacted host, server, resource, VM, container, app, or storage phrase, treat that phrase as current_resource for this turn.",
+ "Tool Target Handle: When you need a read-only tool against the attached resource, use target_host=\"current_resource\" or resource_id=\"current_resource\". Do not copy 'redacted by policy' into any tool argument.",
+ "Resolved Resource Type: " + resourceType,
+ "Read Tool Boundary: Call read-only tools against current_resource only when the user explicitly asks you to investigate live runtime state, asks for fresh verification, or specifically requests a read attempt.",
+ "Data Boundary: User-authored resource labels may be redacted by policy. The current_resource handle is the authoritative target; do not reveal or reconstruct raw aliases, hostnames, provider IDs, paths, or secret-bearing metadata.",
+ "Action Boundary: Context is read-only and grants no approval or execution authority. Any action requires the governed approval/action flow.",
+ }, "\n")
+}
+
+func plainTextResourceRegistrationNode(resource unifiedresources.Resource) string {
+ if resource.Proxmox != nil {
+ return strings.TrimSpace(resource.Proxmox.NodeName)
+ }
+ return strings.TrimSpace(resource.ParentName)
+}
+
+func plainTextResourceReferenceCandidates(resource unifiedresources.Resource, reg tools.ResourceRegistration) []string {
+ candidates := []string{
+ reg.Name,
+ resource.Name,
+ unifiedresources.ResourceDisplayName(resource),
+ }
+ candidates = append(candidates, resource.Identity.Hostnames...)
+ switch strings.TrimSpace(reg.Kind) {
+ case "agent":
+ if resource.Proxmox != nil {
+ candidates = append(candidates, resource.Proxmox.NodeName)
+ }
+ if resource.Agent != nil {
+ candidates = append(candidates, resource.Agent.Hostname, resource.Agent.AgentID)
+ }
+ if resource.Docker != nil {
+ candidates = append(candidates, resource.Docker.Hostname, resource.Docker.HostSourceID, resource.Docker.AgentID)
+ }
+ if resource.TrueNAS != nil {
+ candidates = append(candidates, resource.TrueNAS.Hostname)
+ }
+ if resource.VMware != nil {
+ candidates = append(candidates, resource.VMware.RuntimeHostName, resource.VMware.HostUUID)
+ }
+ case "vm", "system-container":
+ if resource.Proxmox != nil {
+ candidates = append(candidates, resource.Proxmox.SourceID)
+ }
+ case "app-container":
+ if resource.Docker != nil {
+ candidates = append(candidates, resource.Docker.DisplayName, resource.Docker.CustomDisplayName)
+ }
+ }
+ return appendUniquePlainTextCandidates(nil, candidates...)
+}
+
+func plainTextResourceMatchedReference(normalizedPrompt string, candidates []string) (string, bool) {
+ for _, candidate := range candidates {
+ normalizedCandidate := normalizeAssistantPlainTextReference(candidate)
+ if normalizedCandidate == "" || plainTextReferenceIsUnsafe(normalizedCandidate) {
+ continue
+ }
+ if strings.Contains(" "+normalizedPrompt+" ", " "+normalizedCandidate+" ") {
+ return normalizedCandidate, true
+ }
+ }
+ return "", false
+}
+
+func plainTextResourceSelectionKey(reg tools.ResourceRegistration, matchedReference string) string {
+ kind := strings.TrimSpace(reg.Kind)
+ matchedReference = strings.TrimSpace(matchedReference)
+ if kind == "agent" && matchedReference != "" {
+ return kind + "\x00" + matchedReference
+ }
+ key := kind + "\x00" + strings.TrimSpace(reg.HostUID) + "\x00" + strings.TrimSpace(reg.ProviderUID)
+ if key == "\x00\x00" {
+ key = kind + "\x00" + strings.TrimSpace(reg.Name)
+ }
+ return key
+}
+
+func plainTextResourceMatchPreferred(candidate, existing assistantPlainTextResourceMatch) bool {
+ candidateExec := plainTextResourceRegistrationAllows(candidate.registration, "exec")
+ existingExec := plainTextResourceRegistrationAllows(existing.registration, "exec")
+ if candidateExec != existingExec {
+ return candidateExec
+ }
+ candidateNameMatches := normalizeAssistantPlainTextReference(candidate.registration.Name) == candidate.matchedReference
+ existingNameMatches := normalizeAssistantPlainTextReference(existing.registration.Name) == existing.matchedReference
+ if candidateNameMatches != existingNameMatches {
+ return candidateNameMatches
+ }
+ return false
+}
+
+func plainTextResourceRegistrationAllows(reg tools.ResourceRegistration, action string) bool {
+ action = strings.TrimSpace(action)
+ if action == "" {
+ return false
+ }
+ for _, executor := range reg.Executors {
+ for _, allowed := range executor.Actions {
+ if strings.EqualFold(strings.TrimSpace(allowed), action) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func plainTextReferenceIsUnsafe(normalizedCandidate string) bool {
+ if len(normalizedCandidate) < 3 {
+ return true
+ }
+ if _, ok := assistantPlainTextReferenceStopwords[normalizedCandidate]; ok {
+ return true
+ }
+ allDigits := true
+ for _, r := range normalizedCandidate {
+ if r == ' ' {
+ continue
+ }
+ if !unicode.IsDigit(r) {
+ allDigits = false
+ break
+ }
+ }
+ return allDigits
+}
+
+func normalizeAssistantPlainTextReference(value string) string {
+ value = strings.ToLower(strings.TrimSpace(value))
+ if value == "" {
+ return ""
+ }
+ var b strings.Builder
+ lastSpace := true
+ for _, r := range value {
+ if unicode.IsLetter(r) || unicode.IsDigit(r) {
+ b.WriteRune(r)
+ lastSpace = false
+ continue
+ }
+ if !lastSpace {
+ b.WriteByte(' ')
+ lastSpace = true
+ }
+ }
+ return strings.Join(strings.Fields(b.String()), " ")
+}
+
+func appendUniquePlainTextCandidates(base []string, values ...string) []string {
+ seen := make(map[string]struct{}, len(base)+len(values))
+ for _, value := range base {
+ key := strings.TrimSpace(value)
+ if key == "" {
+ continue
+ }
+ seen[strings.ToLower(key)] = struct{}{}
+ }
+ for _, value := range values {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ continue
+ }
+ key := strings.ToLower(value)
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
+ base = append(base, value)
+ }
+ return base
+}
diff --git a/internal/ai/chat/plain_text_resource_context_test.go b/internal/ai/chat/plain_text_resource_context_test.go
new file mode 100644
index 0000000000..2976201c97
--- /dev/null
+++ b/internal/ai/chat/plain_text_resource_context_test.go
@@ -0,0 +1,370 @@
+package chat
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func TestResolvePlainTextAssistantResourceReference_ReadOnlyCommand(t *testing.T) {
+ provider := plainTextResourceTestProvider(plainTextResourceTestAgent("delly"))
+
+ match, ok := resolvePlainTextAssistantResourceReference(
+ "On the delly host, run the read-only command `ls /dev | wc -l` and tell me the count.",
+ provider,
+ )
+ if !ok {
+ t.Fatal("expected unambiguous plain-text resource reference to resolve")
+ }
+ if match.registration.Kind != "agent" {
+ t.Fatalf("resolved kind = %q, want agent", match.registration.Kind)
+ }
+ if match.registration.Name != "delly" {
+ t.Fatalf("resolved name = %q, want delly", match.registration.Name)
+ }
+}
+
+func TestResolvePlainTextAssistantResourceReference_ProxmoxNodeName(t *testing.T) {
+ provider := plainTextResourceTestProvider(unifiedresources.Resource{
+ ID: "agent:pve-node-1",
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "Proxmox node 1",
+ Status: unifiedresources.StatusOnline,
+ Tags: []string{"sensitive"},
+ Proxmox: &unifiedresources.ProxmoxData{
+ NodeName: "delly",
+ },
+ })
+
+ match, ok := resolvePlainTextAssistantResourceReference(
+ "On the delly host, run the read-only command `ls /dev | wc -l` and tell me the count.",
+ provider,
+ )
+ if !ok {
+ t.Fatal("expected Proxmox node name to resolve as a plain-text resource reference")
+ }
+ if match.registration.Kind != "agent" {
+ t.Fatalf("resolved kind = %q, want agent", match.registration.Kind)
+ }
+}
+
+func TestResolvePlainTextAssistantResourceReference_CoalescesNodeAndAgentForSameHost(t *testing.T) {
+ proxmoxNode := unifiedresources.Resource{
+ ID: "agent:pve-node-1",
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "Proxmox node 1",
+ Status: unifiedresources.StatusOnline,
+ Tags: []string{"sensitive"},
+ Proxmox: &unifiedresources.ProxmoxData{
+ NodeName: "delly",
+ },
+ }
+ pulseAgent := plainTextResourceTestAgent("delly")
+ provider := plainTextResourceTestProvider(proxmoxNode, pulseAgent)
+
+ match, ok := resolvePlainTextAssistantResourceReference(
+ "On the delly host, run the read-only command `ls /dev | wc -l` and tell me the count.",
+ provider,
+ )
+ if !ok {
+ t.Fatal("expected matching Proxmox node and Pulse agent to coalesce")
+ }
+ if match.registration.Name != "delly" {
+ t.Fatalf("resolved name = %q, want command-capable agent delly", match.registration.Name)
+ }
+ if !plainTextResourceRegistrationAllows(match.registration, "exec") {
+ t.Fatalf("expected coalesced match to prefer exec-capable registration: %#v", match.registration)
+ }
+}
+
+func TestResolvePlainTextAssistantResourceReference_HostQualifierPrefersAgent(t *testing.T) {
+ provider := plainTextResourceTestProvider(
+ plainTextResourceTestAgent("delly"),
+ unifiedresources.Resource{
+ ID: "storage:local-zfs",
+ Type: unifiedresources.ResourceTypeStorage,
+ Name: "local-zfs",
+ Status: unifiedresources.StatusOnline,
+ ParentName: "delly",
+ Identity: unifiedresources.ResourceIdentity{
+ Hostnames: []string{"delly"},
+ },
+ Storage: &unifiedresources.StorageMeta{
+ Type: "zfspool",
+ Nodes: []string{"delly"},
+ },
+ Proxmox: &unifiedresources.ProxmoxData{
+ NodeName: "delly",
+ },
+ },
+ )
+
+ match, ok := resolvePlainTextAssistantResourceReference(
+ "On the delly host, run the read-only command `ls /dev | wc -l` and tell me the count.",
+ provider,
+ )
+ if !ok {
+ t.Fatal("expected host qualifier to prefer the agent over storage rows carrying the same node label")
+ }
+ if match.registration.Kind != "agent" {
+ t.Fatalf("resolved kind = %q, want agent", match.registration.Kind)
+ }
+}
+
+func TestResolvePlainTextAssistantResourceReference_AmbiguousReferencesFailClosed(t *testing.T) {
+ provider := plainTextResourceTestProvider(
+ plainTextResourceTestAgent("delly"),
+ plainTextResourceTestAgent("mini"),
+ )
+
+ _, ok := resolvePlainTextAssistantResourceReference(
+ "Compare delly and mini, then run a read-only command.",
+ provider,
+ )
+ if ok {
+ t.Fatal("expected ambiguous plain-text resource references to fail closed")
+ }
+}
+
+func TestServiceExecuteStream_AttachesPlainTextResourceReferenceAsCurrentResource(t *testing.T) {
+ tmpDir := t.TempDir()
+ store, err := NewSessionStore(tmpDir)
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ resource := plainTextResourceTestAgent("delly")
+ providerResources := plainTextResourceTestProvider(resource)
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{UnifiedResourceProvider: providerResources})
+
+ var capturedRequests [][]providers.Message
+ provider := &stubServiceProvider{
+ streamFn: func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ capturedMessages := append([]providers.Message(nil), req.Messages...)
+ capturedRequests = append(capturedRequests, capturedMessages)
+ callback(providers.StreamEvent{
+ Type: "content",
+ Data: providers.ContentEvent{Text: "I will check that."},
+ })
+ callback(providers.StreamEvent{
+ Type: "done",
+ Data: providers.DoneEvent{InputTokens: 1, OutputTokens: 1},
+ })
+ return nil
+ },
+ }
+
+ svc := &Service{
+ cfg: &config.AIConfig{ChatModel: "openrouter:deepseek/deepseek-chat"},
+ sessions: store,
+ executor: executor,
+ agenticLoop: NewAgenticLoop(provider, executor, "system"),
+ provider: provider,
+ unifiedResourceProvider: providerResources,
+ started: true,
+ }
+
+ req := ExecuteRequest{
+ SessionID: "sess-plain-text-resource",
+ Prompt: "On the delly host, run the read-only command `ls /dev | wc -l` and tell me the count.",
+ }
+ if err := svc.ExecuteStream(context.Background(), req, func(StreamEvent) {}); err != nil {
+ t.Fatalf("ExecuteStream failed: %v", err)
+ }
+
+ if len(capturedRequests) == 0 || len(capturedRequests[0]) == 0 {
+ t.Fatal("expected provider-bound messages to be captured")
+ }
+ capturedMessages := capturedRequests[0]
+ modelUserContent := capturedMessages[len(capturedMessages)-1].Content
+ for _, expected := range []string{
+ "[Resource Context Handoff Instructions]",
+ "Source: Pulse resource reference resolution",
+ "Selected Resource: Pulse resolved one unambiguous user-referenced resource as the attached resource for this turn.",
+ "target_host=\"current_resource\" or resource_id=\"current_resource\"",
+ "Provider-safe user request:",
+ "On the current_resource host, run the read-only command",
+ unifiedresources.ResourcePolicyRedactedLabel,
+ } {
+ if !strings.Contains(modelUserContent, expected) {
+ t.Fatalf("provider-bound message missing %q: %q", expected, modelUserContent)
+ }
+ }
+ if strings.Contains(modelUserContent, "delly") {
+ t.Fatalf("provider-bound message leaked raw resource alias: %q", modelUserContent)
+ }
+
+ resolved := store.GetResolvedContext("sess-plain-text-resource")
+ info, found := resolved.GetResolvedResourceByAlias("delly")
+ if !found {
+ t.Fatalf("expected resolved resource alias to be registered")
+ }
+ if !resolved.WasRecentlyAccessed(info.GetResourceID(), time.Minute) {
+ t.Fatalf("expected resolved resource to be marked as explicit current_resource access")
+ }
+}
+
+func TestAttachPlainTextAssistantResourceContext_FallsBackToReadStateProvider(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+ session, err := store.EnsureSession("sess-read-state-provider")
+ if err != nil {
+ t.Fatalf("failed to ensure session: %v", err)
+ }
+ messages := []Message{{
+ ID: "msg-1",
+ Role: "user",
+ Content: "On the delly host, run the read-only command `ls /dev | wc -l` and tell me the count.",
+ }}
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestSnapshot(models.StateSnapshot{
+ Hosts: []models.Host{{
+ ID: "host-delly",
+ Hostname: "delly",
+ Status: "online",
+ Platform: "linux",
+ CommandsEnabled: true,
+ Tags: []string{"sensitive"},
+ }},
+ })
+
+ ok := attachPlainTextAssistantResourceContext(session.ID, messages, store, nil, registry, messages[0].Content)
+ if !ok {
+ t.Fatal("expected ReadState provider fallback to attach resource context")
+ }
+ if !strings.Contains(messages[0].Content, "Source: Pulse resource reference resolution") {
+ t.Fatalf("expected resource context directive in user message, got %q", messages[0].Content)
+ }
+ resolved := store.GetResolvedContext(session.ID)
+ info, found := resolved.GetResolvedResourceByAlias("delly")
+ if !found {
+ t.Fatal("expected read-state resource to register by alias")
+ }
+ if !resolved.WasRecentlyAccessed(info.GetResourceID(), time.Minute) {
+ t.Fatalf("expected read-state resource to be explicit current-turn access")
+ }
+}
+
+func TestServiceSetReadStateEnablesPlainTextResourceReferenceFallback(t *testing.T) {
+ tmpDir := t.TempDir()
+ store, err := NewSessionStore(tmpDir)
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestSnapshot(models.StateSnapshot{
+ Hosts: []models.Host{{
+ ID: "host-delly",
+ Hostname: "delly",
+ Status: "online",
+ Platform: "linux",
+ CommandsEnabled: true,
+ Tags: []string{"sensitive"},
+ }},
+ })
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+
+ var capturedRequests [][]providers.Message
+ provider := &stubServiceProvider{
+ streamFn: func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ capturedMessages := append([]providers.Message(nil), req.Messages...)
+ capturedRequests = append(capturedRequests, capturedMessages)
+ callback(providers.StreamEvent{
+ Type: "content",
+ Data: providers.ContentEvent{Text: "I will check that."},
+ })
+ callback(providers.StreamEvent{
+ Type: "done",
+ Data: providers.DoneEvent{InputTokens: 1, OutputTokens: 1},
+ })
+ return nil
+ },
+ }
+
+ svc := &Service{
+ cfg: &config.AIConfig{ChatModel: "openrouter:deepseek/deepseek-chat"},
+ sessions: store,
+ executor: executor,
+ agenticLoop: NewAgenticLoop(provider, executor, "system"),
+ provider: provider,
+ started: true,
+ }
+ svc.SetReadState(registry)
+
+ req := ExecuteRequest{
+ SessionID: "sess-read-state-late",
+ Prompt: "On the delly host, run the read-only command `ls /dev | wc -l` and tell me the count.",
+ }
+ if err := svc.ExecuteStream(context.Background(), req, func(StreamEvent) {}); err != nil {
+ t.Fatalf("ExecuteStream failed: %v", err)
+ }
+
+ if len(capturedRequests) == 0 || len(capturedRequests[0]) == 0 {
+ t.Fatal("expected provider-bound messages to be captured")
+ }
+ modelUserContent := capturedRequests[0][len(capturedRequests[0])-1].Content
+ for _, expected := range []string{
+ "Source: Pulse resource reference resolution",
+ "target_host=\"current_resource\" or resource_id=\"current_resource\"",
+ } {
+ if !strings.Contains(modelUserContent, expected) {
+ t.Fatalf("provider-bound message missing %q: %q", expected, modelUserContent)
+ }
+ }
+ resolved := store.GetResolvedContext("sess-read-state-late")
+ info, found := resolved.GetResolvedResourceByAlias("delly")
+ if !found {
+ t.Fatal("expected late read-state resource to register by alias")
+ }
+ if !resolved.WasRecentlyAccessed(info.GetResourceID(), time.Minute) {
+ t.Fatalf("expected late read-state resource to be explicit current-turn access")
+ }
+}
+
+func plainTextResourceTestAgent(name string) unifiedresources.Resource {
+ return unifiedresources.Resource{
+ ID: "agent:" + name,
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: name,
+ Status: unifiedresources.StatusOnline,
+ Tags: []string{"sensitive"},
+ Identity: unifiedresources.ResourceIdentity{
+ Hostnames: []string{name},
+ },
+ Agent: &unifiedresources.AgentData{
+ AgentID: "agent-" + name,
+ Hostname: name,
+ CommandsEnabled: true,
+ },
+ Policy: &unifiedresources.ResourcePolicy{
+ Sensitivity: unifiedresources.ResourceSensitivitySensitive,
+ Routing: unifiedresources.ResourceRoutingPolicy{
+ Scope: unifiedresources.ResourceRoutingScopeCloudSummary,
+ Redact: []unifiedresources.ResourceRedactionHint{
+ unifiedresources.ResourceRedactionAlias,
+ unifiedresources.ResourceRedactionHostname,
+ },
+ },
+ },
+ }
+}
+
+func plainTextResourceTestProvider(resources ...unifiedresources.Resource) handoffUnifiedProvider {
+ byType := make(map[unifiedresources.ResourceType][]unifiedresources.Resource)
+ for _, resource := range resources {
+ byType[resource.Type] = append(byType[resource.Type], resource)
+ }
+ return handoffUnifiedProvider{
+ resources: byType,
+ }
+}
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 9aed9ce2d4..bb14422265 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -121,6 +121,7 @@ type Service struct {
started bool
autonomousMode bool
contextPrefetcher *ContextPrefetcher
+ discoveryProvider tools.DiscoveryProvider
budgetChecker func() error // Optional mid-run budget enforcement
orgID string
controlLevelResolver func(*config.AIConfig) string
@@ -650,10 +651,17 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
if overrideModel != "" {
selectedModel = overrideModel
}
+ hasModelHandoffContext := handoffContext != "" ||
+ len(handoffResources) > 0 ||
+ len(handoffActions) > 0 ||
+ handoffFindingID != "" ||
+ !handoffMetadataEmpty(handoffMetadata)
+ assistantToolScope := assistantToolScopeForPrompt(req.Prompt, hasModelHandoffContext)
// Proactively gather context for mentioned resources
s.mu.RLock()
prefetcher := s.contextPrefetcher
+ readState := s.readState
s.mu.RUnlock()
log.Info().
@@ -715,11 +723,13 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
}
}
}
-
- if !mentionsFound {
- s.injectRecentSessionContext(session.ID, messages, sessions)
+ }
+ if assistantToolScope == assistantTurnToolScopeFull {
+ if attachPlainTextAssistantResourceContext(session.ID, messages, sessions, unifiedResourceProvider, readState, req.Prompt) {
+ mentionsFound = true
}
- } else {
+ }
+ if !mentionsFound {
s.injectRecentSessionContext(session.ID, messages, sessions)
}
@@ -742,13 +752,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
}
// Run agentic loop
- hasModelHandoffContext := handoffContext != "" ||
- len(handoffResources) > 0 ||
- len(handoffActions) > 0 ||
- handoffFindingID != "" ||
- !handoffMetadataEmpty(handoffMetadata)
modelBoundaryAllowedInventoryContext := ""
- assistantToolScope := assistantToolScopeForPrompt(req.Prompt, hasModelHandoffContext)
if assistantToolScope == assistantTurnToolScopeQueryOnly {
emitWorkflowState(streamCallback, "context", "Reading current Pulse inventory with pulse_query.", "", "pulse_query")
if assistantPromptRequestsDeterministicInventoryCount(normalizeAssistantToolRoutingPrompt(req.Prompt)) {
@@ -3649,6 +3653,17 @@ func (s *Service) SetUnifiedResourceProvider(provider tools.UnifiedResourceProvi
}
}
+func (s *Service) SetReadState(readState unifiedresources.ReadState) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.readState = readState
+ if readState != nil && s.discoveryProvider != nil {
+ s.contextPrefetcher = NewContextPrefetcher(readState, s.discoveryProvider)
+ } else {
+ s.contextPrefetcher = nil
+ }
+}
+
func (s *Service) SetAppContainerActionProvider(provider MCPAppContainerActionProvider) {
s.mu.Lock()
defer s.mu.Unlock()
@@ -3668,6 +3683,7 @@ func (s *Service) SetAppContainerReadProvider(provider MCPAppContainerReadProvid
func (s *Service) SetDiscoveryProvider(provider MCPDiscoveryProvider) {
s.mu.Lock()
defer s.mu.Unlock()
+ s.discoveryProvider = provider
if s.executor != nil {
s.executor.SetDiscoveryProvider(provider)
}
@@ -3854,7 +3870,7 @@ func (s *Service) buildSystemPromptWithToolGovernance(toolGovernance string) str
- target_host specifies where commands run (host name, container name, or VM name)
- Commands execute inside the target: target_host="homepage-docker" runs inside that container
- For Docker containers inside system containers: target the container, then use docker commands
-- The placeholder current_resource is valid only when this turn includes a Pulse resource-context handoff that explicitly says an attached resource is selected. If no attached resource context is present, do not use target_host="current_resource" or resource_id="current_resource"; ask which host, VM, container, app, or storage resource the user means, or use read-only query/search tools to identify an explicit target first.
+- The placeholder current_resource is valid only when this turn includes Pulse resource context that explicitly says an attached resource is selected, either from a resource-context handoff or from Pulse backend resource-reference resolution. If no attached resource context is present, do not use target_host="current_resource" or resource_id="current_resource"; ask which host, VM, container, app, or storage resource the user means, or use read-only query/search tools to identify an explicit target first.
## DOCKER BIND MOUNTS
- Container files are often mapped to host paths via bind mounts
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
index 5052cbf615..4e017aae81 100644
--- a/internal/ai/chat/service_tooling_test.go
+++ b/internal/ai/chat/service_tooling_test.go
@@ -320,7 +320,8 @@ func TestBuildSystemPrompt_CurrentResourceRequiresResourceHandoff(t *testing.T)
prompt := svc.buildSystemPrompt()
for _, expected := range []string{
- "The placeholder current_resource is valid only when this turn includes a Pulse resource-context handoff",
+ "The placeholder current_resource is valid only when this turn includes Pulse resource context",
+ "either from a resource-context handoff or from Pulse backend resource-reference resolution",
"If no attached resource context is present, do not use target_host=\"current_resource\" or resource_id=\"current_resource\"",
"Missing target information is not a safe default.",
"In autonomous mode, ask for the missing target in normal assistant text instead of attempting a tool call with current_resource",
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index 3a9c67558a..2841cca277 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -86,6 +86,10 @@ type aiServiceRuntimeConfigReader interface {
GetConfig() *config.AIConfig
}
+type aiServiceReadStateUpdater interface {
+ SetReadState(unifiedresources.ReadState)
+}
+
func aiChatRuntimeConfigDigest(cfg *config.AIConfig) [sha256.Size]byte {
payload, err := json.Marshal(cfg)
if err != nil {
@@ -326,8 +330,25 @@ func (h *AIHandler) SetReadState(rs unifiedresources.ReadState) {
return
}
h.stateMu.Lock()
- defer h.stateMu.Unlock()
h.readState = rs
+ h.stateMu.Unlock()
+
+ var services []AIService
+ h.servicesMu.RLock()
+ if h.defaultService != nil {
+ services = append(services, h.defaultService)
+ }
+ for _, svc := range h.services {
+ if svc != nil {
+ services = append(services, svc)
+ }
+ }
+ h.servicesMu.RUnlock()
+ for _, svc := range services {
+ if updater, ok := svc.(aiServiceReadStateUpdater); ok {
+ updater.SetReadState(rs)
+ }
+ }
}
// SetRecoveryManager stores a recovery manager for injection into newly created chat services.
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index dcaa7d6c11..ff5f0ae29c 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -37,6 +37,15 @@ func (m *syncingMockAIService) GetConfig() *config.AIConfig {
return m.cfg
}
+type readStateCapturingMockAIService struct {
+ MockAIService
+ updates []unifiedresources.ReadState
+}
+
+func (m *readStateCapturingMockAIService) SetReadState(rs unifiedresources.ReadState) {
+ m.updates = append(m.updates, rs)
+}
+
func (m *MockAIService) Start(ctx context.Context) error {
args := m.Called(ctx)
return args.Error(0)
@@ -2328,6 +2337,28 @@ func TestGetService_MultiTenantUsesTenantReadState(t *testing.T) {
mockSvc.AssertExpectations(t)
}
+func TestSetReadStatePropagatesToExistingServices(t *testing.T) {
+ h := NewAIHandler(nil, nil, nil)
+ defaultSvc := &readStateCapturingMockAIService{}
+ tenantSvc := &readStateCapturingMockAIService{}
+ h.defaultService = defaultSvc
+ h.services["acme"] = tenantSvc
+
+ readState := unifiedresources.NewRegistry(nil)
+ h.SetReadState(readState)
+
+ if len(defaultSvc.updates) != 1 || defaultSvc.updates[0] != readState {
+ t.Fatalf("default service read-state updates = %#v, want one propagated read state", defaultSvc.updates)
+ }
+ if len(tenantSvc.updates) != 1 || tenantSvc.updates[0] != readState {
+ t.Fatalf("tenant service read-state updates = %#v, want one propagated read state", tenantSvc.updates)
+ }
+ _, _, _, _, storedReadState, _ := h.stateRefs()
+ if storedReadState != readState {
+ t.Fatalf("handler stored read state = %#v, want %#v", storedReadState, readState)
+ }
+}
+
func TestGetService_HostedTenantDoesNotAutoBootstrapQuickstartService(t *testing.T) {
oldNewService := newChatService
defer func() { newChatService = oldNewService }()