sidequestion

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: AGPL-3.0 Imports: 15 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.

README

ScopeWeaver /btw

한국어

Ordinary chat, a task's MainAgent, and Workers belonging to the current task support independent side questions. Enter /btw question in the main input to submit; an empty /btw or the side-question button opens history. Desktop uses a resizable sidebar, while mobile uses a Drawer.

Answers use the agent context snapshot at submission and support streaming, follow-ups, stopping and clearing. Closing the panel, refreshing or disconnecting SSE does not cancel the model request. Stop affects only the current side question. Clear cancels it and deletes side-question history while retaining the main context snapshot.

Implementation boundaries

The upstream implementation used Go, norma v0.3.7, Next.js and existing Markdown / ResizablePanel / Drawer / AlertDialog components, without changing norma source or adding a side-question dependency. Planner support, Workers inherited from other tasks and tool-subtask upgrades were outside its scope. Dependency versions may have advanced since that implementation.

flowchart LR
    A[Main agent QueryDeps] --> B[Actual provider binding]
    B --> C[Immutable structured snapshot]
    B --> D[Normal main-agent tool loop]
    C --> E[(Latest PostgreSQL snapshot)]
    E --> F[Snapshot + recent successful side exchanges + question]
    F --> G[SideQuestionService provider request]
    G --> H[(Separate side history and usage)]
    H --> I[Cumulative-answer SSE / side panel]
  • capture.go marks main-loop requests only in Options.Deps.CallModel / CallModelSync. The provider decorator sits inside the concrete model after outer pool routing, so it records the actual selected model. Compaction and summary requests do not overwrite snapshots.
  • Snapshots publish at request start, complete model response and terminal run state. Partial responses are excluded. norma's MessagesForAPI keeps tool calls paired; results enter the snapshot at the next main-model request or terminal state. Interrupted streams retain the last valid boundary.
  • JSON deep copies preserve structured messages, system instructions, tool definitions and generation parameters. Model inference holds neither snapshot locks nor database transactions.
  • SideQuestionService calls the concrete provider and summarizes first if needed. The final answer may shrink context and retry once only after its first context-overflow error and before any text/tool-call output. It creates no agent session and connects to no tool executor, main transcript, activity stream, task graph or task-model switching chain. Answer requests keep tool definitions for existing structured tool context; summary requests omit tools. New tool calls have no execution path.
  • Each parent session allows one running request; each service process allows four, with a 120-second request timeout. Side questions have independent cancellation contexts under the service lifecycle.
  • Requests retain a model-profile reference and a nonsensitive identity digest; credentials come from the current profile at request time. If the profile is deleted or identity fields such as model, protocol or address change, run the main agent to refresh its snapshot. Tests do not change the product's default model.

Persistence and recovery

db/schema.sql creates side_question_sessions and side_question_requests. Sessions store the parent resource, latest snapshot, run ID, version and clear version. Requests store the question, cumulative answer, status, model, snapshot time, usage, event sequence and pagination ordinal.

Parent keys use conversation ID, or task ID + exploration ID + intent ID. Workers do not use reusable execution-slot names.

Snapshot writes coalesce per parent and flush every 250 ms. The database compares (run_id, version) to reject stale writes. The selected snapshot is saved again before side-question submission. Successful saves release the large in-memory snapshot; failures retain the pending version. Cumulative streaming answers write at most every 250 ms. Terminal states save immediately with bounded retries on database errors.

Startup marks leftover running requests interrupted, retaining saved partial answers and usage without replaying requests. The latest successfully saved context can answer the next question directly. Old sessions without a snapshot require running the main agent first; context is not reconstructed from UI activity logs.

Clear increments the clear version and deletes requests; conditional updates reject late callbacks. Physical parent deletion uses foreign-key cascades. Logical Worker deletion removes side data in the same transaction and rejects later snapshots. Task archiving first blocks new requests, waits for the main flow to stop, cancels side requests and waits for persistence. Archive v3 also supports v1/v2 without side-question tables.

Full history is retained and paginated by ordinal, up to 20 records per page. Model requests replay at most 20 recent successful exchanges, further constrained by token budget. Older exchanges have a separate rolling summary. If the main context is too large, only the older part of the side copy is summarized, keeping recent structured tool calls/results. Summaries, preparation and usage share side-question concurrency, cancellation and the 120-second timeout. See context budgets and upstream references.

