Add support-agent example: mock customer-support agent
Demonstrates two harness surfaces the previous examples skipped: - SkillProvider: KB articles in examples/support-agent/kb/ are exposed via runtime.SkillProvider. The runtime auto-registers load_skill and inlines a compact article index into the static (cacheable) system prompt; full bodies load on demand. - PermissionChecker: tickets_update and escalate_to_human are gated on a 'supervisor' flag. FilterToolDefs hides the gated tools from the LLM tool list in non-supervisor mode so it doesn't waste turns inventing calls that would just be denied. Five concrete tools (kb_search, tickets_get, tickets_create, tickets_update, escalate_to_human) plus the auto-registered load_skill. Five seed KB articles cover refund policy, escalation matrix, account recovery, password reset, and API rate limits — chosen to exercise the common support patterns each tool involves. In-memory ticket store (examples/support-agent/store.go) seeded with four tickets in different states. Webhook delivery for escalations is optional via SUPPORT_AGENT_WEBHOOK; when unset the tool prints the escalation banner to stdout, so the demo runs with only ANTHROPIC_API_KEY set. Tests (support_test.go) cover store CRUD, defensive copying, the permission checker's read/write split, and KB indexing/search — all offline, no API needed.
This commit is contained in:
1 parent
152f653dd7
commit
8ed38d7b66
12 files changed
+1368
-2
No files matched your search
+10
-2
@@ -1,7 +1,9 @@
|
||||
# Documentation: only root README.md and developer.md are tracked
|
||||
# Documentation: only root README.md, developer.md, and example KB packs are tracked
|
||||
*.md
|
||||
!/README.md
|
||||
!/developer.md
|
||||
!/examples/*/kb/
|
||||
!/examples/*/kb/*.md
|
||||
|
||||
# Other prose/document formats
|
||||
*.txt
|
||||
@@ -16,9 +18,15 @@
|
||||
*.out
|
||||
*.prof
|
||||
*.bench
|
||||
# Compiled example binaries (Go puts the binary at examples/<name>/<name>)
|
||||
# Compiled example binaries. `go build ./examples/<name>/` puts the binary
|
||||
# in the current dir — could be the example dir or the repo root depending
|
||||
# on where you invoked it. Cover both.
|
||||
/examples/*/[a-z]*-agent
|
||||
/examples/minimal/minimal
|
||||
/data-agent
|
||||
/lta-agent
|
||||
/minimal
|
||||
/support-agent
|
||||
|
||||
# Editor / OS
|
||||
.DS_Store
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# Account Recovery
|
||||
|
||||
When a customer reports they've lost access or their account was
|
||||
compromised, follow this script. Do **not** improvise: every step here
|
||||
exists because of a past incident.
|
||||
|
||||
## Step 1 — Triage in one question
|
||||
|
||||
Ask: "Are you locked out of your account, or are you still logged in
|
||||
but seeing activity you don't recognise?"
|
||||
|
||||
- **Locked out** → password-reset flow (see `password-reset` article).
|
||||
- **Unfamiliar activity** → suspected compromise (continue below).
|
||||
|
||||
## Step 2 — Suspected compromise
|
||||
|
||||
1. **Do not ask for the password**, ever.
|
||||
2. Tell the customer to immediately:
|
||||
- Sign out of every active session from Settings → Security → Sign
|
||||
out everywhere.
|
||||
- Rotate their password via the standard reset flow.
|
||||
- Rotate any API keys via Dashboard → API → Keys → Rotate.
|
||||
- Enable 2FA if not already on.
|
||||
3. File a ticket with subject `Possible account compromise` and
|
||||
priority `urgent`.
|
||||
4. Add an internal note listing what the customer reported (IPs,
|
||||
timestamps, what they noticed).
|
||||
5. **Escalate to Security** via `escalate_to_human` — do not attempt
|
||||
to investigate access logs yourself.
|
||||
|
||||
## Step 3 — What we tell them
|
||||
|
||||
> "I've filed an urgent ticket and our security team will reach out
|
||||
> within 30 minutes. While you wait, please rotate your credentials
|
||||
> using the steps above. If you see any further suspicious activity,
|
||||
> reply to this thread with timestamps and we'll add them to the
|
||||
> investigation."
|
||||
|
||||
Never confirm or deny what the security team will find — that's their
|
||||
call to make.
|
||||
@@ -0,0 +1,46 @@
|
||||
# API Rate Limits
|
||||
|
||||
Default limits for Acme API clients. When a customer reports 429s or
|
||||
unexpected throttling, check their plan tier first via the dashboard
|
||||
before escalating.
|
||||
|
||||
## Default limits per plan
|
||||
|
||||
| Plan | Requests / minute | Requests / day | Concurrent streams |
|
||||
|------------|-------------------|----------------|--------------------|
|
||||
| Free | 20 | 1,000 | 1 |
|
||||
| Starter | 120 | 50,000 | 5 |
|
||||
| Growth | 600 | 500,000 | 25 |
|
||||
| Enterprise | Custom (≥ 1,200) | Custom | Custom |
|
||||
|
||||
## How to read the headers
|
||||
|
||||
Every response includes:
|
||||
|
||||
- `X-RateLimit-Limit` — the per-minute cap
|
||||
- `X-RateLimit-Remaining` — calls left in the current window
|
||||
- `X-RateLimit-Reset` — Unix epoch (seconds) when the window rolls over
|
||||
- `Retry-After` — present on 429 responses; seconds to wait
|
||||
|
||||
Tell customers to back off using `Retry-After`, not arbitrary delays.
|
||||
|
||||
## When 429s aren't actually rate limits
|
||||
|
||||
A surprising fraction of "rate limit" tickets are something else. Rule
|
||||
these out before escalating:
|
||||
|
||||
1. **Auth failure cascading**: 401s in a tight retry loop look like
|
||||
429s when the customer reads aggregate request graphs. Confirm by
|
||||
checking response codes individually.
|
||||
2. **Same key on multiple processes**: the limit is per-key, not
|
||||
per-process. A customer running 4 workers on a Starter plan will
|
||||
share 120 RPM across all of them.
|
||||
3. **Quota vs rate**: hitting the daily quota returns 429 too. Check
|
||||
`X-RateLimit-Limit` — if it's the daily number, they need a higher
|
||||
plan, not a rate-limit increase.
|
||||
|
||||
## Requesting an increase
|
||||
|
||||
- Free / Starter / Growth: increases are not granted; suggest upgrading.
|
||||
- Enterprise: file a ticket with priority `high`, subject
|
||||
`Rate-limit increase request`, and CC the account's CSM.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Escalation Matrix
|
||||
|
||||
Use `escalate_to_human` (supervisor mode only) when one of the
|
||||
following thresholds is hit. The agent should still file a ticket
|
||||
first so the human has context on landing.
|
||||
|
||||
| Trigger | Priority | Route to |
|
||||
|----------------------------------------------------------|----------|-----------------|
|
||||
| Account compromise / suspicious logins | urgent | Security |
|
||||
| Chargeback threat or legal language ("lawyer", "sue") | urgent | Billing + Legal |
|
||||
| Reported data loss or accidental deletion | urgent | On-call SRE |
|
||||
| Service downtime claim with customer impact > 1 hour | high | On-call SRE |
|
||||
| Refund request > $100 outside the discretionary window | high | Billing |
|
||||
| Customer explicitly asks to speak to a manager / human | high | Senior support |
|
||||
| Repeated (3rd+) ticket for the same root cause | medium | Tier 2 |
|
||||
|
||||
## Escalation note conventions
|
||||
|
||||
When escalating, add an internal note that includes:
|
||||
|
||||
1. **One-sentence summary** of what the customer wants.
|
||||
2. **What you've already tried / verified** (e.g. "confirmed propagation
|
||||
delay via /status endpoint at 14:32 UTC").
|
||||
3. **The KB article(s)** you cited.
|
||||
4. **Anything the customer was promised** ("told them we'd respond
|
||||
within 30 min").
|
||||
|
||||
Format: `ESCALATION: <one-line summary> | did: <…> | promised: <…>`
|
||||
@@ -0,0 +1,28 @@
|
||||
# Password Reset
|
||||
|
||||
For the standard "I can't log in / forgot my password" case. If the
|
||||
customer reports unfamiliar activity in addition to being locked out,
|
||||
treat it as a compromise — see `account-recovery`.
|
||||
|
||||
## The standard flow
|
||||
|
||||
1. Direct the customer to https://app.acme.example/reset and ask them
|
||||
to enter the email address they signed up with.
|
||||
2. The reset email arrives within 2 minutes from `[email protected]`.
|
||||
3. The link is single-use and expires in 1 hour.
|
||||
|
||||
## Common failure modes
|
||||
|
||||
| Symptom | Likely cause | Action |
|
||||
|---------------------------------------------|---------------------------|---------------------------------------------------------------------|
|
||||
| No email after 5 minutes | Corporate spam filter | Have customer check spam, then ask IT to allowlist `acme.example`. |
|
||||
| "Email not found" error | Wrong address or typo | Confirm the spelling; check whether SSO is configured for them. |
|
||||
| Link expired | > 1 hour since send | Issue a fresh reset; verify the customer is acting on the new one. |
|
||||
| SSO error after reset | SSO required by org | Reset doesn't apply — customer must log in via their SSO provider. |
|
||||
| 2FA prompt after reset, no device available | Lost authenticator | File a ticket; only Security can reset 2FA. **Do not** disable it. |
|
||||
|
||||
## Don'ts
|
||||
|
||||
- Don't email a temporary password.
|
||||
- Don't disable 2FA on the customer's behalf — always escalate.
|
||||
- Don't ask the customer for any portion of their password "to verify".
|
||||
@@ -0,0 +1,40 @@
|
||||
# Refund Policy
|
||||
|
||||
Acme issues refunds under the following conditions. The agent should
|
||||
quote the matching clause verbatim when discussing a refund with a
|
||||
customer.
|
||||
|
||||
## Subscription charges
|
||||
|
||||
- **Within 14 days of renewal**: full refund, no questions asked.
|
||||
- **Day 15–30 of renewal**: prorated refund for unused portion of the
|
||||
billing period.
|
||||
- **After day 30**: no refund. Customer may downgrade to take effect at
|
||||
next renewal.
|
||||
|
||||
## Usage / overage charges
|
||||
|
||||
- Refunds are **discretionary** and capped at **$100 per billing
|
||||
period** when one of the following applies:
|
||||
1. The customer did not receive the 80% / 100% rate-limit warning
|
||||
emails (verify via `tickets_get` notes or the email-events
|
||||
dashboard).
|
||||
2. A documented platform incident on our side caused the spike (cross-
|
||||
reference status.acme.example).
|
||||
3. The overage is the customer's first ever and the amount is < $50.
|
||||
- Overages > $100 require supervisor approval. File a ticket with
|
||||
priority `high` and escalate.
|
||||
|
||||
## One-time purchases (add-ons, professional services)
|
||||
|
||||
- Refunds are not available once the engagement begins or the add-on is
|
||||
consumed.
|
||||
- Unused engagements may be transferred once to a different team within
|
||||
the same account.
|
||||
|
||||
## Disputes
|
||||
|
||||
- If the customer threatens a chargeback or mentions their bank, do
|
||||
**not** discuss refund eligibility further. File a ticket with
|
||||
priority `urgent`, status `escalated`, and add an internal note
|
||||
flagging "billing dispute — chargeback risk". Hand off to billing.
|
||||
@@ -0,0 +1,185 @@
|
||||
// Mock customer-support agent — third example demonstrating two harness
|
||||
// surfaces the previous agents skip:
|
||||
//
|
||||
// - SkillProvider: the knowledge base is exposed as harness "skills".
|
||||
// The runtime auto-registers a load_skill tool and the static system
|
||||
// prompt advertises the available articles by slug. The full body
|
||||
// loads on demand.
|
||||
//
|
||||
// - PermissionChecker: write-side tools (tickets_update, escalate_to_human)
|
||||
// are gated on a "supervisor mode" flag. By default the agent can
|
||||
// read tickets and the KB but cannot mutate state — flip
|
||||
// SUPPORT_AGENT_SUPERVISOR=1 (or pass --supervisor) to unlock.
|
||||
//
|
||||
// Backend is fully in-memory: a few seed tickets are pre-populated. Run:
|
||||
//
|
||||
// export ANTHROPIC_API_KEY=sk-ant-...
|
||||
// go run ./examples/support-agent
|
||||
// # or, to unlock write tools:
|
||||
// SUPPORT_AGENT_SUPERVISOR=1 go run ./examples/support-agent
|
||||
//
|
||||
// Try asking:
|
||||
// - "What's our refund policy for usage-based charges?"
|
||||
// - "Look up ticket T-1002 — what's it about?"
|
||||
// - "A customer's account was hacked. File a ticket and walk me through next steps."
|
||||
// - "Mark ticket T-1001 as resolved." (supervisor only)
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/sausheong/harness/providers/anthropic"
|
||||
"github.com/sausheong/harness/runtime"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
func main() {
|
||||
supervisorFlag := flag.Bool("supervisor", false,
|
||||
"unlock write tools (tickets_update, escalate_to_human). "+
|
||||
"Equivalent to SUPPORT_AGENT_SUPERVISOR=1.")
|
||||
flag.Parse()
|
||||
|
||||
apiKey := os.Getenv("ANTHROPIC_API_KEY")
|
||||
if apiKey == "" {
|
||||
fmt.Fprintln(os.Stderr, "ANTHROPIC_API_KEY required")
|
||||
os.Exit(1)
|
||||
}
|
||||
supervisor := *supervisorFlag || os.Getenv("SUPPORT_AGENT_SUPERVISOR") == "1"
|
||||
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr,
|
||||
&slog.HandlerOptions{Level: slog.LevelWarn})))
|
||||
|
||||
// Single shared store: seeded with a handful of in-flight tickets so
|
||||
// the demo is interactive on first launch.
|
||||
store := NewTicketStore()
|
||||
store.Seed()
|
||||
|
||||
// Five concrete tools. The runtime auto-registers a sixth (load_skill)
|
||||
// because we pass deps.Skills below.
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(&KBSearchTool{KB: NewKBSkills()})
|
||||
reg.Register(&TicketGetTool{Store: store})
|
||||
reg.Register(&TicketCreateTool{Store: store})
|
||||
reg.Register(&TicketUpdateTool{Store: store})
|
||||
reg.Register(&EscalateTool{Webhook: os.Getenv("SUPPORT_AGENT_WEBHOOK")})
|
||||
|
||||
sess := session.NewSession("support-agent", "main")
|
||||
prov := anthropic.NewAnthropicProvider(apiKey, "")
|
||||
|
||||
rt, err := runtime.BuildRuntime(
|
||||
runtime.RuntimeDeps{
|
||||
AgentLoop: runtime.LoopConfig{
|
||||
MaxToolConcurrency: 3,
|
||||
MaxAgentDepth: 1,
|
||||
},
|
||||
// SkillProvider: contributes a KB index to the static system
|
||||
// prompt and backs the auto-registered load_skill tool.
|
||||
Skills: NewKBSkills(),
|
||||
// PermissionChecker: gates the two write-side tools on
|
||||
// supervisor mode. nil-safe (would default to allow-all),
|
||||
// but we want the gating behaviour even in default mode.
|
||||
Permission: NewSupportChecker(supervisor),
|
||||
},
|
||||
runtime.RuntimeInputs{
|
||||
Provider: prov,
|
||||
Tools: reg,
|
||||
Session: sess,
|
||||
},
|
||||
runtime.AgentSpec{
|
||||
ID: "support",
|
||||
Name: "Acme Support",
|
||||
Model: "anthropic/claude-haiku-4-5-20251001",
|
||||
SystemPrompt: `You are a customer support agent for Acme, a SaaS company. ` +
|
||||
`Be empathetic, concise, and accurate.
|
||||
|
||||
Workflow:
|
||||
1. When the customer describes their issue, FIRST use kb_search to find
|
||||
relevant policy articles, then load_skill to read the full body of any
|
||||
article you'll cite. Do not invent policy from memory — quote the KB.
|
||||
2. If the customer references an existing ticket, call tickets_get to
|
||||
pull its current state before responding.
|
||||
3. If the issue is new and warrants tracking (refund request, account
|
||||
compromise, billing dispute, downtime claim), call tickets_create.
|
||||
4. Status mutations (mark resolved, change priority) and escalation to
|
||||
a human go through tickets_update / escalate_to_human. These tools
|
||||
are restricted in non-supervisor mode — if you receive a permission
|
||||
denial, tell the customer their request will be handed to a senior
|
||||
agent and stop.
|
||||
|
||||
Tone:
|
||||
- Acknowledge the customer's situation in one sentence before quoting policy.
|
||||
- Cite KB article slugs in brackets, e.g. "[refund-policy]".
|
||||
- Never promise a specific resolution timeline you can't verify from
|
||||
a ticket or KB article.`,
|
||||
MaxTurns: 12,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "build runtime:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
mode := "agent mode"
|
||||
if supervisor {
|
||||
mode = "supervisor mode (write tools unlocked)"
|
||||
}
|
||||
fmt.Printf("Acme Support — %s\n", mode)
|
||||
fmt.Println("Type a customer message; blank line to exit.")
|
||||
fmt.Println("Examples:")
|
||||
fmt.Println(" • What's your refund policy for usage charges?")
|
||||
fmt.Println(" • Look up ticket T-1002.")
|
||||
fmt.Println(" • My account was just compromised — what do I do?")
|
||||
if !supervisor {
|
||||
fmt.Println(" (Re-run with --supervisor to test write tools.)")
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
in := bufio.NewScanner(os.Stdin)
|
||||
for {
|
||||
fmt.Print("> ")
|
||||
if !in.Scan() || in.Text() == "" {
|
||||
return
|
||||
}
|
||||
runOne(rt, in.Text())
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
// runOne drains one Run, formatting events for terminal display.
|
||||
func runOne(rt *runtime.Runtime, prompt string) {
|
||||
events, err := rt.Run(context.Background(), prompt, nil)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "\nrun error:", err)
|
||||
return
|
||||
}
|
||||
for ev := range events {
|
||||
switch ev.Type {
|
||||
case runtime.EventTextDelta:
|
||||
fmt.Print(ev.Text)
|
||||
case runtime.EventToolCallStart:
|
||||
if ev.ToolCall != nil {
|
||||
fmt.Printf("\n [%s] ", ev.ToolCall.Name)
|
||||
}
|
||||
case runtime.EventToolResult:
|
||||
if ev.Result != nil && ev.Result.Error != "" {
|
||||
fmt.Printf("✗ %s", ev.Result.Error)
|
||||
} else {
|
||||
fmt.Print("✓")
|
||||
}
|
||||
case runtime.EventError:
|
||||
fmt.Fprintln(os.Stderr, "\nerror:", ev.Error)
|
||||
case runtime.EventDone:
|
||||
fmt.Println()
|
||||
if ev.Usage != nil {
|
||||
fmt.Fprintf(os.Stderr, "[%d in / %d out tokens]\n",
|
||||
ev.Usage.InputTokens, ev.Usage.OutputTokens)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// SupportChecker implements tool.PermissionChecker with one rule: the
|
||||
// two write-side tools (tickets_update, escalate_to_human) are visible
|
||||
// and callable only in supervisor mode. Read tools and the auto-
|
||||
// registered load_skill are always allowed.
|
||||
//
|
||||
// FilterToolDefs runs at tool-list-assembly time, so in non-supervisor
|
||||
// mode the LLM never sees the gated tools and won't waste a turn
|
||||
// inventing calls that would just be denied.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// SupportChecker enforces the read/write split.
|
||||
type SupportChecker struct {
|
||||
supervisor bool
|
||||
}
|
||||
|
||||
// NewSupportChecker constructs the checker. supervisor=true unlocks
|
||||
// tickets_update and escalate_to_human; supervisor=false hides them.
|
||||
func NewSupportChecker(supervisor bool) *SupportChecker {
|
||||
return &SupportChecker{supervisor: supervisor}
|
||||
}
|
||||
|
||||
// gatedTools is the set restricted to supervisor mode. Listed
|
||||
// explicitly (rather than "anything matching `*_update`") so adding a
|
||||
// new write tool is an obvious diff: the author has to decide whether
|
||||
// to add it here.
|
||||
var gatedTools = map[string]bool{
|
||||
"tickets_update": true,
|
||||
"escalate_to_human": true,
|
||||
}
|
||||
|
||||
// Check is consulted before every tool invocation.
|
||||
func (c *SupportChecker) Check(_ context.Context, _agentID, toolName string, _ json.RawMessage) tool.Decision {
|
||||
if !gatedTools[toolName] {
|
||||
return tool.Decision{Behavior: tool.DecisionAllow}
|
||||
}
|
||||
if c.supervisor {
|
||||
return tool.Decision{Behavior: tool.DecisionAllow}
|
||||
}
|
||||
return tool.Decision{
|
||||
Behavior: tool.DecisionDeny,
|
||||
Reason: fmt.Sprintf("%q is a write tool and requires supervisor mode "+
|
||||
"(re-run with --supervisor or SUPPORT_AGENT_SUPERVISOR=1)", toolName),
|
||||
}
|
||||
}
|
||||
|
||||
// FilterToolDefs hides gated tools from the LLM's tool list when not in
|
||||
// supervisor mode. Mirrors Check's policy so visibility and
|
||||
// executability never disagree.
|
||||
func (c *SupportChecker) FilterToolDefs(toolDefs []llm.ToolDef, _agentID string) []llm.ToolDef {
|
||||
if c.supervisor {
|
||||
return toolDefs
|
||||
}
|
||||
out := make([]llm.ToolDef, 0, len(toolDefs))
|
||||
for _, td := range toolDefs {
|
||||
if !gatedTools[td.Name] {
|
||||
out = append(out, td)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// KBSkills implements runtime.SkillProvider on top of the embedded
|
||||
// markdown KB articles in ./kb/. The runtime calls FormatIndex once at
|
||||
// BuildRuntime time and inlines the result into the static (cacheable)
|
||||
// system prompt; full bodies load on demand via the auto-registered
|
||||
// load_skill tool, keyed by the slug (filename without extension).
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// kbFS is the bundled set of KB articles. Embedded so the example runs
|
||||
// from anywhere — no need to chdir to the example directory.
|
||||
//
|
||||
//go:embed kb/*.md
|
||||
var kbFS embed.FS
|
||||
|
||||
// KBSkills is a SkillProvider backed by kbFS. Articles are loaded once
|
||||
// at construction; a real consumer would re-parse on a watcher signal.
|
||||
type KBSkills struct {
|
||||
bySlug map[string]kbArticle
|
||||
slugs []string // sorted, for stable index ordering
|
||||
}
|
||||
|
||||
type kbArticle struct {
|
||||
slug string
|
||||
summary string // first non-blank, non-heading line of the body
|
||||
body string
|
||||
}
|
||||
|
||||
// NewKBSkills loads every kb/*.md, parses out a one-line summary, and
|
||||
// returns a ready-to-use SkillProvider. Panics on a malformed embed
|
||||
// (build-time failure, not a runtime concern).
|
||||
func NewKBSkills() *KBSkills {
|
||||
entries, err := fs.ReadDir(kbFS, "kb")
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("kb embed: %v", err))
|
||||
}
|
||||
k := &KBSkills{bySlug: make(map[string]kbArticle, len(entries))}
|
||||
for _, e := range entries {
|
||||
if e.IsDir() || !strings.HasSuffix(e.Name(), ".md") {
|
||||
continue
|
||||
}
|
||||
raw, err := fs.ReadFile(kbFS, "kb/"+e.Name())
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("read kb/%s: %v", e.Name(), err))
|
||||
}
|
||||
slug := strings.TrimSuffix(e.Name(), ".md")
|
||||
body := string(raw)
|
||||
k.bySlug[slug] = kbArticle{
|
||||
slug: slug,
|
||||
summary: extractSummary(body),
|
||||
body: body,
|
||||
}
|
||||
k.slugs = append(k.slugs, slug)
|
||||
}
|
||||
sort.Strings(k.slugs)
|
||||
return k
|
||||
}
|
||||
|
||||
// FormatIndex returns the cacheable index of articles. Kept compact —
|
||||
// the index goes into every cached prompt, so we summarise rather than
|
||||
// inline bodies.
|
||||
func (k *KBSkills) FormatIndex() string {
|
||||
var b strings.Builder
|
||||
b.WriteString("## Knowledge Base\n\n")
|
||||
b.WriteString("Use load_skill(\"<slug>\") to read the full article.\n\n")
|
||||
for _, slug := range k.slugs {
|
||||
fmt.Fprintf(&b, "- **%s** — %s\n", slug, k.bySlug[slug].summary)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Get implements SkillProvider. Returns the raw markdown body.
|
||||
func (k *KBSkills) Get(name string) (string, bool) {
|
||||
a, ok := k.bySlug[name]
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
return a.body, true
|
||||
}
|
||||
|
||||
// Slugs returns the article slugs (sorted). Used by KBSearchTool.
|
||||
func (k *KBSkills) Slugs() []string { return append([]string(nil), k.slugs...) }
|
||||
|
||||
// Article returns the (summary, body) for a slug. Used by KBSearchTool
|
||||
// for snippet preview.
|
||||
func (k *KBSkills) Article(slug string) (summary, body string, ok bool) {
|
||||
a, ok := k.bySlug[slug]
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
return a.summary, a.body, true
|
||||
}
|
||||
|
||||
// extractSummary pulls the first non-heading, non-blank line out of an
|
||||
// article. Falls back to the slug-friendly title if nothing matches.
|
||||
func extractSummary(body string) string {
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
t := strings.TrimSpace(line)
|
||||
if t == "" || strings.HasPrefix(t, "#") {
|
||||
continue
|
||||
}
|
||||
if len(t) > 160 {
|
||||
t = t[:160] + "..."
|
||||
}
|
||||
return t
|
||||
}
|
||||
return "(no summary)"
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
// In-memory ticket store. Goroutine-safe via a sync.RWMutex; the IDs are
|
||||
// monotonically allocated so a session can refer to "the ticket I just
|
||||
// created" without round-tripping through the model.
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Ticket statuses. Stored as plain strings (rather than a custom enum
|
||||
// type) so the JSON the agent sees is self-describing.
|
||||
const (
|
||||
StatusOpen = "open"
|
||||
StatusPending = "pending"
|
||||
StatusResolved = "resolved"
|
||||
StatusEscalated = "escalated"
|
||||
)
|
||||
|
||||
// Note is one entry in a ticket's history. Internal=true marks a note
|
||||
// the customer wouldn't see — useful for the agent to record what it
|
||||
// did between turns.
|
||||
type Note struct {
|
||||
Author string `json:"author"`
|
||||
Content string `json:"content"`
|
||||
Internal bool `json:"internal"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Ticket is the unit the agent reads, creates, and (in supervisor mode)
|
||||
// updates. Mirrors the fields a real ticketing system exposes; status +
|
||||
// priority are constrained strings rather than enums for JSON simplicity.
|
||||
type Ticket struct {
|
||||
ID string `json:"id"`
|
||||
CustomerID string `json:"customer_id"`
|
||||
Subject string `json:"subject"`
|
||||
Description string `json:"description"`
|
||||
Status string `json:"status"`
|
||||
Priority string `json:"priority"` // low | medium | high | urgent
|
||||
Notes []Note `json:"notes"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// TicketStore is the in-memory backend shared by all ticket-* tools.
|
||||
type TicketStore struct {
|
||||
mu sync.RWMutex
|
||||
byID map[string]*Ticket
|
||||
nextID int
|
||||
}
|
||||
|
||||
// NewTicketStore allocates an empty store with IDs starting at T-1001.
|
||||
func NewTicketStore() *TicketStore {
|
||||
return &TicketStore{
|
||||
byID: make(map[string]*Ticket),
|
||||
nextID: 1001,
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a copy of the ticket so callers can't mutate the stored
|
||||
// value through the returned pointer.
|
||||
func (s *TicketStore) Get(id string) (*Ticket, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
t, ok := s.byID[id]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
cp := *t
|
||||
cp.Notes = append([]Note(nil), t.Notes...) // defensive copy
|
||||
return &cp, true
|
||||
}
|
||||
|
||||
// Create allocates a new ticket id and stores the record. customerID,
|
||||
// subject, and description are required; defaults are applied to status
|
||||
// and priority when blank.
|
||||
func (s *TicketStore) Create(customerID, subject, description, priority string) (*Ticket, error) {
|
||||
if customerID == "" {
|
||||
return nil, errors.New("customer_id is required")
|
||||
}
|
||||
if subject == "" {
|
||||
return nil, errors.New("subject is required")
|
||||
}
|
||||
if description == "" {
|
||||
return nil, errors.New("description is required")
|
||||
}
|
||||
if priority == "" {
|
||||
priority = "medium"
|
||||
}
|
||||
if !validPriority(priority) {
|
||||
return nil, fmt.Errorf("invalid priority %q (allowed: low, medium, high, urgent)", priority)
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
id := fmt.Sprintf("T-%d", s.nextID)
|
||||
s.nextID++
|
||||
now := time.Now().UTC()
|
||||
t := &Ticket{
|
||||
ID: id,
|
||||
CustomerID: customerID,
|
||||
Subject: subject,
|
||||
Description: description,
|
||||
Status: StatusOpen,
|
||||
Priority: priority,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
s.byID[id] = t
|
||||
cp := *t
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
// UpdateOpts selects which fields a TicketStore.Update call mutates.
|
||||
// Unset pointers leave the field unchanged. Note (when non-empty) is
|
||||
// always appended in addition to any field changes.
|
||||
type UpdateOpts struct {
|
||||
Status *string
|
||||
Priority *string
|
||||
Note string
|
||||
Author string
|
||||
Internal bool
|
||||
}
|
||||
|
||||
// Update mutates an existing ticket. Returns the post-update copy or an
|
||||
// error if the id is unknown / the field values are invalid.
|
||||
func (s *TicketStore) Update(id string, opts UpdateOpts) (*Ticket, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
t, ok := s.byID[id]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("ticket %q not found", id)
|
||||
}
|
||||
if opts.Status != nil {
|
||||
if !validStatus(*opts.Status) {
|
||||
return nil, fmt.Errorf("invalid status %q (allowed: open, pending, resolved, escalated)", *opts.Status)
|
||||
}
|
||||
t.Status = *opts.Status
|
||||
}
|
||||
if opts.Priority != nil {
|
||||
if !validPriority(*opts.Priority) {
|
||||
return nil, fmt.Errorf("invalid priority %q (allowed: low, medium, high, urgent)", *opts.Priority)
|
||||
}
|
||||
t.Priority = *opts.Priority
|
||||
}
|
||||
if opts.Note != "" {
|
||||
author := opts.Author
|
||||
if author == "" {
|
||||
author = "agent"
|
||||
}
|
||||
t.Notes = append(t.Notes, Note{
|
||||
Author: author,
|
||||
Content: opts.Note,
|
||||
Internal: opts.Internal,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
})
|
||||
}
|
||||
t.UpdatedAt = time.Now().UTC()
|
||||
cp := *t
|
||||
cp.Notes = append([]Note(nil), t.Notes...)
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
// All returns every ticket, sorted by id (ascending). Used only by tests
|
||||
// today; could back a future tickets_list tool.
|
||||
func (s *TicketStore) All() []Ticket {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
out := make([]Ticket, 0, len(s.byID))
|
||||
for _, t := range s.byID {
|
||||
cp := *t
|
||||
cp.Notes = append([]Note(nil), t.Notes...)
|
||||
out = append(out, cp)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out
|
||||
}
|
||||
|
||||
// Seed pre-populates four tickets covering the main scenarios the demo
|
||||
// prompts surface. Idempotent — safe to call once at startup.
|
||||
func (s *TicketStore) Seed() {
|
||||
now := time.Now().UTC()
|
||||
ago := func(d time.Duration) time.Time { return now.Add(-d) }
|
||||
seeds := []*Ticket{
|
||||
{
|
||||
ID: "T-1001", CustomerID: "C-7782",
|
||||
Subject: "Refund for last month's overage charge",
|
||||
Description: "Customer says the $87 overage on April invoice was unexpected; " +
|
||||
"hadn't seen the rate-limit warnings.",
|
||||
Status: StatusOpen, Priority: "medium",
|
||||
CreatedAt: ago(36 * time.Hour), UpdatedAt: ago(36 * time.Hour),
|
||||
},
|
||||
{
|
||||
ID: "T-1002", CustomerID: "C-2294",
|
||||
Subject: "API returning 401s after key rotation",
|
||||
Description: "Customer rotated their API key in the dashboard but the new key " +
|
||||
"returns 401 from /v1/messages. Old key still works.",
|
||||
Status: StatusPending, Priority: "high",
|
||||
Notes: []Note{{
|
||||
Author: "agent", Content: "Confirmed propagation delay; ETA 5 minutes.",
|
||||
Internal: true, CreatedAt: ago(2 * time.Hour),
|
||||
}},
|
||||
CreatedAt: ago(3 * time.Hour), UpdatedAt: ago(2 * time.Hour),
|
||||
},
|
||||
{
|
||||
ID: "T-1003", CustomerID: "C-9911",
|
||||
Subject: "Possible account compromise — unfamiliar logins",
|
||||
Description: "Customer reports two login events from IPs in countries " +
|
||||
"they've never visited. Wants the account locked pending investigation.",
|
||||
Status: StatusEscalated, Priority: "urgent",
|
||||
Notes: []Note{{
|
||||
Author: "supervisor", Content: "Account suspended; security team paged.",
|
||||
Internal: true, CreatedAt: ago(20 * time.Minute),
|
||||
}},
|
||||
CreatedAt: ago(45 * time.Minute), UpdatedAt: ago(20 * time.Minute),
|
||||
},
|
||||
{
|
||||
ID: "T-1004", CustomerID: "C-4451",
|
||||
Subject: "Resolved: password reset not arriving",
|
||||
Description: "Customer wasn't receiving the reset email; turned out to be " +
|
||||
"a corporate filter blocking transactional senders.",
|
||||
Status: StatusResolved, Priority: "low",
|
||||
CreatedAt: ago(72 * time.Hour), UpdatedAt: ago(60 * time.Hour),
|
||||
},
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, t := range seeds {
|
||||
s.byID[t.ID] = t
|
||||
}
|
||||
}
|
||||
|
||||
func validStatus(s string) bool {
|
||||
switch s {
|
||||
case StatusOpen, StatusPending, StatusResolved, StatusEscalated:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func validPriority(p string) bool {
|
||||
switch p {
|
||||
case "low", "medium", "high", "urgent":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// Pure-Go unit tests for the offline pieces (store, permission,
|
||||
// skills, kb_search). The agent loop itself isn't exercised here — it
|
||||
// needs an LLM and is covered by interactive use.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
func TestTicketStore_GetSeed(t *testing.T) {
|
||||
s := NewTicketStore()
|
||||
s.Seed()
|
||||
got, ok := s.Get("T-1002")
|
||||
if !ok {
|
||||
t.Fatal("seed ticket T-1002 missing")
|
||||
}
|
||||
if got.Status != StatusPending {
|
||||
t.Errorf("T-1002 status = %q, want %q", got.Status, StatusPending)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicketStore_GetReturnsCopy(t *testing.T) {
|
||||
s := NewTicketStore()
|
||||
s.Seed()
|
||||
t1, _ := s.Get("T-1001")
|
||||
t1.Status = "tampered"
|
||||
t2, _ := s.Get("T-1001")
|
||||
if t2.Status == "tampered" {
|
||||
t.Error("Get returned a live pointer; mutations leaked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicketStore_CreateAndUpdate(t *testing.T) {
|
||||
s := NewTicketStore()
|
||||
tk, err := s.Create("C-1", "Cannot log in", "got 403", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(tk.ID, "T-") {
|
||||
t.Errorf("id = %q, want T- prefix", tk.ID)
|
||||
}
|
||||
if tk.Priority != "medium" {
|
||||
t.Errorf("default priority = %q, want medium", tk.Priority)
|
||||
}
|
||||
|
||||
resolved := StatusResolved
|
||||
updated, err := s.Update(tk.ID, UpdateOpts{
|
||||
Status: &resolved,
|
||||
Note: "fixed via password reset",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if updated.Status != StatusResolved {
|
||||
t.Errorf("status not updated: %q", updated.Status)
|
||||
}
|
||||
if len(updated.Notes) != 1 || updated.Notes[0].Content != "fixed via password reset" {
|
||||
t.Errorf("note not appended: %+v", updated.Notes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicketStore_RejectsInvalidPriority(t *testing.T) {
|
||||
s := NewTicketStore()
|
||||
if _, err := s.Create("C-1", "subj", "desc", "critical"); err == nil {
|
||||
t.Error("expected priority validation error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportChecker_Default_HidesGated(t *testing.T) {
|
||||
c := NewSupportChecker(false)
|
||||
defs := []llm.ToolDef{
|
||||
{Name: "kb_search"},
|
||||
{Name: "tickets_get"},
|
||||
{Name: "tickets_update"},
|
||||
{Name: "escalate_to_human"},
|
||||
{Name: "load_skill"},
|
||||
}
|
||||
out := c.FilterToolDefs(defs, "support")
|
||||
names := map[string]bool{}
|
||||
for _, d := range out {
|
||||
names[d.Name] = true
|
||||
}
|
||||
if names["tickets_update"] || names["escalate_to_human"] {
|
||||
t.Error("non-supervisor mode leaked write tools into the LLM tool list")
|
||||
}
|
||||
for _, want := range []string{"kb_search", "tickets_get", "load_skill"} {
|
||||
if !names[want] {
|
||||
t.Errorf("non-supervisor mode hid read tool %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportChecker_DeniesGatedAtCallTime(t *testing.T) {
|
||||
c := NewSupportChecker(false)
|
||||
d := c.Check(context.Background(), "support", "tickets_update", nil)
|
||||
if d.Behavior != 1 { // tool.DecisionDeny
|
||||
t.Errorf("expected Deny, got %v", d.Behavior)
|
||||
}
|
||||
if !strings.Contains(d.Reason, "supervisor") {
|
||||
t.Errorf("deny reason should mention supervisor mode: %q", d.Reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportChecker_Supervisor_AllowsAll(t *testing.T) {
|
||||
c := NewSupportChecker(true)
|
||||
for _, name := range []string{"kb_search", "tickets_update", "escalate_to_human"} {
|
||||
if c.Check(context.Background(), "support", name, nil).Behavior != 0 {
|
||||
t.Errorf("supervisor mode denied %q", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBSkills_FormatIndexAndGet(t *testing.T) {
|
||||
k := NewKBSkills()
|
||||
idx := k.FormatIndex()
|
||||
for _, want := range []string{"refund-policy", "escalation-matrix", "account-recovery", "password-reset", "api-rate-limits"} {
|
||||
if !strings.Contains(idx, want) {
|
||||
t.Errorf("index missing %q", want)
|
||||
}
|
||||
}
|
||||
body, ok := k.Get("refund-policy")
|
||||
if !ok || !strings.Contains(body, "Refund Policy") {
|
||||
t.Errorf("Get(refund-policy) returned ok=%v body-prefix=%q", ok, firstN(body, 60))
|
||||
}
|
||||
if _, ok := k.Get("does-not-exist"); ok {
|
||||
t.Error("Get on unknown slug returned ok=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBSearchTool_FindsByBodyContent(t *testing.T) {
|
||||
tool := &KBSearchTool{KB: NewKBSkills()}
|
||||
out, err := tool.Execute(context.Background(), json.RawMessage(`{"query":"chargeback"}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Error != "" {
|
||||
t.Fatal(out.Error)
|
||||
}
|
||||
if !strings.Contains(out.Output, "refund-policy") {
|
||||
t.Errorf("expected refund-policy hit for 'chargeback': %s", firstN(out.Output, 200))
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBSearchTool_ShortQueryRejected(t *testing.T) {
|
||||
tool := &KBSearchTool{KB: NewKBSkills()}
|
||||
out, _ := tool.Execute(context.Background(), json.RawMessage(`{"query":"a"}`))
|
||||
if out.Error == "" {
|
||||
t.Error("expected error for 1-char query")
|
||||
}
|
||||
}
|
||||
|
||||
func firstN(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
// Five concrete tools for the support agent. The runtime auto-registers
|
||||
// a sixth (load_skill) because deps.Skills is set, so the agent can
|
||||
// pull full KB article bodies on demand keyed by the slugs surfaced in
|
||||
// the static prompt's Knowledge Base index.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
func errResult(err error) tool.ToolResult { return tool.ToolResult{Error: err.Error()} }
|
||||
|
||||
func jsonOut(v any) tool.ToolResult {
|
||||
b, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return errResult(err)
|
||||
}
|
||||
return tool.ToolResult{Output: string(b)}
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// kb_search — substring match across slugs + summaries + bodies
|
||||
// =====================================================================
|
||||
|
||||
type KBSearchTool struct {
|
||||
KB *KBSkills
|
||||
}
|
||||
|
||||
func (*KBSearchTool) Name() string { return "kb_search" }
|
||||
func (*KBSearchTool) Description() string {
|
||||
return "Search the Acme knowledge base by free-text query. Returns " +
|
||||
"matching article slugs with one-line summaries and a snippet " +
|
||||
"showing where the query hit. Pair with load_skill(slug) to read " +
|
||||
"the full article body before quoting policy."
|
||||
}
|
||||
func (*KBSearchTool) Parameters() json.RawMessage {
|
||||
return json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"description": "Substring to match (case-insensitive). 2+ characters."
|
||||
}
|
||||
},
|
||||
"required": ["query"]
|
||||
}`)
|
||||
}
|
||||
func (*KBSearchTool) IsConcurrencySafe(json.RawMessage) bool { return true }
|
||||
|
||||
func (t *KBSearchTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
var in struct {
|
||||
Query string `json:"query"`
|
||||
}
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return errResult(fmt.Errorf("invalid input: %w", err)), nil
|
||||
}
|
||||
q := strings.ToLower(strings.TrimSpace(in.Query))
|
||||
if len(q) < 2 {
|
||||
return errResult(fmt.Errorf("query must be at least 2 characters")), nil
|
||||
}
|
||||
|
||||
type hit struct {
|
||||
Slug string `json:"slug"`
|
||||
Summary string `json:"summary"`
|
||||
Snippet string `json:"snippet,omitempty"`
|
||||
}
|
||||
var hits []hit
|
||||
for _, slug := range t.KB.Slugs() {
|
||||
summary, body, _ := t.KB.Article(slug)
|
||||
lowSlug, lowSum, lowBody := strings.ToLower(slug), strings.ToLower(summary), strings.ToLower(body)
|
||||
if !strings.Contains(lowSlug, q) && !strings.Contains(lowSum, q) && !strings.Contains(lowBody, q) {
|
||||
continue
|
||||
}
|
||||
// Build a snippet around the first body hit (if any) to give the
|
||||
// model enough context to decide whether to load_skill the
|
||||
// full article.
|
||||
snippet := ""
|
||||
if idx := strings.Index(lowBody, q); idx >= 0 {
|
||||
start := idx - 80
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
end := idx + len(q) + 120
|
||||
if end > len(body) {
|
||||
end = len(body)
|
||||
}
|
||||
snippet = strings.TrimSpace(body[start:end])
|
||||
snippet = strings.ReplaceAll(snippet, "\n", " ")
|
||||
if start > 0 {
|
||||
snippet = "…" + snippet
|
||||
}
|
||||
if end < len(body) {
|
||||
snippet = snippet + "…"
|
||||
}
|
||||
}
|
||||
hits = append(hits, hit{slug, summary, snippet})
|
||||
}
|
||||
|
||||
return jsonOut(map[string]any{
|
||||
"query": in.Query,
|
||||
"matches": len(hits),
|
||||
"results": hits,
|
||||
}), nil
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// tickets_get — fetch one ticket by ID
|
||||
// =====================================================================
|
||||
|
||||
type TicketGetTool struct {
|
||||
Store *TicketStore
|
||||
}
|
||||
|
||||
func (*TicketGetTool) Name() string { return "tickets_get" }
|
||||
func (*TicketGetTool) Description() string {
|
||||
return "Fetch a support ticket by its ID (format 'T-####'). Returns the " +
|
||||
"full ticket including status, priority, customer ID, history, and " +
|
||||
"any internal notes. Read-only — never mutates."
|
||||
}
|
||||
func (*TicketGetTool) Parameters() json.RawMessage {
|
||||
return json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Ticket ID, e.g. 'T-1002'."
|
||||
}
|
||||
},
|
||||
"required": ["id"]
|
||||
}`)
|
||||
}
|
||||
func (*TicketGetTool) IsConcurrencySafe(json.RawMessage) bool { return true }
|
||||
|
||||
func (t *TicketGetTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
var in struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return errResult(fmt.Errorf("invalid input: %w", err)), nil
|
||||
}
|
||||
if strings.TrimSpace(in.ID) == "" {
|
||||
return errResult(fmt.Errorf("id is required")), nil
|
||||
}
|
||||
tk, ok := t.Store.Get(in.ID)
|
||||
if !ok {
|
||||
return errResult(fmt.Errorf("ticket %q not found", in.ID)), nil
|
||||
}
|
||||
return jsonOut(tk), nil
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// tickets_create — file a new ticket
|
||||
// =====================================================================
|
||||
|
||||
type TicketCreateTool struct {
|
||||
Store *TicketStore
|
||||
}
|
||||
|
||||
func (*TicketCreateTool) Name() string { return "tickets_create" }
|
||||
func (*TicketCreateTool) Description() string {
|
||||
return "File a new support ticket. Use when the customer's issue warrants " +
|
||||
"tracking — refund requests, account compromise, billing disputes, " +
|
||||
"reported outages, or anything that may need supervisor follow-up. " +
|
||||
"Returns the new ticket ID; remember it for later updates."
|
||||
}
|
||||
func (*TicketCreateTool) Parameters() json.RawMessage {
|
||||
return json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"customer_id": {
|
||||
"type": "string",
|
||||
"description": "Customer account ID, e.g. 'C-7782'. If unknown, use 'C-UNKNOWN' and note it in the description."
|
||||
},
|
||||
"subject": {
|
||||
"type": "string",
|
||||
"description": "One-line summary, < 80 chars."
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "Full description in the customer's words plus any context the agent has gathered."
|
||||
},
|
||||
"priority": {
|
||||
"type": "string",
|
||||
"enum": ["low", "medium", "high", "urgent"],
|
||||
"description": "Default 'medium'. See escalation-matrix for thresholds."
|
||||
}
|
||||
},
|
||||
"required": ["customer_id", "subject", "description"]
|
||||
}`)
|
||||
}
|
||||
|
||||
// Not concurrency-safe: allocates a new ID and mutates store state. The
|
||||
// partitioner will serialise multiple create calls inside one batch.
|
||||
func (*TicketCreateTool) IsConcurrencySafe(json.RawMessage) bool { return false }
|
||||
|
||||
func (t *TicketCreateTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
var in struct {
|
||||
CustomerID string `json:"customer_id"`
|
||||
Subject string `json:"subject"`
|
||||
Description string `json:"description"`
|
||||
Priority string `json:"priority"`
|
||||
}
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return errResult(fmt.Errorf("invalid input: %w", err)), nil
|
||||
}
|
||||
tk, err := t.Store.Create(in.CustomerID, in.Subject, in.Description, in.Priority)
|
||||
if err != nil {
|
||||
return errResult(err), nil
|
||||
}
|
||||
return jsonOut(map[string]any{
|
||||
"created": true,
|
||||
"ticket": tk,
|
||||
}), nil
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// tickets_update — change status / priority / append a note
|
||||
// =====================================================================
|
||||
|
||||
type TicketUpdateTool struct {
|
||||
Store *TicketStore
|
||||
}
|
||||
|
||||
func (*TicketUpdateTool) Name() string { return "tickets_update" }
|
||||
func (*TicketUpdateTool) Description() string {
|
||||
return "Mutate an existing ticket. Set `status` to mark it resolved or " +
|
||||
"escalated, change `priority`, or append an `internal_note`. " +
|
||||
"Restricted to supervisor mode — non-supervisor calls are denied " +
|
||||
"by the permission checker before reaching this tool."
|
||||
}
|
||||
func (*TicketUpdateTool) Parameters() json.RawMessage {
|
||||
return json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Ticket ID, e.g. 'T-1002'."
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["open", "pending", "resolved", "escalated"],
|
||||
"description": "Optional. Omit to leave unchanged."
|
||||
},
|
||||
"priority": {
|
||||
"type": "string",
|
||||
"enum": ["low", "medium", "high", "urgent"],
|
||||
"description": "Optional. Omit to leave unchanged."
|
||||
},
|
||||
"internal_note": {
|
||||
"type": "string",
|
||||
"description": "Optional internal note to append (not visible to the customer)."
|
||||
}
|
||||
},
|
||||
"required": ["id"]
|
||||
}`)
|
||||
}
|
||||
func (*TicketUpdateTool) IsConcurrencySafe(json.RawMessage) bool { return false }
|
||||
|
||||
func (t *TicketUpdateTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
var in struct {
|
||||
ID string `json:"id"`
|
||||
Status *string `json:"status,omitempty"`
|
||||
Priority *string `json:"priority,omitempty"`
|
||||
InternalNote string `json:"internal_note,omitempty"`
|
||||
}
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return errResult(fmt.Errorf("invalid input: %w", err)), nil
|
||||
}
|
||||
tk, err := t.Store.Update(in.ID, UpdateOpts{
|
||||
Status: in.Status,
|
||||
Priority: in.Priority,
|
||||
Note: in.InternalNote,
|
||||
Author: "agent",
|
||||
Internal: true,
|
||||
})
|
||||
if err != nil {
|
||||
return errResult(err), nil
|
||||
}
|
||||
return jsonOut(map[string]any{
|
||||
"updated": true,
|
||||
"ticket": tk,
|
||||
}), nil
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// escalate_to_human — webhook POST (or stdout in demo mode)
|
||||
// =====================================================================
|
||||
|
||||
type EscalateTool struct {
|
||||
// Webhook is an optional HTTPS URL to POST escalation payloads to.
|
||||
// When empty, the tool prints to stdout instead — fine for demos.
|
||||
Webhook string
|
||||
}
|
||||
|
||||
func (*EscalateTool) Name() string { return "escalate_to_human" }
|
||||
func (*EscalateTool) Description() string {
|
||||
return "Escalate a ticket to a human (Security, Billing, SRE, or Senior " +
|
||||
"Support). Always file the ticket first, then escalate referencing " +
|
||||
"its ID. Restricted to supervisor mode. The escalation note must " +
|
||||
"follow the format in `escalation-matrix`."
|
||||
}
|
||||
func (*EscalateTool) Parameters() json.RawMessage {
|
||||
return json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ticket_id": {
|
||||
"type": "string",
|
||||
"description": "ID of the ticket being escalated. Required."
|
||||
},
|
||||
"route_to": {
|
||||
"type": "string",
|
||||
"enum": ["Security", "Billing", "Legal", "SRE", "Senior support", "Tier 2"],
|
||||
"description": "Which queue receives the escalation."
|
||||
},
|
||||
"summary": {
|
||||
"type": "string",
|
||||
"description": "One-line summary the receiving human reads first."
|
||||
},
|
||||
"note": {
|
||||
"type": "string",
|
||||
"description": "Full escalation note formatted per escalation-matrix conventions."
|
||||
}
|
||||
},
|
||||
"required": ["ticket_id", "route_to", "summary", "note"]
|
||||
}`)
|
||||
}
|
||||
func (*EscalateTool) IsConcurrencySafe(json.RawMessage) bool { return false }
|
||||
|
||||
func (t *EscalateTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
var in struct {
|
||||
TicketID string `json:"ticket_id"`
|
||||
RouteTo string `json:"route_to"`
|
||||
Summary string `json:"summary"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return errResult(fmt.Errorf("invalid input: %w", err)), nil
|
||||
}
|
||||
if in.TicketID == "" || in.RouteTo == "" || in.Summary == "" || in.Note == "" {
|
||||
return errResult(fmt.Errorf("ticket_id, route_to, summary, and note are all required")), nil
|
||||
}
|
||||
|
||||
payload := map[string]any{
|
||||
"ticket_id": in.TicketID,
|
||||
"route_to": in.RouteTo,
|
||||
"summary": in.Summary,
|
||||
"note": in.Note,
|
||||
"escalated_at": time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
if t.Webhook == "" {
|
||||
// Demo mode: print to stdout instead of an HTTP POST so the
|
||||
// example runs without external infrastructure.
|
||||
fmt.Fprintf(jsonStdoutWriter{}, "\n[ESCALATION → %s] %s | ticket=%s\n %s\n",
|
||||
in.RouteTo, in.Summary, in.TicketID, in.Note)
|
||||
payload["delivery"] = "stdout (no SUPPORT_AGENT_WEBHOOK configured)"
|
||||
return jsonOut(payload), nil
|
||||
}
|
||||
|
||||
body, _ := json.Marshal(payload)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.Webhook, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return errResult(fmt.Errorf("build webhook request: %w", err)), nil
|
||||
}
|
||||
req.Header.Set("content-type", "application/json")
|
||||
req.Header.Set("user-agent", "harness-support-agent/0.1")
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return errResult(fmt.Errorf("webhook POST: %w", err)), nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
return errResult(fmt.Errorf("webhook returned %d", resp.StatusCode)), nil
|
||||
}
|
||||
payload["delivery"] = fmt.Sprintf("webhook %d", resp.StatusCode)
|
||||
return jsonOut(payload), nil
|
||||
}
|
||||
|
||||
// jsonStdoutWriter is a thin io.Writer wrapper around os.Stdout used so
|
||||
// the escalation banner doesn't need its own import block; keeps the
|
||||
// fmt.Fprintf call inline with the rest of the package's stdout uses.
|
||||
type jsonStdoutWriter struct{}
|
||||
|
||||
func (jsonStdoutWriter) Write(p []byte) (int, error) {
|
||||
return fmt.Print(string(p))
|
||||
}
|
||||
Reference in new issue
Block a user