web

package
v0.0.232 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 18 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

DSH Web sessions as a Go library

Import github.com/xhd2015/agent-pro/agent/dsh/web (usually aliased as dshweb). This package does not execute agent-run, dsh, iTerm, a shell script, or a TTY readiness probe. It talks to an already-running DSH Web service and uses the OS browser opener. Optional model/reasoning overrides initialize only the new session; they never save DSH global defaults.

High-level lifecycle

service := dshweb.Service{
    Client: dshweb.Client{}, // DSH_HOME/web-listen.json, or ~/.dsh
    Store: dshweb.FileStore{
        Dir: "/application/chosen/session-state",
        FileName: "runner-binding.json", // optional; default is session.json
    },
}

result, err := service.OpenSession(ctx, dshweb.SessionOptions{
    Key: "business-conversation-123",
    Workspace: "/workspace",
    Browser: "brave", // empty = system default
    Prompt: "Read the playbook and help with this task.",
})
// Handle err first. result.Accepted means input/draft admission, not task completion.
// Present result.Warnings separately: a browser failure after input admission
// must NOT cause the application to redeliver its message.
_ = result
_ = err

result, err = service.Send(ctx, dshweb.SendOptions{
    Key: "business-conversation-123",
    Prompt: "Here is the next message.",
})

// Focus / reopen: no creation and no prompt submission (including pending input).
result, err = service.Open(ctx, "business-conversation-123")
Operation Contract
OpenSession Reserve a provider identity, create/reuse the session, admit the initial prompt once, and automatically open its browser once unless suppressed. Repeated calls preserve pinned workspace/browser/initial model and do not resubmit admitted initial input. An empty prompt permits a blank session.
Send Require an existing binding, settle any interrupted input with its original request ID, then admit the next message. Never automatically pop a browser.
Open Open an existing, created session only. Never create a session or submit/retry pending input.

NoSubmit stores a composer draft instead of submitting a model turn. NoOpen on OpenSession suppresses automatic browser opening for that call without affecting admission. Browser: BrowserNone ("none") instead pins automatic opening off for the conversation, including retries and restarts. Creation, model selection and prompt submission still run normally; successful admission returns Accepted: true and BrowserOpened: false, without a browser warning. Do not use NoSubmit for background execution. Empty/omitted browser still means the system default.

result, err := service.OpenSession(ctx, dshweb.SessionOptions{
    Key: conversationID, Workspace: workspace, Prompt: prompt,
    Browser: dshweb.BrowserNone,
})

Service.Open is an explicit user action: a BrowserNone binding opens in the system default browser without changing its pinned preference or delivering input. Low-level Client.Open(id, BrowserNone) is a no-op and does not discover the server or call an OS opener. Other supported browser names are brave, chrome, firefox, edge, safari and opera; NormalizeBrowser/IsRunner are reusable validation helpers. Background sessions still require a running DSH Web service and can wait for human approval. This policy does not disable browser-automation tools used by the agent.

Live models and Session-only overrides

Client.ModelCatalog(ctx) calls session/modelCatalog without creating a session, opening a browser or changing configuration. It retains Default, provider Groups, each model's Reasoning.Efforts/DefaultEffort, model Unavailable reasons, and isolated provider Failures. Keep (provider, model) together: two providers may advertise the same model id. A model with a non-empty Unavailable reason must not be offered as selectable. Effort ids are adapter-owned strings, not a fixed Codex enum. A partial failure does not erase the healthy groups.

Pass the selected values in SessionOptions.ModelSelection:

options.ModelSelection = &dshweb.ModelSelection{
    Provider: providerID,
    Model: modelID,
    ReasoningEffort: effortID, // empty follows this model's adapter default
}
result, err := service.OpenSession(ctx, options)

A nil selection preserves the existing DSH-default behavior. A new binding saves its initial selection before creation, and the Host's accepted response before sending input. The optional initial_model_selection field uses the existing binding file; no separate mapping is introduced. Restarts and creation retries use that binding, not later application preferences. Send, pure Open, and repeated OpenSession never reapply a new preference to an existing session. The DSH Session log remains authoritative after a user changes its model in DSH.

