tools

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 14, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const CodeRunTool = "code_run"

CodeRunTool is the tool name Compose adds, so callers can test an agent's filter for it.

View Source
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.

View Source
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.

View Source
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.

View Source
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

View Source
var ErrTooManyPending = errors.New("wake: too many pending wakes")

ErrTooManyPending is returned when the pending-wake cap is reached.

Functions

func Base

func Base(cfg Config) ([]agentkit.Tool, error)

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

func ChatID(ctx context.Context) string

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

func Compose(cage agentkit.ToolSet, allowCodeRun bool) (agentkit.ToolSet, error)

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

func HostMatch(pattern, host string) bool

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

func NetSuggestions(host string) []gate.Grant

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.

func WithChatID

func WithChatID(ctx context.Context, id string) context.Context

WithChatID stamps the current chat id onto ctx. The chat manager sets it when it creates a session, so a wake scheduled during that chat's turn resumes THAT chat — nothing is captured but the id string.

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

func New(secrets *secret.Injector, scanner *secret.Scanner) *Net

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

func (n *Net) SetLogger(l *slog.Logger)

SetLogger attaches the effect-trace logger (nil ignored). Call at construction, before the Net is shared across tool calls.

func (*Net) Tools

func (n *Net) Tools() ([]agentkit.Tool, error)

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

type Notification struct {
	Ws      string
	Kind    string
	ChatID  string
	Title   string
	Message string
}

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

func NewReminders(path string, notifier Notifier, scanner *secret.Scanner) *Reminders

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

func (r *Reminders) CancelByID(id string) bool

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

func (r *Reminders) List() []Reminder

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.

func (*Reminders) SetLogger

func (r *Reminders) SetLogger(l *slog.Logger)

SetLogger attaches a logger so a fire dropped by the re-scan is not silent. nil is ignored.

func (*Reminders) Tools

func (r *Reminders) Tools() ([]agentkit.Tool, error)

Tools exposes remind / remind_list / remind_cancel.

type Sessions

type Sessions interface {
	Open(id string) *agentkit.Session
}

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 Wake added in v0.3.0

type Wake struct {
	ID     string    `json:"id"`
	FireAt time.Time `json:"fireAt"`
	ChatID string    `json:"chatId"`
	Note   string    `json:"note"`
}

Wake is one scheduled self-continuation, persisted so it survives a restart.

It is persisted for the same reason a Reminder is, and the absence of that was a silent loss: a wake lived only in a time.AfterFunc, so a restart — or a workspace being closed and reopened — dropped every outstanding continuation with no log line and no error. The model had arranged to come back in ten minutes and simply never did, which reads as the model forgetting rather than as state being thrown away.

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.

Its store is a control-plane file OUTSIDE the model's file mount, exactly like the reminder store.

func NewWaker

func NewWaker(opts ...WakerOption) *Waker

NewWaker builds a Waker, reading any persisted wakes (tolerantly — a missing or malformed file is an empty store). Call Restore once Bind has run to arm them; Bind must be called before a wake can fire. The logger defaults to a no-op (never nil), so callers log unconditionally.

func (*Waker) Bind

func (w *Waker) Bind(s Sessions)

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).

func (*Waker) Cancel

func (w *Waker) Cancel()

Cancel stops every pending timer, leaving the wakes persisted to be re-armed by the next Restore — the same shutdown semantics as Reminders.Cancel.

func (*Waker) Pending

func (w *Waker) Pending() int

Pending reports how many wakes are scheduled but not yet fired.

func (*Waker) Restore added in v0.3.0

func (w *Waker) Restore()

Restore arms every persisted wake; one that came due while the process was down fires promptly (the delay is clamped to ≥0), the same catch-up Reminders.Restore does.

Call it AFTER Bind. An overdue wake fires as soon as its timer is armed, and firing consumes the wake — so arming before the lookup seam exists would drop exactly the wakes this persistence was built to keep.

func (*Waker) Tool

func (w *Waker) Tool() (agentkit.Tool, error)

Tool exposes wake to the model/scripts. It is ungated (schedules a continuation, reaches nothing external); the bounds are the runaway guard.

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.

func WithWakeStore added in v0.3.0

func WithWakeStore(path string) WakerOption

WithWakeStore persists pending wakes at path. An unset path is in-memory only (tests), which is the same bargain NewReminders offers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL