extract

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 24 Imported by: 1 module, 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 extract turns a Slack conversation window into items ledger ops through one agent call.

Index

Constants

View Source
const (
	// BreakerAfter consecutive failed calls open the breaker for BreakerCool; the next call is its trial.
	BreakerAfter = 3
	BreakerCool  = 15 * time.Minute
)
View Source
const (
	EventBreakerOpened      = "extract_breaker_opened"
	EventBreakerClosed      = "extract_breaker_closed"
	EventBreakerTrialFailed = "extract_breaker_trial_failed"
)

Breaker events, logged as they happen.

View Source
const (
	JobName = "extract:slack"
	// JobEvery is the backstop for a lost wake: a landing and each run say when the job next has work.
	JobEvery = 5 * time.Minute
	// JobRetry is the first wait after a failed pass.
	JobRetry = time.Minute
	// PassBudget is how long a pass starts new calls; a started call runs on, up to CallTimeout.
	PassBudget = 10 * time.Minute
	// CallTimeout bounds one extraction call.
	CallTimeout = 10 * time.Minute
	// JobTimeout bounds a pass: its budget, the last call it started, and the work after it.
	JobTimeout = PassBudget + CallTimeout + 2*time.Minute
)
View Source
const (
	SkipOff      = "slack extraction: off"
	SkipNoAgent  = "slack extraction: no agent answers headless calls"
	SkipNoLedger = "slack extraction: no items ledger"
	SkipRunning  = "slack extraction: a pass is running"
)

Skip texts of the job.

View Source
const (
	PromptFile      = "prompts/slack-extraction.md"
	BriefSchemaFile = "prompts/slack-brief.schema.json"
	CitedFile       = "prompts/slack-cited.md"
)

PromptFile, BriefSchemaFile and CitedFile are the extraction's prompt, its brief's schema and the block that holds the cited items, {{ITEMS}}, in the plugin's profile layer. Untrusted text is defused only of the block's lines that start with --, as written.

View Source
const (
	ContextHeading = "-- context, read only: earlier messages to understand what follows; extract nothing from them --"
	ContextEnds    = "-- end of context --"
	SegmentStarts  = "-- segment starts: extract only from here --"
	SegmentEnds    = "-- segment ends --"
)

Markers Render writes around the context and a segment.

View Source
const MaxPromptWords = 5725

MaxPromptWords caps the extraction prompt's template, counted as space-separated words.

Variables

This section is empty.

Functions

func ContextBefore

func ContextBefore(msgs []slack.Message, n, chars int) []slack.Message

ContextBefore is the newest of msgs, ascending, within n messages and chars of text.

func GoalOf

func GoalOf(stored string) string

GoalOf is the goal of a stored brief, empty for none.

func Ops

func Ops(in Input, r Result, team string, parse ParseTarget) (ops []items.Op, dropped int, err error)

Ops diffs r against in.Ledger: create, update, assign, resolve, reopen, link. A person is a Slack user ("slack:<id>", with an "email:<addr>" alias when the cache has one), a user group ("group:<id>") or a team named in the conversation ("group:<name>"); any other key is refused. A new item's id is "e<origin ts without its dot>", suffixed ".2", ".3"... while taken, so a retried run creates it once. An item the result omits gets no op. A cited item gets only an assign or a resolve, on its own unit, from a message by the viewer, its requester or an assignee; a link naming it, or any other op on it, is dropped and counted.

func Prompt

func Prompt(in Input) (string, error)

Prompt fills the extraction prompt for in; each placeholder is replaced once, so text in the conversation that looks like a placeholder stays as written.

func Render

func Render(in Input) string

Render is the conversation block; the eval uses it for every stage.

func TierFor

func TierFor(in Input, base host.Tier, over int) host.Tier

TierFor is the frontier tier when in renders longer than over, else base; over 0 never escalates.

func VocabularyOf

func VocabularyOf(v string) string

VocabularyOf is the vocabulary line of the prompt.

Types

type Clock

type Clock interface{ Now() time.Time }

Clock is the job's clock.

type Extra

type Extra struct {
	Schema   json.RawMessage
	Versions map[string]string
}

Extra is the brief intent's extra fields as an extraction asks them: the flat object schema and each field's version, which the stored brief keeps beside the values.

type Hint

type Hint struct{ Mode, Context, Why string }

type Input