HTTP contract

These existing authenticated and resource-checked paths act as {parent}:

  • /api/conversations/{id}
  • /api/tasks/{id}/chat
  • /api/tasks/{id}/intents/{iid}
Request Response and behavior
GET {parent}/side-questions?before={ordinal} Newest-first items, separate running current, snapshot metadata, next_cursor; 0 means newest page / no next page
POST {parent}/side-questions JSON { "question": "…", "client_request_id": "UUID" }; new requests return 202 and request object; identical ID/question returns existing object with 200
DELETE {parent}/side-questions Cancel and clear this parent's side questions
GET /api/side-questions/{requestID}/events snapshot SSE events: increasing sequence id, complete cumulative request object in data; clear sends cleared
POST /api/side-questions/{requestID}/cancel Explicit cancellation; read terminal state through history or SSE

Questions are limited to 4000 characters. Missing snapshots, changed profiles, busy parents and conflicting idempotency IDs return 409; the global concurrency limit returns 429. Every SSE connection starts with cumulative state rather than depending on previously received fragments. The frontend merges by request ID + sequence and discards old callbacks when switching parents or clearing.

Verification and references

VALIDATION.md records upstream automated checks, actual model use and known limits. These historical receipts are not fresh ScopeWeaver test results.

Independent requests reference Grok CLI side-question.ts at a fixed commit; execution isolation references OpenCode at a fixed commit. ARTEX used norma's structured messages rather than reconstructing text from frontend logs; ScopeWeaver retains that implementation.

Documentation

Overview

Package sidequestion captures immutable main-agent checkpoints. It never owns an agent session or a tool executor.

Index

Constants

View Source
const DefaultOutputTokens = 8192
View Source
const MaxRecentExchanges = 20

Variables

View Source
var ErrContextBudget = locale.NewError("Side-question context still exceeds the model budget after compaction; narrow the question or adjust the model context configuration")

Functions

func Attach

func Attach(ctx context.Context, parent Parent, deps harness.QueryDeps, provider llm.Provider) (context.Context, harness.QueryDeps)

Attach uses QueryDeps rather than a global provider hook so compaction and other auxiliary completions cannot replace the main conversation checkpoint.

func Bind

func Bind(inner llm.Provider, model Model) llm.Provider

Bind belongs immediately around a concrete provider, inside any routing pool.

func BuildRequest

func BuildRequest(s Snapshot, history []Exchange, question string) (llm.CompletionRequest, error)

func EstimateInputTokens

func EstimateInputTokens(req llm.CompletionRequest) int

EstimateInputTokens follows norma's byte-based block estimate with its 4/3 safety factor. Include system/schema and framing costs too; JSON characters are not tokens (and marshaling HTML can add many non-semantic escapes).

func Finish

func Finish(ctx context.Context, messages []llm.Message)

Finish adds tool results that landed after the final model request. Norma's first API message is its host reminder, absent from Terminal.Messages.

func WithHistory

func WithHistory(ctx context.Context, revision int64, runID string) context.Context

func WithPublisher

func WithPublisher(ctx context.Context, publish Publisher) context.Context

func WithRequestObserver

func WithRequestObserver(ctx context.Context, observer RequestObserver) context.Context

func WithWorkingSetProjector

func WithWorkingSetProjector(ctx context.Context, project func(context.Context, []llm.Message) []llm.Message) context.Context

Types

type Answer

type Answer struct {
	Text    string
	Usage   llm.Usage
	ToolUse bool
}

type Capture

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

type ContextInfo

type ContextInfo struct {
	Phase                string `json:"phase,omitempty"`
	RecentExchanges      int    `json:"recent_exchanges"`
	HistorySummarized    bool   `json:"history_summarized"`
	SnapshotSummarized   bool   `json:"snapshot_summarized"`
	EstimatedInputTokens int    `json:"estimated_input_tokens,omitempty"`
	InputBudget          int    `json:"input_budget,omitempty"`
	OutputTokens         int    `json:"output_tokens,omitempty"`
	OverflowRetried      bool   `json:"overflow_retried,omitempty"`
}

type ContextOptions

type ContextOptions struct{ OutputTokens int }

type Exchange