Client.CreateWithOptions is the low-level equivalent; existing Client.Create callers keep their unchanged default behavior. An explicit override requires a Host that accepts and echoes session/create.modelSelection. A missing/mismatched echo stops before prompt or browser delivery rather than silently using the wrong model or calling the globally mutating session/selectModel. An older Host may already have created a blank session; update it and retry with the same reserved identity. Incomplete provider/model pairs fail before binding reservation; DSH validates live model and effort availability before installing the choice.

Ownership and recovery

The application owns business-to-key mapping, runner selection, prompt formatting, preferences, and the state root. The service owns provider IDs, pending request IDs/input, creation/admission checkpoints, browser-opening bookkeeping and retry sequencing. Applications must not share one key between different conversations.

FileStore keeps <Dir>/<Key>/<FileName> and a sibling lock file. Writes use an owner-only temporary file, file sync and atomic rename. The filesystem lock spans all intermediate checkpoints and RPCs, serializing distinct service objects and processes. Waiting for the lock respects context cancellation. No global application home or package-global session registry is used.

The Store / Record interfaces also support application-owned persistence. WithSession implementations must serialize one key and Record.Save must commit an intermediate checkpoint immediately, not defer all writes until callback exit. Read observes the last atomic checkpoint without waiting for a network operation.

Flat legacy Marcus records are compatible without conversion: dsh_session_id, created, initial_delivered, browser_opened, and pending fields keep their names. Unknown application metadata survives writes. Non-DSH runner pins and corrupt records fail closed instead of being rebound to a new provider session. Launch tokens are discovered per operation and never stored in session state. Confirmed pending input is removed from the durable checkpoint.

A browser failure after admission yields browser_open_failed in Warnings and no delivery error. A browser-bookkeeping write failure similarly yields browser_checkpoint_failed. Pure Open failures return an error because there was no input admission to distinguish. Transport/checkpoint failures leave the last committed request ID available for retry. No error falls back to a terminal.

Client remains available for consumers that already own equivalent session orchestration; prefer Service to avoid duplicating lifecycle and recovery logic.

Run status

Client.Status asks the daemon's session/status RPC which Sessions are executing a turn. It is the truth a UI needs for an activity light, and it is different from "loaded": a daemon keeps a lease on every Session it loaded, so a process lease alone cannot tell a thinking Session from an idle one.

running, err := client.Status(ctx, nil)          // every loaded Session
running, err = client.Status(ctx, []string{id})  // just one

An id is absent from the result when the daemon never loaded that Session, denies it to the caller, or does not know it — a Session opened by a plain dsh TUI is not in the daemon's registry. Absence means unknown, not idle.

RunStatus wraps Status into the per-Session liveness hook that agent/sessionactivity reads, caching one batch answer per TTL:

sessionactivity.SetDefaultRunStatus(dshweb.NewRunStatus(dshweb.Client{}).Running)

The hook is consulted only for DSH Sessions, and only to decide "running". It must never be installed for a different daemon than the one that loaded the Session, because a Session ID is answered only by its own daemon. A failed refresh reports unknown for everything instead of replaying a stale answer. The activity reader does not fall back to the process lease on session.lock.

Verification

go test -race ./agent/dsh/web -count=3
go test ./agent/dsh/... ./pkgs/agentruncli

Coverage includes restart/reuse, pinned preferences, drafts, pure reopen, ambiguous delivery deduplication, recovery before newer input, browser warnings, failed checkpoint writes, legacy state, validation, lock cancellation, concurrent instances, and a sparse multi-process test using test binaries (no real browser or model invocation). The library prints no application-specific logs.

Documentation

Overview

Package web controls sessions on a running DSH Web instance. Unlike the one-shot CLI handoff, callers can persist a session ID before submitting input and reuse it for follow-ups and browser-launch retries.

Index

Constants

View Source
const BrowserNone = "none"

BrowserNone disables automatic session-window opening while retaining normal session creation and prompt delivery. It is a persisted browser preference.

View Source
const DefaultRunStatusTTL = time.Second

DefaultRunStatusTTL bounds how stale a cached run-status answer may be. The daemon answers every loaded Session in one round trip, so a short window collapses a burst of per-Session lookups into one RPC while still following a turn that starts or ends within the second.