type Input struct {
	Unit         unit.Unit
	Viewer       Viewer
	Now          time.Time // rendered with the configured zone's abbreviation
	Language     string    // the language of every text field, config plugins.slack.extraction.language
	Conversation slack.Conversation
	Messages     []slack.Message // the window, ascending; never cut inside a thread
	NewFrom      string          // first ts after the unit's cursor; "" means all are new
	Users        map[string]slack.User
	Ledger       []items.Item // the unit's current items, rendered by their own Item.ID
	Brief        string       // the unit's brief in use, as stored; the prompt reads its goal
	Vocabulary   string       // the tag vocabulary in use, tag.Vocabulary's lines
	Extra        *Extra       // the brief intent's extra fields every brief carries; nil asks none
	Contexts     []string     // placement contexts offered (context map keys)
	Segments     []slack.Span // a DM's current spans, ascending, rendered s1, s2...
	// Cited are the open items of other Slack units the window links to, by their own Item.ID,
	// none of which Ledger holds; an answer may only resolve or reassign them.
	Cited []items.Item
	// SegmentBriefs are the briefs in use of Segments, as stored, by index.
	SegmentBriefs []string
	WindowChars   int // Render cuts the oldest messages before NewFrom beyond it; 0 keeps all
	// Context are read-only messages before Messages, rendered c1, c2...: nothing is extracted from them.
	Context []slack.Message
	// Segment is the one DM segment the call covers, its bounds marked; zero for a whole conversation.
	Segment slack.Span
	Focus   string // the ts of the message the unit is about, marked focus
	// Prompts are the extraction's prompt and schemas, from the profile.
	Prompts *Prompts
}

type ItemOut

type ItemOut struct {
	Ref, Kind, Summary, Ask, OriginTS                                          string // Ref is an Item.ID of Input.Ledger, or "n<N>" for a new item
	Requester                                                                  PersonOut
	Assignees, WaitingOn                                                       []PersonOut
	AssignmentTS, AssignmentBasis, State, Resolution, EvidenceTS, EvidenceKind string
	Confidence, Ambiguity, Context, Deadline                                   string
	Links                                                                      []struct{ URL, Label string }
	Options                                                                    []struct {
		Option   string
		BackedBy []PersonOut
	}
	Mode  string                        // "none", "headless", "session"
	Place struct{ Context, Why string } // Context is one of Input.Contexts or ""
}

type Job

type Job struct {
	Facts    slack.FactsReader
	Segments slack.Segments
	Writer   slack.SegmentWriter
	// DM reads a DM conversation's messages with ts at or after from ("" all), ascending.
	DM func(ctx context.Context, conv, from string) ([]slack.Message, error)
	// DMBefore reads the newest n messages of a DM whose anchor is before ts, ascending; nil shows no context.
	DMBefore func(ctx context.Context, conv, before string, n int) ([]slack.Message, error)
	Ledger   Ledger
	Watcher  slack.Watcher
	Asker    host.Asker
	Parse    ParseTarget
	Store    Store
	Clock    Clock
	Cfg      func() config.Config
	Log      func(format string, args ...any)
	// Briefed hears of each unit whose brief a pass wrote; nil hears none.
	Briefed func(u unit.Unit)
	// PutBrief keeps a unit's brief in the host, before the pass saves its
	// cursor, so a crash between them reads the messages again; nil keeps
	// none.
	PutBrief func(ctx context.Context, u unit.Unit, brief string, at time.Time) error
	// Extra is the brief intent's extra fields' schema, which the brief of
	// every unit carries; nil asks for none.
	Extra func(ctx context.Context) (Extra, error)
	// Prompts reads the extraction's prompts from the profile, once a pass.
	Prompts func(ctx context.Context) (*Prompts, error)
	// contains filtered or unexported fields
}

Job is the plugin's job JobName: each pass reads the Slack changes since its cursor and extracts every unit whose changes are due, within the daily caps and the breaker.

func (*Job) Next added in v0.4.0

func (j *Job) Next() time.Time

Next is when the last run said the job next has work: the earliest pending target's quiet time, max wait or retry, never before the breaker's trial or a spent daily cap frees; zero when nothing waits.

func (*Job) Run

func (j *Job) Run(ctx context.Context) (summary, skipped string, err error)

Run is one pass.

func (*Job) Want

func (j *Job) Want(u unit.Unit) bool

Want asks the next run to read u's conversation, past quiet_for: true when it has changes left to read, so a brief of u is coming.