type Exchange struct {
	HistoryRevision int64       `json:"history_revision"`
	SourceRunID     string      `json:"source_run_id,omitempty"`
	ID              string      `json:"id"`
	SessionKey      string      `json:"-"`
	ClientID        string      `json:"client_request_id"`
	Generation      int64       `json:"-"`
	Question        string      `json:"question"`
	Answer          string      `json:"answer"`
	Status          string      `json:"status"`
	Error           string      `json:"error,omitempty"`
	Model           Model       `json:"model"`
	SnapshotAt      time.Time   `json:"snapshot_at"`
	CreatedAt       time.Time   `json:"created_at"`
	Sequence        int64       `json:"sequence"`
	Usage           llm.Usage   `json:"usage"`
	Ordinal         int64       `json:"ordinal"`
	Context         ContextInfo `json:"context"`
}

func (Exchange) Running

func (e Exchange) Running() bool

type Memory

type Memory struct {
	History         string `json:"history,omitempty"`
	Through         int64  `json:"through,omitempty"`
	SnapshotKey     string `json:"snapshot_key,omitempty"`
	SnapshotSummary string `json:"snapshot_summary,omitempty"`
	TailStart       int    `json:"tail_start,omitempty"`
}

Memory is independent of the main snapshot. Through is a persisted ordinal, not an array offset; restart, pagination and failed requests cannot shift it.

type Model

type Model struct {
	ProfileID    int64  `json:"profile_id"`
	Name         string `json:"name"`
	Format       string `json:"format"`
	Model        string `json:"model"`
	Identity     string `json:"identity"`
	Streaming    bool   `json:"streaming"`
	WindowTokens int    `json:"window_tokens"`
}

Model contains only configuration identity, never credentials or proxy URLs.

type Parent

type Parent struct {
	MainSeg        *int  `json:"main_seg,omitempty"`
	ConversationID int64 `json:"conversation_id,omitempty"`
	TaskID         int64 `json:"task_id,omitempty"`
	ExplorationID  int64 `json:"exploration_id,omitempty"`
	IntentID       int64 `json:"intent_id,omitempty"`
}

func (Parent) Key

func (p Parent) Key() string

type Publisher

type Publisher func(Snapshot)

type Replay

type Replay struct {
	Memory Memory
	Load   func(context.Context, int64) ([]Exchange, error)
	Save   func(context.Context, Memory) error
}

Load returns ascending completed exchanges after the cursor, in bounded pages, restricted to ordinals before this request. Save must reject writes after a clear/delete/cancel using the admitted request's generation.

type RequestEvent

type RequestEvent struct {
	Request       llm.CompletionRequest
	AnchorRequest llm.CompletionRequest
	Model         Model
	Usage         llm.Usage
	Source        string
}

RequestEvent observes only main requests selected by QueryDeps. Usage belongs to AnchorRequest; Request may additionally include newly generated messages.

type RequestObserver

type RequestObserver func(context.Context, RequestEvent)

type SideQuestionService

type SideQuestionService struct{ Provider llm.Provider }

SideQuestionService has no harness, tool executor, transcript writer or model failover chain. Answer is one completion; Respond adds bounded preparation and at most one context-overflow recovery around that completion.

func (SideQuestionService) Answer

func (s SideQuestionService) Answer(ctx context.Context, req llm.CompletionRequest, streaming bool, update func(Answer)) (out Answer, err error)

func (SideQuestionService) Respond

func (s SideQuestionService) Respond(ctx context.Context, snapshot Snapshot, question string, replay Replay, options ContextOptions, update func(Answer, ContextInfo)) (out Answer, info ContextInfo, err error)

Respond owns preparation and at most one overflow recovery. No tools, main transcript or model-failover chain are introduced by the summary calls.

type Snapshot

type Snapshot struct {
	HistoryRevision int64                 `json:"history_revision,string"`
	SourceRunID     string                `json:"source_run_id,omitempty"`
	Parent          Parent                `json:"parent"`
	RunID           int64                 `json:"run_id"`
	Version         int64                 `json:"version"`
	CapturedAt      time.Time             `json:"captured_at"`
	Model           Model                 `json:"model"`
	Request         llm.CompletionRequest `json:"request"`
}

Jump to

Keyboard shortcuts

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