View Source
const Runner = "dsh-web"

Variables

This section is empty.

Functions

func IsRunner

func IsRunner(runner string) bool

IsRunner accepts the UI alias as well as the canonical transport name.

func NormalizeBrowser

func NormalizeBrowser(raw string) (string, error)

Types

type Client

type Client struct {
	Home        string
	ReadListen  func() (Listen, error)
	HTTPClient  *http.Client
	OpenBrowser func(rawURL, browser string) error
}

Client has injectable transport/discovery/opener boundaries for in-process tests. Its zero value uses DSH_HOME (or ~/.dsh), a bounded HTTP client, and the OS opener.

func (Client) Create

func (c Client) Create(ctx context.Context, directory, sessionID string) (string, error)

Create registers a workspace and an empty session under a caller-persisted identity. A retry can reuse that blank session. No prompt is submitted and no browser is opened: the caller must durably save the returned ID first.

func (Client) CreateWithOptions

func (c Client) CreateWithOptions(ctx context.Context, opts CreateOptions) (CreatedSession, error)

CreateWithOptions initializes a reserved session and verifies the Host accepted an explicit model before any caller can submit input or open the browser.

func (Client) Fork added in v0.0.220

func (c Client) Fork(ctx context.Context, opts ForkOptions) (string, error)

Fork creates a child session and returns its ID. It neither seeds a draft nor opens a browser; agent/dsh/fork composes both so the child can be reviewed before its first turn.

func (Client) ModelCatalog

func (c Client) ModelCatalog(ctx context.Context) (ModelCatalog, error)

ModelCatalog reads the live registry through the existing authenticated Web API. Provider failures are data, not a reason to discard healthy groups.

func (Client) Open

func (c Client) Open(sessionID, browser string) error

Open opens the existing session, or does nothing for BrowserNone without discovering the server or invoking the OS opener. Service.Open is the explicit manual-opening operation. Opener errors redact the authenticated URL.

func (Client) Send

func (c Client) Send(ctx context.Context, sessionID, requestID, text string, noSubmit bool) error

Send queues a prompt (or stores a draft). A caller-supplied requestID is reused across retries so an ambiguous transport failure does not enqueue twice.

func (Client) SessionModel added in v0.0.228

func (c Client) SessionModel(ctx context.Context, sessionID string) (SessionModel, error)

SessionModel reads session/projections and returns only modelSelection.

func (Client) SetDraft added in v0.0.220

func (c Client) SetDraft(ctx context.Context, sessionID, text string) error

SetDraft stores text in the session composer without submitting a turn, so a caller can hand a prepared prompt to the operator for review. It is the transport behind Send(noSubmit) and the seeding step of a fork.

func (Client) Status added in v0.0.225

func (c Client) Status(ctx context.Context, ids []string) (map[string]bool, error)

Status asks the daemon which Sessions are executing a turn.

A nil ids asks about every Session the daemon has loaded; an empty slice asks about none. An id is absent from the result when the daemon never loaded it, denies it to this caller, or does not know it, so absence means unknown here rather than idle — a Session opened by a plain `dsh` TUI is not in the daemon's registry at all.

type CreateOptions

type CreateOptions struct {
	Workspace      string
	SessionID      string
	ModelSelection *ModelSelection
}

CreateOptions describes a reserved blank session. ModelSelection, if present, initializes only this session; it never calls session/selectModel.

type CreatedSession

type CreatedSession struct {
	SessionID      string          `json:"sessionId"`
	ModelSelection *ModelSelection `json:"modelSelection,omitempty"`
}

CreatedSession echoes the Host's installed initial selection when requested. The echo prevents an older Host silently ignoring an explicit override.

type FileStore

type FileStore struct {
	Dir      string
	FileName string
}

FileStore uses <Dir>/<key>/<FileName>. The caller chooses Dir; there is no implicit Marcus, agent-run, or global home. An empty FileName means session.json. Existing flat binding records remain readable, including non-DSH runner pins.

func (FileStore) Read

func (s FileStore) Read(ctx context.Context, key string) (State, bool, error)