func (*Job) Warnings

func (j *Job) Warnings() []string

Warnings says the breaker is open, names the targets given up on in the last day and counts the calls that timed out in it when more than one did; passed to Metrics.Warn.

type Ledger

type Ledger interface {
	Apply(ctx context.Context, prov items.Provenance, ops []items.Op) (host.Result, error)
	Items(ctx context.Context, u unit.Unit) ([]items.Item, error)
	// All are the items of every unit of the plugin's, by unit.
	All(ctx context.Context) (map[unit.Unit][]items.Item, error)
}

Ledger is the host's items ledger as the job applies its ops.

type LinkOut

type LinkOut struct {
	Item, Target, EvidenceTS string    // Target: a URL or "<provider>:<key>" ("github:acme/widget#527")
	Kind                     link.Kind // "mention" | "review" | "merge"; the extraction prompt defines each
}

type ParseTarget

type ParseTarget func(target string) (unit.Unit, bool)

ParseTarget turns a LinkOut.Target into a unit through the registered codecs; false drops the link and counts it.

type PersonOut

type PersonOut struct{ ID, Name string }

ItemOut is the schema's item, v2 fields plus ref, mode and place. PersonOut is a person an answer names: a Slack user or user group by ID, else a team or role by Name; empty when nobody.

type Prompts

type Prompts struct {
	// contains filtered or unexported fields
}

Prompts are the extraction's prompt and brief schema as the profile holds them, and the schema an extraction answers to: the brief's schema under the conversation's brief and each segment's.

func LoadPrompts

func LoadPrompts(ctx context.Context, read func(ctx context.Context, path string) ([]byte, error)) (*Prompts, error)

LoadPrompts reads the prompts through read, the plugin's profile layer.

func NewPrompts

func NewPrompts(template, briefSchema, cited string) (*Prompts, error)

NewPrompts are the prompts of template, briefSchema and cited, the block of the cited items, which holds {{ITEMS}} once.

func (*Prompts) Schema

func (p *Prompts) Schema() string

Schema is the schema an extraction answers to, without the brief intent's extra fields.

type Reader

type Reader interface {
	States(ctx context.Context, units []unit.Unit) (map[unit.Unit]UnitState, error)
	Hints(ctx context.Context, u unit.Unit) (map[string]Hint, error) // by ledger item id
}

type Result

type Result struct {
	// Brief is the conversation's brief as stored, empty when the answer
	// keeps the brief it has.
	Brief                           string
	ViewerRole, Verdict, VerdictWhy string
	StartedByViewer, ClosurePosted  bool
	Items                           []ItemOut
	Segments                        []SegmentOut // DM conversations only
	Links                           []LinkOut
	// Dropped counts the items and links left out because they cite a message outside the window.
	Dropped int
	// ExtrasDropped counts the briefs kept without their extra fields
	// because those did not fit the brief intent's schema.
	ExtrasDropped int
}

func Extract

func Extract(ctx context.Context, a host.Asker, ask host.Ask, in Input) (Result, host.Answer, error)

Extract asks for in's result; ask carries Tier and MaxCostUSD. An answer that does not fit the schema, or names a ref, segment or link item in doesn't hold, fails with host.ErrUnfit; a new item, an item whose evidence or a link citing a message outside the window, the context's included, is dropped, and a brief whose extra fields do not fit is kept without them.

type SegmentOut

type SegmentOut struct{ Ref, FromTS, ToTS, Topic, Brief string }

SegmentOut: Ref "s<N>" names an existing segment, "new" mints one. Brief is the segment's brief as stored, empty when it keeps the one it has.

type Store

type Store struct {
	DB       *store.ExtractionStore
	Segments *store.SegmentStore
}

Store is the Reader over the store's extraction tables, plus the open segments of a DM.

func (Store) Hints

func (s Store) Hints(ctx context.Context, u unit.Unit) (map[string]Hint, error)

func (Store) States

func (s Store) States(ctx context.Context, units []unit.Unit) (map[unit.Unit]UnitState, error)

type UnitState

type UnitState struct {
	Brief, Verdict, VerdictWhy, ViewerRole, Topic string
	StartedByViewer, ClosurePosted                bool
	At                                            time.Time
}

UnitState is a unit's last extraction; Topic names a DM segment's topic.

type Viewer

type Viewer struct{ ID, Name string }

Jump to

Keyboard shortcuts

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