Documentation
¶
Index ¶
- func BashGrantPrefix(argsJSON string) (string, bool)
- func FormatToolCall(name, argsJSON string) string
- func GrantScope(name, argsJSON string) (scope, prefix string)
- func HumanTokens(n int) string
- func IsReadOnly(name, argsJSON string, cmds readOnlyCommands) bool
- func PrettyJSON(s string) string
- func PreviewResult(s string, maxLines int) string
- type AgentEvent
- type AgentStatus
- type ArgRow
- type AskRequest
- type Callbacks
- type ContentPart
- type CronRequest
- type FriendlyError
- type Message
- type PartKind
- type Session
- func (s *Session) AgentLog(agentID string) string
- func (s *Session) AgentManager() *cogito.AgentManager
- func (s *Session) ClearGoal()
- func (s *Session) ClearHistory()
- func (s *Session) Close() error
- func (s *Session) CompactHistory() (before, after int, err error)
- func (s *Session) ContextTokens() int
- func (s *Session) ExportHistory() []openai.ChatCompletionMessage
- func (s *Session) GetMessages() []Message
- func (s *Session) Goal() string
- func (s *Session) Inject(msg string) bool
- func (s *Session) InjectUser(msg string) bool
- func (s *Session) Interrupt()
- func (s *Session) KillAgent(id string) bool
- func (s *Session) LoadSkill(name string) (string, error)
- func (s *Session) ReconcileMCPServers(desired map[string]types.MCPServer) error
- func (s *Session) Reload(cfg types.Config) error
- func (s *Session) RunLive() bool
- func (s *Session) SendMessage(text string, parts ...ContentPart) (string, error)
- func (s *Session) SendWithAttachments(ctx context.Context, text string, files []string, ...) (string, []attachments.Blocked, error)
- func (s *Session) SetGoal(goal string)
- func (s *Session) SetShellJobs(jobs *wizmcp.ShellJobs)
- func (s *Session) SetSkills(skills []types.Skill) error
- func (s *Session) TakeUndelivered() []string
- func (s *Session) ToolCallDenied(req ToolCallRequest) bool
- type StreamEvent
- type ToolCallRequest
- type ToolCallResponse
- type ToolResult
- type WakeupRequest
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BashGrantPrefix ¶ added in v0.2.0
BashGrantPrefix derives the prefix-grant key for a bash tool call: the script's first word, when the script is a single simple command. ok is false when no safe prefix can be derived (compound or chaining commands, unparseable args) — the UI then offers a whole-tool grant instead.
func FormatToolCall ¶
FormatToolCall renders a tool call's arguments as a compact, human-readable summary for display, replacing raw JSON. argsJSON is the marshaled arguments object. Known tools get a purpose-built one-liner (see toolFormatters); any other tool (MCP servers, plugins) falls back to an aligned key/value args card (see ToolArgRows). If argsJSON is not a JSON object the input is returned unchanged.
func GrantScope ¶ added in v0.2.0
GrantScope describes what choosing "always allow" covers for this call: scope is the user-facing wording, prefix the grant key ("" = whole tool). Only bash gets prefix grants; every other tool (including bash_background) is granted whole.
func HumanTokens ¶
HumanTokens formats a token count compactly (e.g. 47200 → "47.2k").
func IsReadOnly ¶ added in v0.3.0
IsReadOnly reports whether a tool call only observes state and is therefore safe to auto-approve in the default prompt mode. It is deliberately conservative: unknown tools and any non-trivial bash return false. cmds is the read-only bash command set (built-ins plus user config).
func PrettyJSON ¶
PrettyJSON indents a JSON string for display. If s is not valid JSON it is returned unchanged.
func PreviewResult ¶
PreviewResult formats a tool result for compact display: it pretty-prints JSON (PrettyJSON), trims surrounding whitespace, then truncates to at most maxLines lines, appending a "… N more lines" note when it had to cut. Returns "" for empty/whitespace input. maxLines <= 0 means no line limit.
Types ¶
type AgentEvent ¶
type AgentEvent struct {
ID string
Type string // agent type name (e.g. "explore"); empty for generic
Task string
Status AgentStatus
Result string
Err error
// Populated on completion/failure events (zero otherwise):
ToolCount int // tools the sub-agent executed
TotalTokens int // cumulative tokens consumed across the run
Elapsed time.Duration // wall-clock from spawn to completion
}
AgentEvent is emitted on sub-agent lifecycle changes (spawn/complete/fail).
func (AgentEvent) StatsSuffix ¶
func (ev AgentEvent) StatsSuffix() string
StatsSuffix renders the trailing run-stats summary for a completed sub-agent, e.g. " · 3 tools · 12.4k tokens · 1m 03s". Segments whose value is zero or unknown are omitted; returns "" when nothing is known.
type AgentStatus ¶
type AgentStatus string
AgentStatus mirrors cogito's sub-agent lifecycle states for UI consumption, decoupling the UI from the cogito type.
const ( AgentStatusRunning AgentStatus = "running" AgentStatusCompleted AgentStatus = "completed" AgentStatusFailed AgentStatus = "failed" )
type ArgRow ¶ added in v0.2.0
type ArgRow struct {
Key string
Value string // first line of the value
// HiddenLines counts the value's truncated lines (0 = single-line value).
HiddenLines int
}
ArgRow is one key/value line of the fallback args card. Nested objects are flattened to dotted keys, so a card is always a flat list of rows.
func ToolArgRows ¶ added in v0.2.0
ToolArgRows returns the args-card rows for a tool call, for callers that style keys and values separately (the TUI approval block). ok is false when the tool has a purpose-built formatter or the arguments are not a JSON object — render FormatToolCall's string instead.
func (ArgRow) ValueDisplay ¶ added in v0.2.0
ValueDisplay renders the value with its hidden-line hint, e.g. "The login flow redirects to… (+12 lines)".
type AskRequest ¶
type AskRequest struct {
Question string
Options []string // optional multiple-choice options
// MultiSelect, when true, lets the user pick several options (checkbox);
// otherwise it's a single choice (radio). Only meaningful with Options.
MultiSelect bool
}
AskRequest is a question the agent wants to ask the user.
type Callbacks ¶
type Callbacks struct {
OnStatus func(status string)
OnReasoning func(reasoning string)
// OnStream, when set, receives live token-level deltas during generation
// (reasoning/answer/tool-selection) so a UI can render progress as it
// happens. Setting it opts the session into cogito's streaming path; the
// existing step-boundary callbacks (OnReasoning/OnStatus/OnToolResult) still
// fire afterwards. Optional — leave nil for the non-streaming path.
OnStream func(ev StreamEvent)
OnToolCall func(req ToolCallRequest) ToolCallResponse
OnResponse func(response string)
OnError func(err error)
// OnToolResult is called after a tool finishes, with its output. Optional.
OnToolResult func(res ToolResult)
// OnAgentEvent is called on sub-agent lifecycle changes. Optional.
OnAgentEvent func(ev AgentEvent)
// OnAskUser is called when the agent asks the user a question (ask_user tool).
// It blocks until the user answers and returns the answer.
OnAskUser func(req AskRequest) string
// OnScheduleWakeup is called when the agent schedules an in-session wake-up
// (schedule_wakeup tool). It returns immediately with a confirmation; the
// host re-engages the agent with the note once the delay elapses.
OnScheduleWakeup func(req WakeupRequest) string
// OnCronCreate registers a cron job and returns a confirmation (incl. its id).
OnCronCreate func(req CronRequest) string
// OnCronList returns a human-readable listing of active cron jobs.
OnCronList func() string
// OnCronDelete cancels a cron job by id and returns a confirmation.
OnCronDelete func(id string) string
// OnCompactDone is called after the conversation is compacted, with the
// approximate token counts before and after. Optional.
OnCompactDone func(before, after int)
// OnParked is called when the live run parks: the assistant has produced a
// reply but cogito keeps the loop alive because background work (sub-agents
// or shell jobs) is still pending or because the user may inject a follow-up.
// reply is the assistant's text at the park point (may be empty). The host
// can finalize the assistant turn in the transcript and unlock the composer
// so the user can keep chatting (their input is injected into this same run).
// May fire multiple times across one run. Optional.
OnParked func(reply string)
// OnResumed is called when an injected message wakes a parked run. The host
// can re-lock the composer and show the working indicator again. May fire
// multiple times across one run. Optional.
OnResumed func()
}
Callbacks defines the interface for UI interactions.
type ContentPart ¶ added in v0.4.1
ContentPart is nib's native multimodal part, satisfying cogito.TypedMultimedia so SendMessage can hand image/audio/video parts to the fragment. DataURI is a base64 data: URI (e.g. data:image/png;base64,...). AudioFormat is the audio container (e.g. "wav") used for the input_audio wire form.
func (ContentPart) Data ¶ added in v0.4.1
func (p ContentPart) Data() string
Data returns the raw base64 payload (no data: prefix) for input_audio; "" for image/video (which travel via URL()).
func (ContentPart) Format ¶ added in v0.4.1
func (p ContentPart) Format() string
Format returns the audio container for input_audio; "" for image/video.
func (ContentPart) MediaKind ¶ added in v0.4.1
func (p ContentPart) MediaKind() cogito.MediaKind
MediaKind maps to cogito's media kind.
func (ContentPart) URL ¶ added in v0.4.1
func (p ContentPart) URL() string
URL returns the data URI (used for image_url / video_url parts).
type CronRequest ¶
CronRequest is a recurring/one-shot job the agent registers (cron tool).
type FriendlyError ¶ added in v0.4.1
type FriendlyError struct {
// contains filtered or unexported fields
}
FriendlyError wraps a noisy backend error with a short, actionable message while preserving the original via Unwrap (so errors.Is/As still work).
func (*FriendlyError) Error ¶ added in v0.4.1
func (e *FriendlyError) Error() string
func (*FriendlyError) Unwrap ¶ added in v0.4.1
func (e *FriendlyError) Unwrap() error
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents a chat session with the AI assistant
func NewSession ¶
func NewSession(ctx context.Context, cfg types.Config, callbacks Callbacks, transports ...mcp.Transport) (*Session, error)
NewSession creates a new chat session
func (*Session) AgentLog ¶
AgentLog returns the captured activity log for a sub-agent (for the agent_logs tool / UI inspection).
func (*Session) AgentManager ¶
func (s *Session) AgentManager() *cogito.AgentManager
AgentManager exposes the sub-agent registry so the UI can list and detach agents.
func (*Session) ClearGoal ¶
func (s *Session) ClearGoal()
ClearGoal removes the active session goal.
func (*Session) ClearHistory ¶
func (s *Session) ClearHistory()
func (*Session) CompactHistory ¶
CompactHistory summarizes the older portion of the conversation via the LLM and rebuilds the fragment as [summary] + recent tail, keeping the display copy consistent. It returns byte/4 token estimates of the conversation before and after compaction (before==after signals a no-op). On summary failure it returns the error WITHOUT mutating session state (atomic swap).
func (*Session) ContextTokens ¶
ContextTokens reports the current conversation size in tokens for display: the last request's reported prompt tokens, or a byte/4 estimate when the backend hasn't reported usage yet (e.g. before the first turn). This is the same signal the auto-compaction trigger watches.
func (*Session) ExportHistory ¶ added in v0.4.0
func (s *Session) ExportHistory() []openai.ChatCompletionMessage
ExportHistory returns a copy of the full conversation messages (the same []openai.ChatCompletionMessage that backs the model context), suitable for JSON serialization and persistence. Feed the result back via types.Config.InitialHistory to resume the conversation losslessly — the model then continues with real memory of it, not a summary.
The returned slice is a copy, so mutating it (or its serialization) never touches the live session. It EXCLUDES the system prompt: s.messages only ever records user/assistant turns (the system prompt is regenerated per model/locale and re-applied to the fragment on every turn), so there is no system message to strip. Safe to call from another goroutine while a turn is running; it takes the same lock SendMessage holds while appending.
func (*Session) GetMessages ¶
GetMessages returns all messages in the conversation
func (*Session) Inject ¶
Inject delivers msg into the live run's message-injection channel, waking a parked loop so the assistant continues in the SAME run. Non-blocking: returns false when there is no live run, the channel is full, or msg is empty. Used for mid-run user follow-ups, shell-job completions, and scheduled wake-ups.
func (*Session) InjectUser ¶ added in v0.1.1
InjectUser delivers a user-typed follow-up into the live run (see Inject), and additionally tracks it: if the run returns before consuming it (the model never saw it), the text is reported by TakeUndelivered so the caller can re-dispatch it as a fresh turn instead of losing it to the end-of-run drain. System notices (shell-job completions, wake-ups) keep using Inject — re-running a stale notice as a fresh turn would re-trigger finished work.
func (*Session) Interrupt ¶
func (s *Session) Interrupt()
Interrupt cancels the in-flight turn (and any sub-agents spawned within it), leaving the session alive. Safe to call when no turn is running.
func (*Session) KillAgent ¶
KillAgent cancels a running sub-agent by id (its context is cancelled, which stops the agent and any LLM call it has in flight). Returns false when the id is unknown. Safe to call on an already-finished agent.
func (*Session) LoadSkill ¶
LoadSkill appends a named skill's instructions to the session system prompt (eager load via /skill), so subsequent turns include it without a load_skill tool call. Returns a short notice for the transcript.
func (*Session) ReconcileMCPServers ¶
ReconcileMCPServers connects newly-desired config MCP servers and closes ones no longer desired (or whose command/args changed). Connect failures are logged and skipped so one bad server never breaks the session. Called from Reload at turn start (deferred while background sub-agents run), so closing a client session here cannot race with a detached agent still using it.
func (*Session) Reload ¶
Reload re-wires every reloadable part of the session from cfg. It closes MCP client sessions and mutates session state read by the turn goroutine and by detached sub-agents, so it must run at turn start in the turn goroutine and is deferred while background sub-agents run (see applyPendingReload). It must not run concurrently with a running turn or a live detached agent.
func (*Session) RunLive ¶
RunLive reports whether a run is currently in flight (between SendMessage start and return), including while it is parked. The TUI uses this as the authoritative signal for whether a typed message should be queued into the live run or start a new turn, rather than its own loading/parked UI flags which can briefly desync across park/resume events.
func (*Session) SendMessage ¶
func (s *Session) SendMessage(text string, parts ...ContentPart) (string, error)
func (*Session) SendWithAttachments ¶ added in v0.4.1
func (s *Session) SendWithAttachments(ctx context.Context, text string, files []string, overrides map[string]attachments.Override) (string, []attachments.Blocked, error)
SendWithAttachments resolves treatments for files against the active model's capabilities, runs conversion/transcription, and sends one multimodal turn. Returns any blocked files (media the active model can't accept) for the caller to surface.
func (*Session) SetGoal ¶
SetGoal sets (or replaces) the active session goal. While a goal is set, a turn re-runs until the model calls goal_done or the user interrupts. Call between turns, not during a live run: the goal_done tool is wired at the start of a turn, so arming a goal mid-run would not expose goal_done.
func (*Session) SetShellJobs ¶
SetShellJobs wires the shared shell-job registry into the session so the pending-work predicate keeps a run parked while a backgrounded shell command is still running, and so finished shell jobs inject a completion notice into the live run. Registers the completion hook. Call once at setup.
func (*Session) SetSkills ¶
SetSkills rebuilds the in-memory skills MCP server so load_skill advertises the given skills, swapping its client. An empty list tears the server down. Called from Reload at turn start (deferred while background sub-agents run), so closing the old skills client cannot race with a detached agent.
func (*Session) TakeUndelivered ¶ added in v0.1.1
TakeUndelivered returns (and clears) user-typed follow-ups that were injected into a run that ended before consuming them. Call after a run returns to re-dispatch them as fresh turns.
func (*Session) ToolCallDenied ¶
func (s *Session) ToolCallDenied(req ToolCallRequest) bool
ToolCallDenied reports whether the given tool call would be denied (used to verify PreToolUse hook gating end-to-end).
type StreamEvent ¶ added in v0.3.1
type StreamEvent struct {
Kind string // delta kind
Content string // text delta, for reasoning/content
ToolName string // tool name, for tool_call (first chunk only)
ToolArgs string // streamed argument fragment, for tool_call
}
StreamEvent is a single live delta during generation, forwarded only when a consumer sets Callbacks.OnStream (which opts the session into cogito's streaming path). It lets a UI render reasoning/answer/tool-selection as the model produces them, instead of only at step boundaries. Kind is one of "reasoning", "content", "tool_call", "tool_result", "status", "done", "error".
type ToolCallRequest ¶
type ToolCallRequest struct {
Name string
Arguments string
Reasoning string
AgentID string // non-empty when the requesting caller is a sub-agent
}
ToolCallRequest contains information about a tool the agent wants to run.
type ToolCallResponse ¶
type ToolCallResponse struct {
Approved bool
Adjustment string
AlwaysAllow bool
// AlwaysPrefix narrows an AlwaysAllow grant for the bash tool to scripts
// whose first word matches (e.g. "git" → simple `git …` commands run
// without prompting). Empty means the grant covers the whole tool.
// Ignored unless AlwaysAllow is set.
AlwaysPrefix string
// AllowAllTurn, when set together with Approved, approves every remaining
// tool call for the rest of the current turn (incl. sub-agents) w/o prompting.
AllowAllTurn bool
}
ToolCallResponse represents the user's decision on a tool call.
type ToolResult ¶
type ToolResult struct {
Name string
Result string
Arguments string // marshaled JSON of the call's arguments, for display
AgentID string // non-empty when the tool was run by a sub-agent
}
ToolResult is the outcome of a tool execution, surfaced to the UI after the tool runs.
type WakeupRequest ¶
type WakeupRequest struct {
DelaySeconds int
Prompt string // payload to re-run on wake (slash command or prompt)
Reason string // one-line "what I'm waiting for", shown to the user
// Poll marks a wake-up whose only purpose is to poll background work already
// in flight (a sub-agent or shell job). Such a wake-up is auto-cancelled if
// that work finishes first, since the run is then resumed with the result
// automatically — leaving the poll tick to re-dispatch the finished task.
// Reminders and self-paced loop steps leave this false so they always fire.
Poll bool
}
WakeupRequest asks the host to re-engage the agent after a delay — an in-session reminder/cron the agent schedules for itself. In a self-paced loop, Prompt carries the task to repeat; the host re-resolves and re-runs it when the delay elapses.