func (FileStore) WithSession

func (s FileStore) WithSession(ctx context.Context, key string, fn func(Record) error) error

WithSession holds a filesystem lock across network operations AND intermediate saves. Distinct Service/FileStore objects and separate processes share the same lock; an OS-released lock is not mistaken for a completed checkpoint.

type ForkOptions added in v0.0.220

type ForkOptions struct {
	// SessionID is the fork source and is required.
	SessionID string
	// AtSeq is the inclusive cut; 0 lets the Host keep the latest completed turn.
	AtSeq int64
	// Cwd is the child checkout. It must be fully qualified: the Host matches it
	// against its workspace registry and silently keeps the source for an
	// unknown directory, so callers verify the returned child.
	Cwd string
}

ForkOptions describes a child conversation seeded from another session. The Host copies the source transcript up to AtSeq and starts the child in Cwd.

type Listen

type Listen struct {
	Origin string `json:"origin"`
	Token  string `json:"token,omitempty"`
}

Listen contains discovery credentials. Never persist or log Token in a consumer's session binding; read the current record on each operation.

type ModelCatalog

type ModelCatalog struct {
	Default           ModelSelection        `json:"default"`
	RoutableProviders []string              `json:"routableProviders"`
	Groups            []ModelProviderGroup  `json:"groups"`
	Failures          []ModelCatalogFailure `json:"failures"`
}

ModelCatalog describes this running DSH deployment, including partial failures. A listed model is selectable only when Unavailable is empty. Listing does not create a session, open a browser, or save global/default configuration.

type ModelCatalogFailure

type ModelCatalogFailure struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Message string `json:"message"`
}

type ModelCatalogModel

type ModelCatalogModel struct {
	ID          string          `json:"id"`
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Reasoning   *ModelReasoning `json:"reasoning,omitempty"`
	Unavailable string          `json:"unavailable,omitempty"`
}

type ModelProviderGroup

type ModelProviderGroup struct {
	ID     string              `json:"id"`
	Name   string              `json:"name"`
	Models []ModelCatalogModel `json:"models"`
}

type ModelReasoning

type ModelReasoning struct {
	Efforts       []ModelReasoningEffort `json:"efforts"`
	DefaultEffort string                 `json:"defaultEffort,omitempty"`
}

type ModelReasoningEffort

type ModelReasoningEffort struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

type ModelSelection

type ModelSelection struct {
	Provider        string `json:"provider"`
	Model           string `json:"model"`
	ReasoningEffort string `json:"reasoningEffort,omitempty"`
}

ModelSelection identifies an exact DSH provider route. Empty ReasoningEffort follows that model's adapter default; it is not a Codex effort alias.

type Record

type Record interface {
	Load() (State, bool, error)
	Save(State) error
}

Record permits multiple durable checkpoints while its store holds a session lock. Implementations must leave the last committed checkpoint intact on error.

type Result

type Result struct {
	SessionID     string
	Created       bool // a provider session was created during this operation
	Accepted      bool // submitted input or a draft was accepted (not agent completion)
	BrowserOpened bool // this operation opened a browser
	Warnings      []Warning
}

Result distinguishes input admission from browser opening. A browser failure after admission is a warning, not a delivery error. Libraries never print logs.

type RunStatus added in v0.0.225

