Documentation
¶
Overview ¶
Package tools bundles nocturn's own gated tools — the thin ones whose whole body is "build an agentkit.Tool that gates its target on a shared kind before it acts". They share only the gate model (each owns its own kind constant and target matcher), so they live together here rather than one sprawling package per tool. Heavier tools that carry their own runtime — code_run (QuickJS/wasm) and plugins — stay in their own packages; they just contribute agentkit.Tools that Base folds in the same way.
Index ¶
- Constants
- Variables
- func Base(cfg Config) ([]agentkit.Tool, error)
- func ChatID(ctx context.Context) string
- func Compose(cage agentkit.ToolSet, allowCodeRun bool) (agentkit.ToolSet, error)
- func HostMatch(pattern, host string) bool
- func NetSuggestions(host string) []gate.Grant
- func WithChatID(ctx context.Context, id string) context.Context
- type Config
- type Net
- type Notification
- type Notifier
- type Reminder
- type Reminders
- type Sessions
- type Waker
- type WakerOption
Constants ¶
const CodeRunTool = "code_run"
CodeRunTool is the tool name Compose adds, so callers can test an agent's filter for it.
const FileKind = "file"
FileKind is the shared gate Kind file MUTATIONS check; the Target is the workspace-relative, forward-slashed path. read/list/stat/search are observations — confined to the workspace Root but ungated (they prompt nobody, matching the old base policy where reads ran silently); write/remove/ move are mutations gated on this kind so they ask. Path matching (a "notes/*" grant covering that directory, path.Match's "*" not crossing "/") lives here with the tool that owns it.
const NetKind = "net"
NetKind is the shared gate Kind every network tool checks, so one host allowlist spans them all. The host-matching semantics (a "*.example.com" grant covering subdomains) live in this file, with the tool that owns them — the gate stays target-agnostic.
const NotifyKind = "notify"
NotifyKind is the gate Kind the notify tool checks. Its Target is the host-owned constant channel "user" — never model-chosen — so a policy can gate "reaching the user" without the model choosing a different destination. Under the base policy notify runs silently (Allowed); the gate is present so a stricter per-agent policy can tighten it to Ask.
const RemindKind = "remind"
RemindKind is the gate Kind the reminder tools check; like NotifyKind the Target is the host-owned "user" channel. Reminders run silently under the base policy (a reminder notifies the user, it does nothing else), but pass the gate so a stricter policy can tighten them.
Variables ¶
var ErrTooManyPending = errors.New("wake: too many pending wakes")
ErrTooManyPending is returned when the pending-wake cap is reached.
Functions ¶
func Base ¶
Base builds nocturn's base tools — the set every chat and agent draws from before a per-agent cage narrows it: the network tools (http_read/http_write/dns_resolve/ping), time_now, and — when a Root is given — the workspace-confined file tools. It grows as tools land (notify, …). Returned as a slice so the caller can both form the base ToolSet and scope per-agent subsets from it. code_run is NOT here: it is woven per cage by Compose, so a script's reach is bounded to the tools of its cage.
func ChatID ¶
ChatID returns the chat id carried by ctx, or "" — the exported accessor used for log correlation (the diagnostic logger's ctxHandler folds it into every line).
func Compose ¶
Compose finalizes one cage: the tools of `cage`, plus — only when allowCodeRun — a code_run whose script dispatches over EXACTLY those same tools and nothing more. This is the security seam for code_run: it can never widen authority beyond its cage. An agent caged to a subset that includes code_run reaches only that subset from a script too; an agent NOT granted code_run gets no interpreter at all. (code_run never dispatches itself — reentry is refused — nor sub-agent tools, which are layered on outside a cage.)
func HostMatch ¶
HostMatch reports whether a granted host pattern covers a target host: "*" any, an exact host, or a "*.domain" wildcard over that domain and its subdomains. Exported so other net-axis tools (e.g. the gated MCP transport) gate on the SAME allowlist with the SAME target semantics.
func NetSuggestions ¶
NetSuggestions offers the human one widening beyond the exact host: allow the whole parent domain. "api.example.com" -> a "*.example.com" grant. A bare "example.com" yields no widening. Exported alongside HostMatch so the MCP transport offers the same widening on the net axis.
Types ¶
type Config ¶
type Config struct {
Secrets *secret.Injector // host-owned credential jar the network tool injects from
Scanner *secret.Scanner // bidirectional secret leak scanner
Root string // workspace root; file tools are confined here (empty = no file tools)
Notifier Notifier // out-of-band user notification; nil = no notify tool
Waker *Waker // self-continuation scheduler; nil = no wake tool (caller Binds it to the chat manager)
Logger *slog.Logger // effect-trace (http request / path-escape); nil = silent. gate/scanner log their own events.
}
Config carries the per-workspace wiring the base tools need. Every field may be zero: a nil Secrets or Scanner disables credential injection or leak-scanning, an empty Root drops the file tools.
type Net ¶
type Net struct {
// contains filtered or unexported fields
}
Net is the gated HTTP tool group. It holds only transport plus a host-owned credential jar and a bidirectional leak scanner; authority is read from ctx by the gate. A bearer is injected host-side so the model (and any script/plugin behind it) never sees it, and the scanner blocks a secret the caller tries to smuggle OUT and redacts one echoed back IN.
func New ¶
New builds a Net with a bounded HTTP client, an optional credential injector and an optional leak scanner (nil = that feature off). The client re-gates every redirect hop (see checkRedirect): a 3xx is a fresh request to a possibly-different host, so it must clear the same host allowlist and egress scan as the original — otherwise a redirect is a gate/exfil bypass.
func (*Net) SetLogger ¶
SetLogger attaches the effect-trace logger (nil ignored). Call at construction, before the Net is shared across tool calls.
func (*Net) Tools ¶
Tools exposes the network tools. http_read and http_write are split so the tool the model (or a guest's fetch) picks IS the intent: safe methods go through http_read, mutating ones through http_write. Both return a JSON envelope {status, statusText, headers, body} so a caller sees the real outcome, not just a body (a 404 is not mistaken for success) — the same shape the prelude's fetch() reconstructs into a Response.
type Notification ¶
Notification is one proactive message to the user. Kind says which tool produced it (NotifyKind or RemindKind), Ws which workspace it came from, and ChatID the chat or agent run it originated in — together they let a device label it and open the conversation it came out of, instead of receiving an anonymous string. A reminder is rarely an end in itself ("remind me about the meeting" is usually followed by "what was it about"), so landing back in that chat is the useful destination. ChatID is empty when there is nothing to open. The model supplies only Title and Message.
type Notifier ¶
type Notifier interface {
Notify(ctx context.Context, n Notification) error
}
Notifier reaches the user out of band — a phone push, or the terminal. A nil Notifier means the notify tool is not offered at all.
Delivery is best-effort and must not block on the user: an implementation sends and returns, it never waits for an acknowledgement (that is what hitl is for). A non-nil error means the message reached NO device; it is not retryable here, and no implementation retries on its own — so a caller that cannot propagate it must log it rather than discard it. Reaching zero devices because none is registered is NOT an error (nothing failed), it simply returns nil.
type Reminder ¶
type Reminder struct {
ID string `json:"id"`
FireAt time.Time `json:"fireAt"`
Message string `json:"message"`
Title string `json:"title,omitempty"`
ChatID string `json:"chatId,omitempty"`
}
Reminder is one scheduled notification, persisted so it survives a restart. ChatID is the chat it was set in, captured at creation because a fire has no ctx to read it from — it is what lets a tap on the delivered notification land back in the conversation that asked for it. Empty when the reminder was set outside any chat.
type Reminders ¶
type Reminders struct {
// contains filtered or unexported fields
}
Reminders is the persistent reminder tool group: it owns a JSON-file store and one time.AfterFunc per pending reminder. A fire delivers a plain notification through the Notifier — it never runs the model. The store is a control-plane file OUTSIDE the model's file mount, load-bearing like grants.
func NewReminders ¶
NewReminders opens (tolerantly — a missing or malformed file is an empty store) a reminder store at path, delivering fires through notifier. Call Restore once after construction to enroll the persisted reminders. An empty path is in-memory only (tests).
func (*Reminders) Cancel ¶
func (r *Reminders) Cancel()
Cancel stops every pending timer (leaving the reminders persisted, to be re-enrolled next start).
func (*Reminders) CancelByID ¶
CancelByID drops a pending reminder and stops its timer, reporting whether it existed. It is the host-side cancel (the companion app); the model cancels through the remind_cancel tool.
func (*Reminders) List ¶
List returns the pending reminders, soonest first. A fired reminder is gone (fire removes it), so this is the pending set, never a history. It backs both the model's remind_list tool and the companion app's listing.
func (*Reminders) OnChange ¶
func (r *Reminders) OnChange(fn func())
OnChange registers the callback run after the pending set changes (a create, a cancel, a fire), so a listing UI can refresh without polling. Set once, at wiring time, before serving. The callback runs OUTSIDE r.mu — it may call back into List.
func (*Reminders) Restore ¶
func (r *Reminders) Restore()
Restore enrolls every persisted reminder; overdue ones fire promptly (the delay is clamped to ≥0). Call it once after NewReminders.
type Sessions ¶
Sessions is the wake tool's lookup seam: resolve a chat by id to its live session. chat.Manager satisfies it via its existing Open (which re-opens a reaped chat). Defined here so tools does not import chat — chat imports tools for the ctx carrier, not the other way around.
type Waker ¶
type Waker struct {
Min, Max time.Duration
MaxPending int
// contains filtered or unexported fields
}
Waker schedules self-wakes for whichever chat invoked wake. Min/Max clamp the delay; MaxPending caps concurrent pending wakes (zero values fall back to 1s / 1h / 3). It holds the Sessions seam (bound after the manager exists, see Bind) and resolves the firing chat by id — so one workspace-shared Waker serves every chat.
func NewWaker ¶
func NewWaker(opts ...WakerOption) *Waker
NewWaker builds a Waker. Bind must be called (once the manager exists) before a wake can fire; the logger defaults to a no-op (never nil), so callers log unconditionally.
func (*Waker) Bind ¶
Bind wires the chat-lookup seam. It is called at workspace assembly, after the manager exists but before any turn (so no wake can fire before it is set).
type WakerOption ¶
type WakerOption func(*Waker)
WakerOption configures a Waker.
func WithWakeLogger ¶
func WithWakeLogger(l *slog.Logger) WakerOption
WithWakeLogger sets the diagnostic logger — a wake firing is otherwise invisible. A nil logger is ignored (the no-op default stays), so callers never produce a nil logger.