type RunStatus struct {
	Client Client
	TTL    time.Duration
	// Timeout overrides how long one status RPC may take. Zero uses
	// runStatusTimeout.
	Timeout time.Duration
	// Now overrides the clock in tests. Nil uses time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

RunStatus is the liveness hook a phase reader installs: Running reports whether one Session is executing a turn, and whether the daemon could answer at all.

It is shaped to match sessionactivity.RunStatus without importing it, so the activity package keeps its dependency-free contract and this package stays transport-only. Install it with sessionactivity.SetDefaultRunStatus.

One RPC per TTL covers every Session, because the daemon's answer is batch. A failed refresh reports unknown for everything instead of replaying the last good map: a dead daemon must degrade to the caller's process-lease liveness, never to a stale "running".

func NewRunStatus added in v0.0.225

func NewRunStatus(client Client) *RunStatus

NewRunStatus returns the hook for one DSH web instance, refreshing at most once per DefaultRunStatusTTL.

func (*RunStatus) Lookup added in v0.0.229

func (r *RunStatus) Lookup(sessionID string) (running, present, answered bool)

Lookup is the session/status answer for one id: whether the RPC succeeded, whether the id was in the map, and whether that entry is running.

func (*RunStatus) Running added in v0.0.225

func (r *RunStatus) Running(sessionID string) (running bool, known bool)

Running reports whether the daemon's registry has sessionID executing a turn. known is true only when the RPC succeeded and named this id.

type SendOptions

type SendOptions struct {
	Key      string
	Prompt   string
	NoSubmit bool
}

type Service

type Service struct {
	Client Client
	Store  Store
}

Service owns DSH Web session lifecycle. It never starts a terminal, agent-run, dsh CLI, or readiness probe. Client transport and Store are independently injectable; separate services using the same Store share durable checkpoints.

func (Service) Open

func (s Service) Open(ctx context.Context, key string) (result Result, err error)

Open only opens an existing, created DSH session. A BrowserNone binding uses the system default browser for this explicit action without changing its pin. It never creates a provider session, submits/retries pending input, or consults a terminal runner.

func (Service) OpenSession

func (s Service) OpenSession(ctx context.Context, opts SessionOptions) (Result, error)

OpenSession creates/reuses a caller-keyed DSH conversation, admits its first input once, and opens the selected browser unless NoOpen or BrowserNone. Repeated calls do not resubmit an admitted initial prompt. Use Send for a subsequent message.

func (Service) Send

func (s Service) Send(ctx context.Context, opts SendOptions) (Result, error)

Send admits a follow-up to an existing binding and never opens a browser. An interrupted initial input is settled first with its original request ID.

type SessionModel added in v0.0.228

type SessionModel struct {
	Next     *ModelSelection `json:"next"`
	LastUsed *ModelSelection `json:"lastUsed"`
}

SessionModel is the durable model-selection fold for one Session. Next is the pending route for the next request; LastUsed is the last consumed route. Both nil means a new Session that has never selected a model.

type SessionOptions

type SessionOptions struct {
	// ModelSelection is pinned only when a new binding is reserved.
	ModelSelection *ModelSelection
	Key            string
	Workspace      string
	Browser        string
	Prompt         string
	NoSubmit       bool
	NoOpen         bool
}

SessionOptions identifies one caller-owned conversation and its first input. Workspace/Browser are pinned on first creation; later preference changes do not silently relocate an existing session. NoOpen suppresses automatic browser opening for this call, but never changes prompt delivery semantics. BrowserNone instead pins automatic opening off across retries and restarts.

type State

type State struct {
	InitialModelSelection *ModelSelection `json:"initial_model_selection,omitempty"`
	Runner                string          `json:"runner"`
	Browser               string          `json:"browser,omitempty"`
	Workspace             string          `json:"workspace,omitempty"`
	DSHSessionID          string          `json:"dsh_session_id,omitempty"`
	Created               bool            `json:"created,omitempty"`
	InitialDelivered      bool            `json:"initial_delivered,omitempty"`
	BrowserOpened         bool            `json:"browser_opened,omitempty"`
	PendingRequestID      string          `json:"pending_request_id,omitempty"`
	PendingHash           string          `json:"pending_hash,omitempty"`
	PendingPrompt         string          `json:"pending_prompt,omitempty"`
	PendingNoSubmit       bool            `json:"pending_no_submit,omitempty"`
}

State is a durable DSH conversation binding, not a business conversation. JSON names retain compatibility with the original Marcus binding records. Runner is a discriminator so a shared storage location cannot turn an existing terminal conversation into a DSH session. No launch tokens belong here.

type Store

type Store interface {
	Read(context.Context, string) (State, bool, error)
	WithSession(context.Context, string, func(Record) error) error
}

Store separates application-chosen persistence from DSH orchestration. WithSession serializes a key across all instances sharing the same storage; Read observes the last atomic checkpoint without taking a delivery lock.

type Warning

type Warning struct {
	Code    string
	Message string
}

Jump to

Keyboard shortcuts

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