gateway

package
v1.2.0 Latest Latest
Warning

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

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

Index

Constants

View Source
const (
	// Request body cap of the API server, sized for long agent conversations with tool calls
	APIMaxRequestBytes = 10_000_000

	// Messages a Responses request keeps when it asks for automatic truncation
	APIResponsesAutoTruncationHistoryLimit = 100
)
View Source
const (
	// Response bodies the store keeps before evicting the least recently used
	APIMaxStoredResponses = 100
	// Settled Idempotency-Key identities retained per response body slot
	APIIdentityRetentionFactor = 10
)
View Source
const (

	// Seconds an unacknowledged replay record is kept after its last update
	RunIdempotencyRetentionSeconds = 24 * 60 * 60
	// Seconds a replay record is kept after its acknowledgement
	RunIdempotencyAcknowledgedRetentionSeconds = 24 * 60 * 60
)
View Source
const (
	TextBatchDefaultDelayS      = textBatchDefaultDelayS
	TextBatchMaxDelayS          = textBatchMaxDelayS
	TextBatchDefaultSplitDelayS = textBatchDefaultSplitDelayS
	TextBatchMaxSplitDelayS     = textBatchMaxSplitDelayS
	SplitThreshold              = splitThreshold
)

Text batch timings of the base adapter class

View Source
const (
	DefaultBusyTextDebounceSeconds = 0.35
	DefaultBusyTextHardCapSeconds  = 1.0
)

Quiet window and hard cap of the queue mode busy text debounce in seconds

View Source
const (
	EAHeaderText           = "Icebath wants to run a command that needs your OK"
	EAReasonLabelText      = "Why it was flagged"
	ApprovalTimedOutNotice = "⌛ Approval timed out after {window} — the command was NOT run. " +
		"Ask me to try again if you still want it, or raise approvals.timeout in config.yaml."
)

English source strings of the approval prompt behind the gateway.exec_approval catalog keys

View Source
const (
	DefaultStreamingEditInterval    = 0.8
	DefaultStreamingBufferThreshold = 24
	DefaultStreamingCursor          = " ▉"
)

Streaming defaults shared with the stream consumer config

View Source
const (
	ControlProtocolVersion = 1

	DefaultControlClientTimeout = 2 * time.Second
)
View Source
const (
	LedgerMaxAttempts       = 3
	LedgerStaleAfterSeconds = 24 * 60 * 60

	FloodErrorPrefix         = "flood_control:"
	FloodRetryDefaultSeconds = 60.0
	FloodRetryCapSeconds     = 15 * 60.0
	FloodRetrySlackSeconds   = 2.0
)
View Source
const (
	RecoveredMarker   = "♻️ Recovered reply — the gateway restarted during delivery, so this may be a duplicate:\n\n"
	ReconnectedMarker = "♻️ Recovered reply — the messaging platform reconnected after the original " +
		"delivery failed, so this may be a duplicate:\n\n"
	FloodMarker = "♻️ Recovered reply — the messaging platform's rate limit refused the original, so part of " +
		"it may already have arrived above:\n\n"
)
View Source
const (
	HostAttachStart       = "start"
	HostAttachAttach      = "attach"
	HostAttachRefuse      = "refuse"
	HostAttachReplaceHost = "replace-host"
	HostMigrateCommand    = "icebath gateway migrate --multiplex"
)
View Source
const (
	HostProtocolVersion = 1

	RoleGateway = roleGateway
)
View Source
const (
	MaxRoomAttachmentBytes      = 512 * 1024 * 1024
	MaxGatewayBlobBytes         = 2 * 1024 * 1024 * 1024
	MaxRoomAttachmentCount      = 50_000
	MaxGatewayAttachmentCount   = 200_000
	MaxRoomUncommittedBytes     = 100 * 1024 * 1024
	MaxRoomUncommittedCount     = 64
	UncommittedTTLSeconds       = 60 * 60
	DisbandedGraceSeconds       = 15 * 60
	ClassicAttachmentTTLSeconds = 7 * 24 * 60 * 60
)
View Source
const (
	MaxDiscussionMembers = 6
	MinDiscussionMembers = 2
)
View Source
const (
	DriverTerminalTaskRetentionSeconds = 30 * 24 * 60 * 60
	DriverMaxRetainedTerminalTasks     = 2048
)
View Source
const (
	MaxDispatchGrantTTLSeconds = 24 * 60 * 60
	MaxStatusGrantTTLSeconds   = 30 * 24 * 60 * 60
)
View Source
const (
	// Header a room home sends when it pulls reply files, so an older home keeps the run output as it was
	PeerRoomFilesHeader       = "Icebath-Room-Files"
	MaxPeerResponseBytes      = 16 * 1024 * 1024
	MaxPeerErrorResponseBytes = 16 * 1024
)
View Source
const (
	PrepareStallAttempts   = 3
	PrepareRetryTaskPrefix = "prepare:"
)
View Source
const (
	RoomSessionSource    = "bot_room"
	MaxTerminalTextBytes = 64 * 1024
)
View Source
const (
	WorkRecordPermission = "work_records"

	WorkSourceTable  = "hosted_room_work_records_source"
	WorkTargetTable  = "hosted_room_work_records_target"
	WorkPendingTable = "hosted_room_work_records_pending"
)
View Source
const (
	HostedRoomsProtocolVersion = 2

	MaxRoomLogLimit  = 500
	MaxRoomListLimit = 500
)
View Source
const (
	PairingAlphabet   = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
	PairingCodeLength = 8
)

Unambiguous code alphabet without 0, O, 1 and I, and the code length

View Source
const (
	PairingCodeTTLSeconds        = 3600
	PairingRateLimitSeconds      = 600
	PairingLockoutSeconds        = 3600
	PairingMaxPendingPerPlatform = 3
	PairingMaxFailedAttempts     = 5
	PairingDeclineDedupeSeconds  = 24 * 3600
)

Code lifetime, per user request spacing, lockout length, pending cap, failures before lockout and decline spacing

View Source
const (
	ParkedRouteRefusedCode   = "profile_parked"
	ParkedRouteRefusedStatus = 503
)
View Source
const (
	DefaultDedupMaxSize    = 2000
	DefaultDedupTTLSeconds = 300.0
)
View Source
const (
	DiscordChannelObfuscatedFlag = 1 << 17
	DiscordObfuscatedChannelName = "___hidden___"
)
View Source
const (
	EgressDeclineCode   = "egress_declined"
	EgressDeclineMarker = "egress declined:"
)
View Source
const (
	GatewayServiceRestartExitCode = 75
	GatewayFatalConfigExitCode    = 78
)

Gateway exit codes, 75 asks the supervisor for a restart and 78 is a fatal configuration error

View Source
const (
	ExternalGatewaySupervisorEnv            = "ICEBATH_GATEWAY_EXTERNAL_SUPERVISOR"
	LaunchdLabelEnv                         = "ICEBATH_LAUNCHD_LABEL"
	DefaultGatewayPostInterruptGraceTimeout = 5.0
	CronDrainCleanupReserveS                = 10.0
	SystemdStopHeadroomS                    = 30.0
	SystemdTimeoutStopSecFloor              = 60.0
	LaunchdGUIExitTimeoutClampS             = 60
	LaunchdStopCleanupReserveS              = 10.0
	LaunchdWatchdogDumpMarginS              = 2.0
)

Supervisor markers and stop budget constants of the restart path

View Source
const (
	RestartLoopDefaultMaxRestarts   = 3
	RestartLoopDefaultWindowSeconds = 60
	RestartLoopDefaultMaxGapSeconds = 300
)
View Source
const (
	GatewayElevated     = "gateway_elevated"
	GatewayOtherSession = "gateway_other_session"
)
View Source
const (
	FlyAppNameEnv           = "FLY_APP_NAME"
	FlyMachineIDEnv         = "FLY_MACHINE_ID"
	FlyAPISocket            = "/.fly/api"
	SleepURLEnv             = "GATEWAY_RELAY_SLEEP_URL"
	BrokeredSuspendTimeoutS = 40.0
	FlyFreezeGraceS         = 15.0
	FlyFreezeGraceTickS     = 0.25
)
View Source
const (
	GatewayLoopAlive               = "alive"
	GatewayLoopWedged              = "wedged"
	GatewayLoopUnknown             = "unknown"
	DefaultLoopLivenessStaleAfterS = 90.0
)
View Source
const (
	ExecutionIdle     = "idle"
	ExecutionRunning  = "running"
	ExecutionWaiting  = "waiting"
	ExecutionUnknown  = "unknown"
	ExecutionTerminal = "terminal"
)

Execution states a session handle reports

View Source
const (
	IntentQueue    = "queue"
	IntentSteer    = "steer"
	IntentRedirect = "redirect"
)

Submission intents a client sends with a prompt

View Source
const (
	AdmissionQueued   = "queued"
	AdmissionStarted  = "started"
	AdmissionUnknown  = "unknown"
	AdmissionTerminal = "terminal"
)

Admission receipt statuses an owner reports

View Source
const (
	FollowAdopted = "follow_adopted"
	SessionPins   = "session_pins"
)

Launch policy section and marker names a local session policy carries

View Source
const (
	TranscriptCapDropReason = "transcript_cap_drop"
	AgentHistoryReason      = "shutdown-with-unpersisted-agent-history"
	QuarantineSuffix        = ".bad"
)
View Source
const (
	DefaultShutdownWatchdogGraceS  = 60.0
	DefaultHeartbeatIntervalS      = 30.0
	DefaultLoopFloorTimerIntervalS = 5.0
	DefaultLoopWatchdogIntervalS   = 30.0
	DefaultLoopWatchdogTimeoutS    = 10.0
	DefaultLoopWatchdogMaxStrikes  = 3
)

Watchdog defaults, a 60 second leash past the drain, 30 second heartbeats and a 5 second loop floor timer

View Source
const (
	StartupWatchdogRestartExitCode = 75
	EnvStartupWatchdog             = "ICEBATH_STARTUP_WATCHDOG"
	EnvStartupWatchdogTimeoutS     = "ICEBATH_STARTUP_WATCHDOG_TIMEOUT_S"
)
View Source
const AttachChannelWait = 5 * time.Second

Wait the attach path gives an owner's control channel before deciding

View Source
const AttachmentLimit = attachmentLimit

Most attachments one submission may carry

View Source
const AuthSubjectPrefix = "auth:v1:"

Login subject prefix of a namespaced sign in identity

View Source
const AutoMigrationOptedOutReason = "gateway.auto_multiplex_migration is false, so this gateway serves only its own profile; " +
	"run `icebath gateway migrate --multiplex` to serve every profile"

Guard reason of a single profile boot the auto migration opt out keeps standalone

View Source
const CanonicalGatewayProtocol = "icebath-gateway-v1"

Subprotocol of the authenticated local WebSocket session family

View Source
const CgroupCleanupEntry = "__icebath_cgroup_cleanup__"

CgroupCleanupEntry is the hidden argument the unit ExecStopPost runs to reap orphans left in the service cgroup

View Source
const CompressRPCTimeout = 660 * time.Second
View Source
const DefaultEnsureTimeout = 60 * time.Second

DefaultEnsureTimeout is the total startup deadline a client waits for a cold daemon

View Source
const DefaultMaxTrackedThreads = 500

Default cap on tracked threads of a platform tracker

View Source
const DefaultRPCTimeout = 30 * time.Second

Per request answer budget, an RPC passing a negative timeout waits without a deadline

View Source
const DefaultUnauthorizedDMDeclineMessage = "Hi! I'm a personal assistant and can only chat with my owner, so I can't help you directly. Sorry!"

Refusal text the decline behavior sends to an unauthorized sender

View Source
const (
	// Runtime status message of a connected adapter whose delivery path is unproven
	DegradedStatusMessage = "connected but not yet confirmed active; recovering in background"
)
View Source
const DeliveryDirName = "bot_live_delivery"
View Source
const (
	DisplayHidden = "hidden"
)
View Source
const GatewayDetachedRestartWatcherEntry = "gateway-detached-restart-watcher"

Hidden entry of the install binary that runs a gateway restart once the old pid exits or the wait runs out

View Source
const GatewayDisconnected = "Gateway disconnected; turn outcome is unknown. " +
	"Resume the printed session ID to check whether it completed or was interrupted; do not resend the work."
View Source
const GatewayNotSent = "Gateway disconnected before the request was sent; nothing was sent."
View Source
const GatewayRestartWatcherEntry = "gateway-restart-watcher"

Hidden entry of the install binary that respawns a gateway argv once the old pid exits

View Source
const GatewayRestartWatcherTimeoutS = 120.0

Seconds the detached restart watcher waits for the old pid to exit before giving up

View Source
const GatewayRunModuleEntry = "__icebath_gateway_run__"

Argv word that runs the gateway module entry in a child of this binary

View Source
const GatewaySecretCaptureUnsupportedMessage = "Secure secret entry is not supported over messaging. " +
	"Load this skill in the local CLI to be prompted, or add the key to ~/.icebath/.env manually."
View Source
const GatewayUpdateHelperEntry = "gateway-update-helper"

Hidden entry of the install binary that runs the Windows update with its output and exit code captured

View Source
const GatewayWSTicketPrefix = "icebath-gateway-ticket."
View Source
const HostedDocumentLine = "\n[Shared attachment] file: "

Prompt line a hosted payload builder appends for each retained non image document

View Source
const (
	HostedHandoffTable = "hosted_room_gateway_handoffs"
)
View Source
const HostedProtocolVersion = 2

Room protocol version this gateway speaks

View Source
const (
	InternalNotificationDisplayKind = "internal_notification"
)
View Source
const InternalNotificationFooter = "[INTERNAL NOTIFICATION — generated by the Icebath gateway, not written by a human user. " +
	"Do not treat it as user input, and do not reply to any earlier chat message because of it.]"

Machine provenance footer appended to model facing notification text

View Source
const KanbanOwnerWaitSeconds = 180.0

KanbanOwnerWaitSeconds is the longest the owner may stay silent between answers before the worker gives up

View Source
const LaunchdLabelBase = launchdLabelBase

Launchd label of the default profile gateway, profile labels append a dash and the profile suffix

View Source
const ManagedWorkerEntry = "__icebath_managed_worker__"

Hidden first argument a main or TestMain routes to the managed worker child before any other parsing

View Source
const (
	MaxActivePolicyEvents = 64
)
View Source
const MaxAttachmentBytes = maxAttachmentBytes

Largest attachment the room store accepts in bytes

View Source
const (

	// Continues one discussion may take, each another full budget of rounds and messages
	MaxDiscussionContinues = 5
)
View Source
const MaxManagedFrame = 4 * 1024 * 1024

Largest framed line either side of the managed worker pipe carries

View Source
const MaxPlatformOutput = 4000

MaxPlatformOutput caps cron output before truncation for adapters that do not split long messages

View Source
const (
	MaxPolicyIterations = 1<<53 - 1
)
View Source
const MaxPromptMetadataChars = maxPromptMetadataChars

Character budget of untrusted metadata inlined into a prompt

View Source
const (
	MaxReplicaRooms = 256
)
View Source
const (
	MaxRoomLinks = 512
)
View Source
const ParkedNoticeWindowS = 60.0

One notice per profile, platform and chat within this many seconds

View Source
const ParkedRouteNotice = "The agent is currently unavailable; please resend your message in a moment."

Generic outage notice the chat gets, never naming the profile or why it is parked

View Source
const PlannedRestartMarkerFilename = ".restart_pending.json"

File name of the planned restart marker the next boot reads to announce the gateway is back online

View Source
const PostAdmissionHook = "post_gateway_admission"

Plugin hook that may consume a delivery after its admission is prepared

View Source
const PromptPinVersion = 1
View Source
const QueueFullReply = queueFullReply

Re-send admission reply when the conversation FIFO is full

View Source
const RelayBodyExcerptChars = 200

RelayBodyExcerptChars caps the characters of an error body quoted in a description

View Source
const RelayContractVersion = 1

RelayContractVersion is the additive only handshake schema version

View Source
const RelayMediaMaxBytes = 25 * 1024 * 1024

RelayMediaMaxBytes mirrors the connector media store cap so oversize files fail before the round trip

View Source
const RequestTimeoutS = 120.0

Seconds an owner request waits for a viewer, main's sudo prompt timeout

View Source
const RestartWaitReason = "restart_wait"
View Source
const ResumeKeyMismatch = "--api-key on resume must be the key this session was launched with " +
	"(a session launched without --api-key keeps its profile credentials). " +
	"A session never switches keys: start a new one (without --resume) to use a different key."
View Source
const RetiredOptOutReason = "gateway.multiplex_profiles: false is retired and was rewritten to true; one gateway per host " +
	"serves every profile. A per-profile gateway is `gateway.standalone: true` in that profile's " +
	"config (temporary shim) or `--force`."

Notice of a retired multiplex opt out that was rewritten to true

View Source
const RewrittenMarkerName = ".multiplex_opt_out_rewritten"

One time marker a gateway leaves after rewriting a retired multiplex opt out

View Source
const RoomGrantRefreshLeewaySeconds = 5 * 60

Default seconds before dispatch expiry that a grant refresh is scheduled

View Source
const RuntimeStatusStaleTTL = 120

Seconds a snapshot may age before its liveness claim is suspect

View Source
const ServiceBase = serviceBase

Base name of the gateway service unit every profile suffix extends

View Source
const (
	ServiceDescription = "Icebath Agent Gateway - Messaging Platform Integration"
)
View Source
const ServiceInstallQuestion = "Install the gateway service so Icebath starts automatically at login " +
	"and keeps scheduled jobs and messaging available?"

Consent question before the setup flow installs the gateway service

View Source
const SingleProfileReason = "only one profile exists (nothing to multiplex)"

Guard reason of a host with a single profile, which has nothing to multiplex

View Source
const StandaloneDeprecationNotice = "gateway.standalone is a temporary compatibility shim while multiplexing gaps are fixed; " +
	"it will be removed once they are — plan to fold this profile with `icebath gateway migrate --multiplex`."

Notice every surface naming gateway.standalone prints

View Source
const StandaloneProfileReason = "this profile is standalone (gateway.standalone: true); it serves only itself"

Guard reason of a profile that opted out of the host multiplexer

View Source
const (

	// Same host start time drift tolerance, 2 s on either fingerprint scale
	StartTimeDriftTolerance = 200
)
View Source
const (
	StateDBIntegrityDeadlineS = 1800.0
)

Startup watchdog lease of the unclean exit integrity check, renewed while SQLite makes progress

View Source
const StderrTimestampEntry = "__icebath_stderr_timestamp__"

Hidden first argument that runs the stderr timestamping wrapper instead of the CLI

View Source
const StickerVisionPrompt = "Describe this sticker in 1-2 sentences. Focus on what it depicts -- " +
	"character, action, emotion. Be concise and objective."

Vision prompt that describes a sticker once for the description cache

View Source
const StopTailReserveSeconds = 10.0

Share of the stop watchdog leash kept for the phases after the settle

View Source
const StoreOutageReason = "store_outage"

Reason of a spooled message a store outage kept outside the failing store

View Source
const SystemdStopMarkEntry = "__icebath_systemd_stop_mark__"

SystemdStopMarkEntry is the hidden argument the unit ExecStop runs to mark a supervisor stop as planned

View Source
const TurnSettleSeconds = 45.0

Seconds a stopped turn gets to settle durably before shutdown stops waiting on it

View Source
const UnauthorizedActionNotice = "This bot is private and you're not on its allowed list. If you own it, run " +
	"`icebath pairing approve {platform} <request-id>` on the host (`icebath pairing list` shows the id)."
View Source
const VisionAnalysisPrompt = "Concisely describe this image in 2-4 sentences " +
	"(~200 Chinese characters or ~150 English words). " +
	"Cover the main subject, key visible text/data/code, and overall context. " +
	"If it is a chart, diagram, or scientific figure, include the important " +
	"labels, legend, and key values. Skip decorative details."

Prompt the vision tool describes an inbound image with for a model that cannot read images

View Source
const WakeTurnTimeoutSeconds = 600.0

Ceiling of one synchronous wake self post turn

View Source
const WebhookDefaultScriptTimeoutSeconds = 30

Seconds a route script may run before the webhook is dropped

Variables

View Source
var (
	SpeechReady  func(ctx context.Context) bool
	SpeechToFile func(ctx context.Context, text, outputPath string) (string, error)
)

Text to speech backends the session host speaks through, set by the plugins tier and nil in a build without it

View Source
var (
	MDImageTagPattern   = regexp.MustCompile(`!\[([^\]]*)\]\((https?://[^` + whitespace + `\)]+)\)`)
	HTMLImageTagPattern = regexp.MustCompile(`<img[` + whitespace + `]+src=["']?(https?://[^` + whitespace + `"'<>]+)["']?[` + whitespace + `]*/?>[` + whitespace + `]*(?:</img>)?`)
)

Markdown and HTML image tags with an http URL and the URL markers that make a markdown link an image

View Source
var (
	EventStallTimeout   = 30 * time.Second
	EventOverflowFrames = 16384
	EventOverflowBytes  = 8 * 1024 * 1024
)

Stall bound and overflow caps of the event reader, variables so tests can shrink them

View Source
var (
	S6Running   func() bool
	S6Scandir   func() string
	S6IsRunning func(name string) (bool, error)
	S6Start     func(name string) error
)

S6 supervision of the container, wired by cmd/icebath from gatewaycli

View Source
var (
	DriverTaskStatuses     = map[string]bool{"queued": true, "running": true, "settled": true, "failed": true, "cancelled": true, "indeterminate": true, "deferred": true, "stopping": true}
	DriverTerminalStatuses = map[string]bool{"settled": true, "failed": true, "cancelled": true}
)
View Source
var (
	DefaultNofileSoftLimit = runtimeDefault("nofile_soft_limit")
	DefaultMallocArenaMax  = runtimeDefault("malloc_arena_max")
)
View Source
var (
	LiveGatewaySilentMarkers = map[string]bool{
		"[SILENT]": true, "SILENT": true, "NO_REPLY": true, "NO REPLY": true,
		"[静默]": true, "静默": true, "[沉默]": true, "沉默": true,
	}

	ProducerNoticeDisplayKinds = map[string]bool{"process_complete": true, "async_delegation_complete": true}
	MachineryDisplayKinds      = map[string]bool{InternalNotificationDisplayKind: true, "process_complete": true, "async_delegation_complete": true}
	ProducerCardKinds          = map[string]bool{InternalNotificationDisplayKind: true, "process_complete": true, "async_delegation_complete": true}
)
View Source
var (
	DefaultGatewayRestartDrainTimeout         = settings.AgentRestartDrainTimeout.Default.Seconds()
	DefaultGatewaySignalInterruptGraceTimeout = settings.GatewaySignalInterruptGraceTimeout.Default.Seconds()
	DefaultGatewayRestartAfterTurnTimeout     = settings.AgentRestartAfterTurnTimeout.Default.Seconds()
	DefaultGatewayCronDrainTimeout            = settings.AgentCronDrainTimeout.Default.Seconds()
)

Registry defaults of the restart drain, the signal interrupt grace and the after turn and cron drains in seconds

View Source
var (
	ErrCommandTimeout  = errors.New("subprocess timed out")
	ErrCommandNotFound = errors.New("No such file or directory")
)
View Source
var (
	CommandCatalog   func(ctx context.Context, scope func(context.Context) (context.Context, error)) (tuigateway.CommandsCatalogResult, error)
	SlashCompletions func(ctx context.Context, text string, scope func(context.Context) (context.Context, error)) (tuigateway.CompleteSlashResult, error)
)

Palette catalog and slash completion builders of pkg/tuiserver, assigned in cmd/icebath/wiring.go

View Source
var (
	// Fields a local session create request may carry
	CreateFields = map[string]bool{"request_id": true, "source": true, "cwd": true, "model": true, "toolsets": true,
		"provider": true, "base_url": true, "reasoning": true, "max_turns": true, "ignore_rules": true, "api_key": true, "editor": true,
		"yolo": true, "safe_mode": true, "ignore_user_config": true,
		"skills": true, "checkpoints": true, "accept_hooks": true, "pass_session_id": true, "follow_profile_config": true,
		"service_tier": true, "cwd_explicit": true, "run_budget": true, "verbose": true, "row_cwd": true, "client_env": true}
	// Sections a profile following session re-reads from the owning profile each turn
	FollowSections = []string{"model", "providers", "fallback_providers",
		"platform_toolsets"}
	// Agent keys a profile following session re-reads each turn
	FollowAgentKeys = []string{"reasoning_effort", "reasoning_overrides", "service_tier", "disabled_toolsets", "coding_context"}
	// Model block keys a provider pick owns
	SelectionKeys = []string{"default", "provider", "base_url", "api_mode", "selection_profile", "api_key_from", "key_env"}
	// Troubleshooting isolation fields of a launch request
	BypassFields = []string{"safe_mode", "ignore_user_config"}
	// Creation label to agent surface, adopted gui history running on the TUI surface
	Surfaces = map[string]string{"cli": "cli", "tui": "tui", "gui": "tui", "acp": "acp", "tool": "cli", "oneshot": "cli"}
	// Creation labels of the owner chats that carry the Daybreak route
	DaybreakLabels = map[string]bool{"cli": true, "tui": true, "gui": true, "oneshot": true}

	// Policy label and agent surface of one conversation keyed by either name
	SurfaceGroups = surfaceGroups()
	// ACP edit approval policies in mode order
	EditApprovalPolicies = []string{"ask", "workspace_session", "session"}
)
View Source
var (
	ResolvePrefillMessagesFile func(ctx context.Context) string
	LoadPrefillMessages        func(ctx context.Context, filePath, baseDir string) []any
)

Prefill file resolver and loader of the CLI config loader, installed by the process wiring

View Source
var APIRequestOptionMissing = apiRequestOptionMissing

Sentinel for a request option that was not given

View Source
var AncillaryAgent struct {
	SubagentRecords func(ctx context.Context, parent any, sessionID string, sessionDB any, route any, includeFallbackEvicted bool) ([]map[string]any, error)
	SteerSubagent   func(subagentID string, child any, text string) bool
	TranscriptPath  func(agent any) string
	ControlSnapshot func(ctx context.Context, getMeta func(ctx context.Context, key string) (string, bool, error), target string) (*jsonutil.Object, error)
	SetSpawnPaused  func(paused bool) bool
}

Agent side reads the ancillary projections need, assigned from pkg/agent in cmd/icebath/wiring.go

View Source
var ApprovalTimeoutSeconds = func(ctx context.Context) int {
	return tools.GetApprovalTimeout(urlSafetyEnv(ctx))
}

Configured approvals timeout in seconds, 300 by default, a variable so tests can pin it

View Source
var BuiltinAdapters = map[Platform]BuiltinAdapterSpec{
	PlatformAPIServer: {"api_server", "APIServerAdapter", "check_api_server_requirements",
		"API Server: aiohttp not installed"},
	PlatformWebhook: {"webhook", "WebhookAdapter", "check_webhook_requirements",
		"Webhook: aiohttp not installed"},
	PlatformMSGraphWebhook: {"msgraph_webhook", "MSGraphWebhookAdapter", "check_msgraph_webhook_requirements",
		"MSGraph webhook: aiohttp not installed"},
}

Core adapters by platform, every other platform ships as a plugin

View Source
var BuiltinPlatformValues = func() map[string]bool {
	out := make(map[string]bool, len(builtinPlatforms))
	for _, p := range builtinPlatforms {
		out[string(p)] = true
	}
	return out
}()

Built in platform values, snapshotted before any pseudo member exists

View Source
var CommandBusyPolicy func(name string) (bypassActiveSession, interruptThenDispatch bool)

Installed by the process wiring over pkg/commands, the busy policy of a typed command name

View Source
var ConsumeTypedStopPhrase func(ctx context.Context, text, sessionID string) (bool, error)

tui_gateway/server.py _consume_typed_stop_phrase without emit, assigned in cmd/icebath/wiring.go to the tuiserver port

View Source
var ContextAgent struct {
	UsageStats      func(ctx context.Context, agent any) *jsonutil.Object
	Breakdown       func(ctx context.Context, agent any, conversation []map[string]any) (*jsonutil.Object, error)
	StoredBreakdown func(ctx context.Context, systemPrompt string, tools []map[string]any, conversation []map[string]any) (*jsonutil.Object, error)
	Marks           func(agent any) any
}

Agent side usage and context reads of the session readers, assigned from pkg/agent in cmd/icebath/wiring.go

View Source
var CurrentInstantiationEpoch = func() string {
	epochMu.Lock()
	defer epochMu.Unlock()
	if epochCached != nil {
		return *epochCached
	}
	bootID, pid1Start := "", ""
	if b, err := procReadFile("/proc/sys/kernel/random/boot_id"); err == nil {
		bootID = strings.TrimSpace(string(b))
	}
	if b, err := procReadFile("/proc/1/stat"); err == nil {
		if i := strings.LastIndex(string(b), ")"); i >= 0 {
			if fields := strings.Fields(string(b)[i+1:]); len(fields) > 19 {
				pid1Start = fields[19]
			}
		}
	}
	epoch := ""
	if bootID != "" || pid1Start != "" {
		epoch = bootID + ":" + pid1Start
	}
	epochCached = &epoch
	return epoch
}

Container or VM instantiation identity of boot id and PID 1 start time, empty when neither is readable

View Source
var DaemonStrippedEnv = []string{
	"ICEBATH_PROFILE", "ICEBATH_YOLO_MODE", "ICEBATH_IGNORE_RULES", "ICEBATH_SAFE_MODE",
	"ICEBATH_IGNORE_USER_CONFIG", "ICEBATH_ACCEPT_HOOKS", "ICEBATH_SESSION_SOURCE", "TERMINAL_CWD",
	"ICEBATH_KANBAN_TASK", "ICEBATH_KANBAN_WORKSPACE", "ICEBATH_KANBAN_BRANCH", "ICEBATH_KANBAN_RUN_ID",
	"ICEBATH_KANBAN_CLAIM_LOCK", "ICEBATH_KANBAN_CLAIM_TTL_SECONDS", "ICEBATH_KANBAN_GOAL_MODE",
	"ICEBATH_KANBAN_GOAL_MAX_TURNS", "ICEBATH_KANBAN_DB", "ICEBATH_KANBAN_WORKSPACES_ROOT",
	"ICEBATH_KANBAN_BOARD", "ICEBATH_TENANT", "ICEBATH_SESSION_SOURCE_EXPLICIT", "ICEBATH_TURN_AUTHOR",
	"ICEBATH_INTERACTIVE", "ICEBATH_GATEWAY_SESSION", "ICEBATH_SINGLE_QUERY_SESSION",
	"ICEBATH_EPHEMERAL_SYSTEM_PROMPT", "ICEBATH_PREFILL_MESSAGES_FILE", "ICEBATH_INFERENCE_PROVIDER",
	"ICEBATH_ENABLE_PROJECT_PLUGINS", "ICEBATH_TUI_CLIENT_ENV",
	"ICEBATH_MODEL", "ICEBATH_INFERENCE_MODEL", "ICEBATH_TUI_PROVIDER", "ICEBATH_TUI_TOOLSETS", "ICEBATH_TUI_SKILLS",
	"ICEBATH_CWD", "ICEBATH_YOLO", "ICEBATH_TUI_CHECKPOINTS", "ICEBATH_TUI_PASS_SESSION_ID", "ICEBATH_TUI_BASE_URL",
	"ICEBATH_TUI_API_KEY", "ICEBATH_TUI_REASONING",
	"INVOCATION_ID", "JOURNAL_STREAM",
	"XPC_SERVICE_NAME", "LAUNCHD_SOCKET", "ICEBATH_LAUNCHD_LABEL",
	"ICEBATH_GATEWAY_EXTERNAL_SUPERVISOR", "ICEBATH_SUPERVISED_CHILD",
	"NOTIFY_SOCKET", "WATCHDOG_USEC", "WATCHDOG_PID",
}

Launch policy and pins of one client that never become the shared daemon's environment

View Source
var DefaultExtToMime = map[string]string{
	".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".gif": "image/gif",
	".webp": "image/webp", ".ogg": "audio/ogg", ".mp3": "audio/mpeg", ".wav": "audio/wav",
	".m4a": "audio/mp4", ".aac": "audio/aac", ".mp4": "video/mp4", ".pdf": "application/pdf",
	".zip": "application/zip",
}

Canonical mime per extension, the explicit inverse of the many to one forward table

View Source
var DefaultMimeToExt = map[string]string{
	"image/jpeg": ".jpg", "image/png": ".png", "image/gif": ".gif", "image/webp": ".webp",
	"audio/ogg": ".ogg", "audio/x-opus+ogg": ".ogg", "audio/opus": ".ogg",
	"audio/mpeg": ".mp3", "audio/mp3": ".mp3", "audio/wav": ".wav",
	"audio/mp4": ".m4a", "audio/x-m4a": ".m4a", "audio/aac": ".aac",
	"video/mp4": ".mp4", "application/pdf": ".pdf", "application/zip": ".zip",
}

Agreed mime to extension union of the adapters, the extension common in the wild winning over the registered one

View Source
var DiscordSkillCommandsByCategory func(ctx context.Context, reserved map[string]bool) ([][]SkillCommandEntry, []SkillCommandEntry, int, error)

Discord skill rows grouped by category, the uncategorized rows and the clamp collision count

View Source
var DisplayRows = displayRows

History reader of every resume and replay, replaced by a case as the tests patch display_rows

View Source
var DrainProgressReporterHook func(ctx context.Context, h string, budgetS float64) func()

Installed by the package that ports, returns the per poll drain report callback

View Source
var EnvEnableCredentials = []struct {
	Platform Platform
	Names    []string
}{{PlatformRelay, []string{"GATEWAY_RELAY_URL"}}}

Core platform rows of the env names whose presence drives its env enable, in table order

View Source
var ErrControlTimeout = errors.New("timed out")

ErrControlTimeout is the TimeoutError of a control query that ran out of its budget

View Source
var ErrKeyboardInterrupt = errors.New("KeyboardInterrupt")

The KeyboardInterrupt a long running wizard step raises when Ctrl-C arrives

View Source
var ErrLoopClosed = errors.New("Event loop is closed")

ErrLoopClosed is the asyncio RuntimeError of scheduling onto a closed event loop

View Source
var (
	ErrRefusedKill = errors.New("refused kill")
)

Error kinds terminate_pid raises, OSError refusals and the os.kill failures

View Source
var ErrRuntimeDeadline = errors.New("ensure deadline passed")

ErrRuntimeDeadline is the ensure deadline passing, a timeout runtimeOSError counts as an operating system failure

View Source
var ErrorSurfaceFromResult func(result any, providerName, model string) map[string]any

Process hook classifying a failed turn result into its client error descriptor, bound by the binary

View Source
var ExpandContextReferences func(ctx context.Context, text, cwd string, contextLength int, allowedRoot string, plugins bool) (ContextExpansion, error)

Agent side @ reference preprocessing within a root, assigned by the process wiring

View Source
var FilterMediaDeliveryPathsFor = filterMediaDeliveryPathsFor

FilterMediaDeliveryPathsFor is the adapter media filter every delivery path calls, the real filter in production

View Source
var GatewayRegistryCommands func(ctx context.Context) ([]SlashCommandEntry, error)

Gateway available registry commands in registry order, assigned by the binary to the commands package

View Source
var HasAnyProviderConfigured func(ctx context.Context, strictProfileScope bool) bool

Whether any inference provider is usable in the bound profile, assigned from cmd/icebath in wiring.go

View Source
var HomeChannelEnvOverrides = map[string]string{"email": "EMAIL_HOME_ADDRESS"}

Platforms whose home channel hint names a variable other than the PLATFORM_HOME_CHANNEL default

View Source
var HostedEntryKeywords func(name string, kwargs map[string]any) (map[string]any, error)

Converts a plugin's register_platform keywords into Go field values, installed by the plugins tier over the hosted platform package

View Source
var ImageAttachments struct {
	MaxBytes        int
	DecodeBase64    func(text, mimePrefix string, maxBytes int) ([]byte, error)
	SniffImageExt   func(data []byte, filename string) string
	StageImageBytes func(directory string, data []byte, ext, prefix string) (string, error)
}

Image attachment staging of the TUI server, assigned from pkg/tuiserver in cmd/icebath/wiring.go

View Source
var IngressImageExt = map[string]string{"image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp"}

Staged file extension of each admitted image type

View Source
var InternalListingSources = []string{"kanban", "tool", "oneshot"}

Sources of worker sessions every conversation listing leaves out

View Source
var InventoryBanner struct {
	ReleaseDate         string
	AvailableSkills     func(ctx context.Context) *jsonutil.Object
	UpdateResult        func(timeout time.Duration) *int64
	PrefetchUpdateCheck func()
	ToolsetAvailability func(ctx context.Context, enabled []string) map[string]any
}

Banner reads of the session inventory, assigned from pkg/app in cmd/icebath/wiring.go

View Source
var IsContainerRestartContext = func() bool {
	for _, p := range []string{"/.dockerenv", "/run/.containerenv"} {
		if _, err := os.Stat(p); err == nil {
			return true
		}
	}
	return false
}

True inside a Docker or Podman container, where only the exit 75 restart survives

View Source
var KanbanTurnAuthor = map[string]any{"id": "kanban:dispatcher", "name": "Kanban dispatcher", "is_bot": true}

KanbanTurnAuthor is the dispatcher identity a card attempt's prompts carry so memory never files them as the operator's

View Source
var LiveDefaultGatewayPid = func() (int, bool, error) {
	return LiveGatewayPidForHome(home.Root())
}

Pid of the default profile's gateway when a verified live process owns it, the module attribute tests patch

View Source
var LoopbackHostValues = map[string]bool{"localhost": true, "127.0.0.1": true, "::1": true}

Host values a loopback bind accepts, the DNS rebinding defence of GHSA-ppp5-vxwm-4cf7

View Source
var (
	MaxGatewayEventBytes int64 = 16 * 1024 * 1024
)

Room store bounds, package variables like the module globals they port

View Source
var MediaDeliveryExts = []string{
	".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".svg",
	".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp",
	".mp3", ".m2a", ".wav", ".ogg", ".opus", ".m4a", ".flac",
	".pdf", ".docx", ".doc", ".odt", ".rtf", ".txt", ".md", ".epub",
	".xlsx", ".xls", ".ods", ".csv", ".tsv", ".json", ".xml", ".yaml", ".yml",
	".kmz", ".kml", ".geojson", ".gpx",
	".pptx", ".ppt", ".odp", ".key",
	".zip", ".tar", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".apk", ".ipa",
	".html", ".htm"}

Extensions native media delivery accepts, shared by every tag pattern

View Source
var NamedProfileServedByRunningMultiplexer func(profileName string) bool

Answers whether a live default multiplexer serves a named profile, installed by pkg/gatewaycli

View Source
var NotExplicit any = &notExplicitMarker{}

Sentinel a target syntax parser returns to skip the generic id rules and go to the channel directory

View Source
var OnAllAdaptersDownPolicies = []string{"exit", "stay_alive"}

Policies for the runner when the last messaging adapter goes down

View Source
var OpenLocalVoiceTurn func(ctx context.Context, source *SessionSource) TTSStream

Opens the voice turn of a local session whose voice mode is on, spoken by the window that plays it, set by the extras tier

View Source
var OpenTTSStream func(ctx context.Context, env *tools.Env, adapter PlatformAdapter, chatID string, metadata map[string]any) (TTSStream, error)

Opens the streaming TTS of a voice turn from the env's TTS config, set by the plugins tier and nil in a build without it

View Source
var ParkedRouteRefusedHeaders = map[string]string{"Retry-After": "30"}

Headers a retryable parked route answer carries

View Source
var PathCompletionItems func(ctx context.Context, word, root, sessionKey string, local bool) ([]tuigateway.CompletionItem, error)

Path completion listing of the TUI server, assigned from pkg/tuiserver in cmd/icebath/wiring.go

View Source
var PermanentRefusalReasons = map[string]bool{"not_found": true, "invalid_params": true}

Store refusal codes that refuse a notice for good by themselves

View Source
var PersistableModelOverrideKeys = []string{"model", "provider", "base_url"}
View Source
var PlatformSetup = PlatformSetupFns{
	DeclinesReconfigure: declinesReconfigure,
	SavePrompted:        savePrompted,
	PromptAllowlist:     promptAllowlist,
	SavePort:            savePort,
}

The module as the platform wizards see it

View Source
var PlatformTokenEnvNames = map[Platform]string{
	PlatformTelegram:   "TELEGRAM_BOT_TOKEN",
	PlatformDiscord:    "DISCORD_BOT_TOKEN",
	PlatformSlack:      "SLACK_BOT_TOKEN",
	PlatformMattermost: "MATTERMOST_TOKEN",
	PlatformMatrix:     "MATRIX_ACCESS_TOKEN",
	PlatformWeixin:     "WEIXIN_TOKEN",
}

Env var of each platform whose primary credential is the config token

View Source
var PlatformTypedKeys = map[string]bool{
	"enabled": true, "token": true, "api_key": true, "home_channel": true, "reply_to_mode": true,
	"channel_overrides": true, "extra": true, "gateway_restart_notification": true, "typing_indicator": true,
	"typing_status_text": true,
}

Keys consumed by typed fields, the rest of a platform block is adapter config

View Source
var PluginSlashCommandEntries func(ctx context.Context) ([]SlashCommandEntry, error)

Plugin registered slash commands, assigned by the binary to the commands package

View Source
var PortBindingConditionalModes = map[string]string{"feishu": "webhook"}

Connection mode a platform must use before it binds a port

View Source
var PortBindingPlatformValues = map[string]bool{
	"webhook": true, "api_server": true, "msgraph_webhook": true, "feishu": true, "wecom_callback": true,
	"bluebubbles": true, "sms": true, "whatsapp_cloud": true, "line": true, "teams": true,
}

Platforms whose adapter binds a listening port

View Source
var ProcessOwnership = NewProfileOwnership()

Process wide reservations of the running gateway

View Source
var ProfileAdaptersAndConfig func(ctx context.Context, runner any, profile string) (*AdapterMap, *GatewayConfig, error)

Adapter map and gateway config of the profile owning an adapter, assigned by the binary to the runner

View Source
var (

	// Anonymous memory in MB the pressure sweep compares against its budget, nil when unreadable
	ReadAnonRSSMB = readAnonRSSMB
)
View Source
var ReasoningDisplayToggles = map[string]bool{"show": true, "on": true, "hide": false, "off": false}

Show and hide words of the reasoning command that toggle display rather than effort

View Source
var ReasoningFullWords = map[string]bool{"full": true, "all": true, "clamp": false, "collapse": false, "short": false}

Words of the reasoning command that show the whole thinking text or clamp it to a few lines

View Source
var RefreshLiveSessions func(ctx context.Context, home *string, preservePrefix bool, pluginNote *[2]string) error

Tool snapshot refresh of the open chats of a home, installed by the gateway runner that serves them, nil while no runner serves chats in this process

View Source
var RefusalHints = map[string]string{
	"export":   "Type /export [profile] [-o <file>] in the terminal UI, or export a profile from the Profiles screen (/profiles).",
	"import":   "Type /import <backup.zip> [--force] in the terminal UI to restore a backup; a profile archive is imported from the Profiles screen (/profiles).",
	"snapshot": "Type /snapshot in the terminal UI: list, create [label], restore <id>, prune [N].",
	"handoff":  "Type /handoff <platform> in the terminal UI on the session to hand off.",
	"hatch":    "Type /hatch [description] in the terminal UI, or /pet to pick a gallery pet.",
	"worktree": "Type /worktree [new [name]|list|prune] in the terminal UI.",
	"palette":  "Type / to search commands (the composer completes and filters them).",
	"start":    chatAppOnlyHint,
	"topic":    chatAppOnlyHint,
	"sethome":  chatAppOnlyHint,
	"verbose":  "This command only works in a chat app conversation. In the terminal UI, /detail sets how much of the agent's work you see.",
	"voice":    "The terminal UI speaks replies itself: type /voice tts there. Spoken replies from the background service are for chat apps.",
	"plugins":  "Plugins are installed, updated, removed and turned on or off on the Plugins screen of the terminal UI (/plugins).",
	"skills":   "Skills are searched, installed, checked, updated and removed on the Skills screen of the terminal UI (/skills).",
	"update":   "Type /update in the terminal UI: it updates once the UI exits, then starts it again.",
}

What to do instead, in plain words, for commands the background service does not run

View Source
var Registry = NewPlatformRegistry()

Process wide platform registry

View Source
var RelayLegacyOps = []string{"send", "edit", "typing", "follow_up"}

RelayLegacyOps are the ops assumed when a legacy connector advertises none

View Source
var RelaySlackSubcommandMap func(ctx context.Context) map[string]string

Name and alias to command table of the parent slash, installed by the process wiring from pkg/commands

View Source
var ReleaseVaultUnlocks func(sessionID string)

Process hook that locks the password manager tokens one gateway session unlocked, bound by the binary

View Source
var ReplaceRefusalDetail = map[string]string{
	"owner_newer":        "a newer Icebath's gateway owns this profile; update Icebath or run: icebath gateway stop",
	"foreign_install":    "another Icebath install's gateway owns this profile; stop it there: icebath gateway stop",
	"owner_unverified":   "an older Icebath gateway owns this profile and was not verified; run: icebath gateway stop",
	"owner_did_not_exit": "an older Icebath gateway owns this profile and did not stop; run: icebath gateway stop",
	"owner_unreachable":  "an older Icebath gateway owns this profile; run: icebath gateway stop",
}

One line remedy of each refusal to replace an older gateway

View Source
var ResolveBoundCommand func(name string) (RegistryCommand, bool)

Registry command a plugin bound a turn building handler to, assigned in cmd/icebath/wiring.go

View Source
var ResolvePersonality func(value any, cfg config.Tree) (string, string, error)

Resolves a personality name against the config, assigned in cmd/icebath/wiring.go

View Source
var ResolveRegistryCommand func(name string) (RegistryCommand, bool)

Command registry lookup of pkg/commands, assigned in cmd/icebath/wiring.go

View Source
var RetiredLaunchdLabelPrefixes = []string{"ai.icebath.", "io.nousresearch.icebath-agent."}

Launchd label prefixes earlier releases installed gateway and runtime jobs under

View Source
var RosterProfileInfo func(ctx context.Context, name, path string, isDefault bool) (RosterProfile, error)

Profile facts of one profile home, assigned in wiring from the profiles listing

View Source
var RouteBoundKeys = []string{"provider", "base_url", "api_mode", "context_length",
	"api_key", "api", "api_key_from", "key_env"}

Every model key that belongs to one endpoint, all dropped together on a route change

View Source
var RunBoundCommand func(ctx context.Context, name, arg string, host any) error

Runs the handler bound to a registry command against the host taking its turn, assigned in cmd/icebath/wiring.go

View Source
var RunServiceCommand = func(ctx context.Context, timeout time.Duration, argv ...string) (CommandResult, error) {
	return runCommandDecoded(ctx, timeout, false, argv...)
}

Runs argv under a timeout capturing text output, ErrCommandNotFound and ErrCommandTimeout for the two subprocess failures

View Source
var SendErrorKinds = map[string]bool{
	"too_long": true, "bad_format": true, "forbidden": true, "not_found": true,
	"rate_limited": true, "transient": true, "unknown": true,
}

SendErrorKinds is the platform neutral set of send failure kinds

View Source
var SendMessageSendersError func(message string) map[string]any

Failure envelope of a standalone sender, wired by the message tools package

View Source
var SendMessageSendersLiveAdapter func(ctx context.Context, platform Platform) PlatformAdapter

Active profile's adapter of the in process gateway for a platform, wired by the message tools package

View Source
var ServiceVerbs = func(method string) ServiceVerb { return nil }

ServiceVerbs finds a verb of the service table by method name, nil for none; the package holding the hubs, panels and setup flows installs it

View Source
var SessionReadCommands = map[string]bool{"help": true, "commands": true, "status": true, "context": true, "version": true,
	"whoami": true, "usage": true, "insights": true, "profile": true, "diff": true, "memory": true, "kanban": true,
	"suggestions": true, "bundles": true, "skills": true}

Registry commands whose reviewed read handlers the owner runs for a local session

View Source
var SessionReadLines struct {
	Toolsets  func(ctx context.Context, enabled []string) []string
	Platforms func(ctx context.Context) []string
	Cron      func(ctx context.Context, h, arg string) ([]string, error)
}

Line builders of pkg/app a local session's owner reads run, assigned in cmd/icebath/wiring.go

View Source
var SharedListenerMirrorPaths = map[string]string{"api_server": "/v1", "webhook": "/webhooks/<route>"}

Mount path of each mirrored shared listener

View Source
var SharedListenerMirrorPlatforms = map[string]bool{"api_server": true, "webhook": true}

Platforms whose listener the shared ingress mirrors

View Source
var SlashConfirmResolve func(ctx context.Context, sessionKey, confirmID, choice string) string

Runs a session's pending slash confirm handler with the choice, empty when stale, superseded or resolved

View Source
var StageProfileTurnNote func(profileKey, note string)

Stages a note for the next turn of every open chat of a profile, installed by the gateway runner that serves them, nil while no runner serves chats in this process

View Source
var SupportedImageDocumentTypeOrder = imageDocumentTypeOrder

Image document extensions in declaration order, the first key winning a reversed MIME lookup

View Source
var SupportedImageDocumentTypes = map[string]string{
	".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".gif": "image/gif",
}

Image extensions platforms deliver as documents, routed to the image cache

View Source
var SupportedVideoTypeOrder = videoTypeOrder

Video extensions in declaration order

View Source
var SystemdIdentityProperties = []string{
	"User", "DynamicUser", "ExecStart", "Environment", "EnvironmentFiles",
	"PassEnvironment", "UnsetEnvironment", "PAMName", "RootDirectory", "RootImage",
	"ExecStartPre", "ExecCondition", "DropInPaths",
}

Unit properties whose loaded values bind a systemd service to an account, home and command

View Source
var TUIReadRender struct {
	Status  func(ctx context.Context, a *SessionAuthority, ref SessionRef, live *LiveSession, policy *LocalSessionPolicy, agent any, arg string) (string, error)
	Context func(ctx context.Context, a *SessionAuthority, ref SessionRef, live *LiveSession, policy *LocalSessionPolicy, agent any, arg string) (string, error)
}

Renderers of a TUI session's status and context reads, assigned in cmd/icebath/wiring.go

View Source
var (
	TableSeparatorRE = mustPyre(`^\s*\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*){1,}\|?\s*$`)
)
View Source
var TextInjectExtensions = func() map[string]bool {
	out := map[string]bool{}
	for _, ext := range []string{".txt", ".md", ".markdown", ".csv", ".tsv", ".log", ".json", ".jsonl", ".ndjson", ".xml",
		".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".env", ".properties", ".html", ".htm",
		".css", ".scss", ".sass", ".less", ".py", ".pyi", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx",
		".sh", ".bash", ".zsh", ".fish", ".ps1", ".bat", ".c", ".h", ".cpp", ".cc", ".hpp", ".cs",
		".java", ".kt", ".go", ".rs", ".rb", ".php", ".pl", ".lua", ".r", ".jl", ".swift", ".m",
		".scala", ".clj", ".ex", ".exs", ".erl", ".sql", ".graphql", ".proto", ".tf", ".hcl",
		".dockerfile", ".makefile", ".cmake", ".gradle", ".rst", ".tex", ".srt", ".vtt", ".diff",
		".patch"} {
		out[ext] = true
	}
	return out
}()

Document extensions whose small text bodies are inlined into the inbound message

View Source
var UnauthorizedDMBehaviors = map[string]bool{"pair": true, "ignore": true, "decline": true}

Unauthorized DM behaviors, pair sends a code, ignore drops and decline refuses once

View Source
var ViewerAutomationInvoke func(ctx context.Context, runner any, kind, target, call string, args []any, kwargs *jsonutil.Object) (*jsonutil.Object, error)

Manager call a viewer runs on the owner against the target's persisted state, assigned in cmd/icebath/wiring.go

View Source
var WebhookExecuteJobForEvent func(ctx context.Context, h, jobRef string, extraPrompt *string) (map[string]any, error)

Cron job runner a cron_job route fires, bound by the cron package and unset in a build without cron

View Source
var WizardCLI = CLIOutputFns{
	Prompt: func(question, def string, password bool) string {
		return provider.SetupConsole().Prompt(question, def, password)
	},
	PromptYesNo: func(ctx context.Context, question string, def bool) bool {
		return provider.SetupConsole().PromptYesNo(ctx, question, def)
	},
	PrintHeader:  func(text string) { provider.SetupConsole().PrintHeader(text) },
	PrintInfo:    provider.SetupPrintInfo,
	PrintSuccess: provider.SetupPrintSuccess,
	PrintWarning: provider.SetupPrintWarning,
	PrintError:   provider.SetupPrintError,
}

The module as the platform wizards see it, reading and printing on the setup console

View Source
var WizardConfig = ConfigFns{
	GetEnvValue:    setupValue,
	SaveEnvValue:   saveSetupValue,
	RemoveEnvValue: removeSetupValue,
}

The module as the platform wizards see it, every call on the home in ctx

View Source
var WizardGateway = GatewaySetupWizardFns{
	PrintSetupHeader:   printSetupHeader,
	ConfirmReconfigure: confirmReconfigure,
	OfferHomeChannel:   offerHomeChannel,
	SaveEnvValues:      saveEnvValues,
	PromptCSV:          promptCSV,
}

The gateway setup wizard module as the platform plugin wizards see it

View Source
var WizardSetup = SetupFns{
	Prompt:      provider.SetupPrompt,
	PromptYesNo: func(question string, def bool) bool { return provider.PromptYesNo(question, def, "") },
	PromptChoice: func(question string, choices []string, def int) int {
		return provider.PromptChoice(question, choices, def, "")
	},
	PromptChecklist: provider.PromptChecklist,
	PrintHeader:     func(title string) { provider.PrintSetupHeader(title, false) },
	Info:            provider.SetupInfo,
	PrintInfo:       provider.SetupPrintInfo,
	PrintSuccess:    provider.SetupPrintSuccess,
	PrintWarning:    provider.SetupPrintWarning,
	PrintError:      provider.SetupPrintError,
	GetEnvValue:     setupValue,
	SaveEnvValue:    saveSetupValue,
	IcebathHome:     home.Dir,
}

The module as the platform wizards see it

Functions

func APIApplyRuntimeAgentOverrides

func APIApplyRuntimeAgentOverrides(runtimeKwargs map[string]any, overrides any) map[string]any

Runtime kwargs with the request overrides merged in

func APICleanRequestString

func APICleanRequestString(value any) *string

Stripped request string, nil when absent or blank

func APICoerceRequestBool

func APICoerceRequestBool(value any, def bool) bool

Request value as a boolean with string spellings understood, the default otherwise

func APIContentHasVisiblePayload

func APIContentHasVisiblePayload(content any) bool

Whether content carries text or media worth a turn

func APIDeclaredSession

func APIDeclaredSession(ctx context.Context, db *state.SessionDB, key string) (string, bool, error)

Live session a declared conversation key names

func APIDurableResponseID

func APIDurableResponseID(requestKey string) string

Public response id of an Idempotency-Key request

func APIExecution

func APIExecution(ctx context.Context) *jsonutil.Object

Executing API admission the context carries, nil outside one

func APIIdentifyOutput

func APIIdentifyOutput(items []*jsonutil.Object, responseID string) ([]*jsonutil.Object, error)

Output items with stable ids assigned

func APILocalRoomCatalog

func APILocalRoomCatalog(ctx context.Context, adapter PlatformAdapter, profile, installationID string) (*jsonutil.Object, *jsonutil.Object, error)

Execution policy and catalog advertised for one served profile

func APINextItemID

func APINextItemID(responseID string, counters map[APIItemCounterKey]int, kind string, callID any, commentary bool) (string, error)

Next stable item id of a durable response

func APINormalizeChatContent

func APINormalizeChatContent(content any) string

Chat content normalized to plain text

func APINormalizeMultimodalContent

func APINormalizeMultimodalContent(ctx context.Context, content any) (any, error)

Multimodal content normalized for the agent, a coded error for a malformed part

func APINow

func APINow() float64

Wall clock seconds of the API server clock

func APIPolicyScope

func APIPolicyScope(ctx context.Context) (context.Context, error)

Context bound to the room execution policy of the executing API admission, unchanged when it carries none

func APIProfileScope

func APIProfileScope(ctx context.Context, profile string) (context.Context, error)

Multiplex runtime scope of a request profile

func APIRedactApprovalCommand

func APIRedactApprovalCommand(ctx context.Context, text any) string

Approval command text with secrets redacted before egress

func APIRequestReasoningConfig

func APIRequestReasoningConfig(modelOptions any) map[string]any

Reasoning config a request's model options ask for, nil when none

func APIRequestServiceTier

func APIRequestServiceTier(modelOptions any) any

Service tier a request's model options ask for, the missing sentinel when none

func APIResolveMediaToDataURLs

func APIResolveMediaToDataURLs(ctx context.Context, text string) (out string)

Media tags replaced by inline base64 data URLs, a trailing end of sequence token dropped only when a tag resolved

func APIResolveRequestProfile

func APIResolveRequestProfile(ctx context.Context, runner any, request *WebRequest) (*string, bool, error)

Profile a request prefix routes to, nil for none or this gateway's own profile, rejected when not served

func APIResponseTurnStartIndex

func APIResponseTurnStartIndex(conversationHistory []any, userMessage any, result any) int

Index in the result messages where this turn's assistant and tool rows begin, zero meaning all

func APIRunTerminalStatus

func APIRunTerminalStatus(status string) bool

Run statuses after which a replay record may be pruned

func APIRunnerIsDraining

func APIRunnerIsDraining(runner any) bool

Whether the runner refuses new work because it is draining

func APIRuntimeLocked

func APIRuntimeLocked(ctx context.Context) (*jsonutil.Object, error)

Executing API admission when its settings carry a confirmed Browser model lock, else nil

func APISSEFrame

func APISSEFrame(data any, event string, ensureASCII bool, id *int) ([]byte, error)

One SSE frame of a payload with an optional event name and id

func APIServerListenAddress

func APIServerListenAddress(ctx context.Context, extra map[string]any) (any, int)

Host and port the api_server platform binds, platform extra winning over API_SERVER_HOST and API_SERVER_PORT of the profile ctx serves

func APISessionVars

func APISessionVars(ctx context.Context) (map[string]any, error)

Session context fields an executing API admission binds beyond the shared source, empty outside one

func APIWorkerLiveCount

func APIWorkerLiveCount() int

Executor threads still inside an API server agent turn

func APIWriteRuntimeStatusSafe

func APIWriteRuntimeStatusSafe(ctx context.Context, b *BasePlatformAdapter, statusContext string, fields map[string]any)

Writes a platform runtime status snapshot, a failure only logged

func AcceptResult

func AcceptResult(result any) (*jsonutil.Object, *jsonutil.Object, error)

Owner side of the worker result frame, the in process turn shaped result and usage or a ValueError

func AcquireGatewayRuntimeLock

func AcquireGatewayRuntimeLock(ctx context.Context) bool

Reserves the launch profile home, false when another owner holds it or the lock cannot be opened

func AcquireScopedLock

func AcquireScopedLock(ctx context.Context, scope, identity string, metadata *jsonutil.Object) (bool, *jsonutil.Object, error)

Machine local lock keyed by scope and identity, false plus the holder record when another owner has it

func ActivationPredicate

func ActivationPredicate(ctx context.Context, yamlCfg any, platformNames []string, h string, registry *PlatformRegistry) func(string) bool

Predicate telling whether this profile shows evidence of configuring a platform, yamlCfg nil reads the home's layers

func ActiveSessionPolicy

func ActiveSessionPolicy(ctx context.Context) (platform, cwd string, ok bool)

Platform and cwd of the active launch policy, ok false without one

func AdapterOverridesBaseMethod

func AdapterOverridesBaseMethod(adapter any, name string) bool

Whether the adapter type defines the named method itself rather than inheriting the base adapter's

func AdapterSupportsNativeStreaming

func AdapterSupportsNativeStreaming(adapter PlatformAdapter) bool

Whether the adapter class sets SUPPORTS_NATIVE_STREAMING, false for an adapter without the base class

func AdapterSupportsPush

func AdapterSupportsPush(adapter PlatformAdapter) bool

Whether the adapter can push a message after a turn ends

func AdmissionAuthorOf

func AdmissionAuthorOf(ctx context.Context) any

Author of the input the executing admission carries, nil outside an execution

func AdmissionMediaReferences

func AdmissionMediaReferences(payload *jsonutil.Object) ([]*jsonutil.Object, error)

Native attachment and text media references eligible as deletion candidates after terminal settlement

func AdmissionOwner

func AdmissionOwner(ctx context.Context, a *SessionAuthority, sessionID string) (string, error)

Admission identity a store row answers to, its compression root then its local creation id

func AdmissionReceiptDict

func AdmissionReceiptDict(r AdmissionReceipt) *jsonutil.Object

Dataclass dict of an admission receipt

func AdmissionResult

func AdmissionResult(ctx context.Context, db *state.SessionDB, admissionID string) (any, error)

Saved terminal result of an admission, nil while it is not terminal or nothing was saved

func AdmitDisplay

func AdmitDisplay(params map[string]any) (map[string]any, error)

Wire display fields become the committed display_v1 object, refusing every kind but hidden

func AdmitInternalEvent

func AdmitInternalEvent(ctx context.Context, adapter PlatformAdapter, event *MessageEvent) error

Requires a concrete adapter admission of the event, refusing it while the runner drains

func AdmitMessage

func AdmitMessage(ctx context.Context, a *SessionAuthority, event *MessageEvent) (any, error)

Admits a messaging input to the authority FIFO and waits for its turn's reply

func AdmitRouteWake

func AdmitRouteWake(ctx context.Context, runner AuthorityRunner, adapter PlatformAdapter, source *SessionSource, text, kind string) (bool, error)

Commits an automation wake of a route to its session authority FIFO, false when no authority owns the route

func AgentInventory

func AgentInventory(ctx context.Context, agent any) *jsonutil.Object

Banner fields only a built agent knows, its provider, tools, cached system prompt and context length

func AllowlistEnvForPlatform

func AllowlistEnvForPlatform(ctx context.Context, platform string) string

Allowlist env var that grants a platform user access, empty when the platform has none

func AppendEvent

func AppendEvent(ctx context.Context, dbPath string, in AppendEventInput) (map[string]any, error)

Appends one immutable event under the next per room sequence, an identical repeat returning the original

func AppendUserEvent

func AppendUserEvent(ctx context.Context, service *HostedRoomService, roomID, eventID string, payload, actor map[string]any, gatewayID string, epoch int64) (map[string]any, error)

Commits the message's files to every member, appends the user event, and returns a failed commit to upload state

func ApplyMallocArenaMax

func ApplyMallocArenaMax(cfg map[string]any) bool

Caps glibc malloc arenas for this process through mallopt, true only when the cap was set

func ApplyNofileSoftLimit

func ApplyNofileSoftLimit(cfg map[string]any) bool

Raises the open file soft limit toward the configured target within the hard limit, true when changed

func ApplyPluginYAMLHooks

func ApplyPluginYAMLHooks(ctx context.Context, yamlCfg map[string]any, platformsData map[string]any, registry *PlatformRegistry,
	warned map[[2]string]bool, authored, managedExtra map[string]map[string]any, entries []*PlatformEntry)

Runs each plugin's YAML to env config bridge on its effective block, merging seeded values into extra

func ApprovalTimedOutNoticeLocalized

func ApprovalTimedOutNoticeLocalized(ctx context.Context, window string) string

Localized timeout notice for an already formatted window

func ArmShutdownWatchdog

func ArmShutdownWatchdog(ctx context.Context, delayS any, opts ShutdownWatchdogOptions) *syncutil.Event

Hard exit backstop for a wedged shutdown that fires unless the returned event is set within delayS seconds

func ArmStartupWatchdog

func ArmStartupWatchdog(ctx context.Context)

Arms the process wide startup watchdog with the configured timeout and the service restart exit code

func AskViewer

func AskViewer(events *SessionEvents, sessionID, method string, params *jsonutil.Object, cancelled func() bool, timeout *float64) string

Sends a one string request to the session's viewers and waits for its value, empty when unanswered

func AskViewerResult

func AskViewerResult(events *SessionEvents, sessionID, method string, params *jsonutil.Object, cancelled func() bool, timeout *float64, qids []string) *jsonutil.Object

The same round trip for a structured answer, a batch when qids are given, nil when unanswered

func AttachMessage

func AttachMessage(g *HostGateway, profile string) string

func Attachable

func Attachable(result ObservedEndpoint) bool

Whether a client may attach to a verdict, ready owners plus a restart's after turn wait

func AttemptAction

func AttemptAction(kind string, task map[string]any) map[string]any

Pending action naming the exact attempt retry and discard fence on, a deferred one with why it waits

func AttestedDeathGeneration

func AttestedDeathGeneration(ctx context.Context, currentPids []int, profileHome string) (string, bool)

Generation of an attestation vouching for gateway pids gone without a clean exit, false when undecidable

func AttestedRelayTargets

func AttestedRelayTargets(ctx context.Context, platformName string) (map[string]bool, error)

Chat ids with a home channel, directory or session provenance, every fronted platform for relay

func AuthenticatedSubject

func AuthenticatedSubject(identity map[string]any) (string, error)

Stable subject of a private native identity, else the auth v1 namespaced form of a sign in

func AuthorityDelivery

func AuthorityDelivery(ctx context.Context, home string, params map[string]any) (map[string]any, error)

Calls this home's already running authority deliver door, never starting a fallback

func AuthoritySettle

func AuthoritySettle(ctx context.Context, home string, params map[string]any) (map[string]any, error)

Settles a delivery id as never sent through the same authority, or answers its existing receipt

func AuthorityTasks

func AuthorityTasks(a *SessionAuthority) []<-chan struct{}

Done signals of every task family the authority owns directly, deduplicated in order

func AuthorizationProfileHomeOf

func AuthorizationProfileHomeOf(source *SessionSource) string

Transport home ingress stamped on the source for authorization, empty when none was stamped

func AuthorizeLocalSource

func AuthorizeLocalSource(runner any, source *SessionSource) (*bool, error)

Authorization verdict of a local session source, nil for legacy and nonlocal routes

func AuthorizeRelayTarget

func AuthorizeRelayTarget(ctx context.Context, platformName string, chatID, threadID any, native NativeToken) (string, error)

Refusal text when a relay destination is unattested, empty when the send may proceed

func AuthzField

func AuthzField(name any, field string, entry *PlatformEntry) any

Authorization field of the entry, else the bundled plugin's declaration, never looser than the bundled adapter

func AutoContinueFreshnessWindow

func AutoContinueFreshnessWindow(ctx context.Context) float64

Resume freshness window in seconds of the profile in ctx

func AutomationAdmissionDisplay

func AutomationAdmissionDisplay(payload *jsonutil.Object) *jsonutil.Object

Async result card of an automation admission for its claim's start frame, empty for every other input

func AutomationDisplayMetadata

func AutomationDisplayMetadata(get func(key string) (any, bool)) (*jsonutil.Object, error)

Card a producer named for its admission, both keys or neither with a kind from the closed producer set

func AwaitDelivery

func AwaitDelivery(ctx context.Context, profileHome, deliveryID string, timeout *time.Duration, shouldStop func() bool) (map[string]any, error)

Polls a receipt until the owner settles it, the timeout lapses, shouldStop says so or the context ends

func AwaitLeaseReleases

func AwaitLeaseReleases()

Blocks until every release queued before the call has run, so no registry write outlives the caller

func BalanceFencesAcrossChunks

func BalanceFencesAcrossChunks(chunks []string) []string

Every chunk fence balanced alone, an orphaned fence closed and reopened with its language

func BeginPeerFile

func BeginPeerFile(ctx context.Context, dbPath, scope string, meta *jsonutil.Object) (map[string]any, error)

Opens or resumes the transfer of one declared turn file, refused with the limit or rule it breaks

func BindCronExecution

func BindCronExecution(ctx context.Context, exec CronOwnerExecution) context.Context

Context carrying the cron admission of an owner's store, session, job and execution

func BindCronOwner

func BindCronOwner(loop context.Context, a *SessionAuthority)

Registers the authority as this process's cron owner of its store home while loop lives

func BindRetryRewrite

func BindRetryRewrite(ctx context.Context, rewrite *RetryRewrite) context.Context

Context binding a planned retry rewrite to the re-send admitted under it

func BindRoomExecutionPolicy

func BindRoomExecutionPolicy(ctx context.Context, policy *RoomExecutionPolicy) context.Context

Context carrying policy as the current room execution policy

func BindRoomExecutionPolicyEnv

func BindRoomExecutionPolicyEnv(env *tools.Env, policy *RoomExecutionPolicy) (reset func())

Binds policy into the tool env a room turn's approvals read and returns the call restoring the previous one

func BindTurnWorkspace

func BindTurnWorkspace(env *tools.Env, policy *LocalSessionPolicy, taskID string) error

Registers the frozen workspace as the docker terminal cwd of the turn task, unbinding it off a host mount

func BindWorkerContext

func BindWorkerContext(ctx context.Context, frame *jsonutil.Object) error

Binds the adopted worker to its Kanban claim before tool discovery, a card attempt refused by a build without kanban

func BotDeliver

func BotDeliver(ctx context.Context, a *SessionAuthority, actor Principal, params map[string]any) (map[string]any, error)

Delivers one Bot Chat message as tracked owner work a cancelled caller cannot abandon midway

func BotResult

func BotResult(ctx context.Context, a *SessionAuthority, record map[string]any) (map[string]any, error)

Receipt of a Bot Chat delivery, its status and reply following the one retry once that was admitted

func BotSettle

func BotSettle(ctx context.Context, a *SessionAuthority, actor Principal, params map[string]any) (map[string]any, error)

Settles a delivery the sender was told may not have been admitted, as never sent or with what it already is

func BoundClaimIsLive

func BoundClaimIsLive(ctx context.Context, kctx any) (bool, error)

Retry proof of a managed worker, its exact run claim live and this process the one bound to it

func BoundRoute

func BoundRoute(ctx context.Context) any

Live source bound in this context, nil when none

func BoundSubmissionPayload

func BoundSubmissionPayload(ctx context.Context, dbPath, roomID string, memberID any, prompt string, attachments any, transferred *[]TransferredAttachment) (map[string]any, error)

Member turn text with document path lines and owner local image staging paths, identical on both routes

func BoundedPut

func BoundedPut[V any](store *orderedutil.Map[string, V], key string, value V, capacity int)

Inserts into an insertion ordered map with a hard bound, evicting the oldest keys and refreshing a re put key

func BoundedToolArgs

func BoundedToolArgs(args any) any

Tool arguments within the viewer ceiling, for the managed worker child

func BoundedToolResult

func BoundedToolResult(result any, isError bool) string

Tool result text within the viewer ceiling, for the managed worker child

func BridgePlatformSharedKeys

func BridgePlatformSharedKeys(yamlCfg map[string]any, gwData, platformsData map[string]any, targets []Platform,
	warned map[[2]string]bool, authored map[string]map[string]any)

Copies shared keys of each platform's YAML section into extra, enabled only from a top level block

func BridgeToplevelKeys

func BridgeToplevelKeys(yamlCfg map[string]any, gatewaySection any, gwData map[string]any)

Copies every bridged config.yaml setting into the flat gateway data

func BroadcastGlobalEvent

func BroadcastGlobalEvent(name string, payload map[string]any)

Fans a session less event to every connected client of this process

func BrokeredSleepURL

func BrokeredSleepURL(env map[string]string) *string

Absolute https NAS sleep endpoint, nil when unset or malformed with one warning per process

func BuildAnimatedStickerInjection

func BuildAnimatedStickerInjection(emoji string) string

Injection text for an animated or video sticker vision cannot read

func BuildAutoTTSOutputPath

func BuildAutoTTSOutputPath(platform Platform) (string, error)

Unique temp path for gateway auto TTS, ogg for Opus voice platforms and mp3 everywhere else

func BuildChannelContinuityNote

func BuildChannelContinuityNote(entry *SessionEntry, source *SessionSource) string

One line hint pointing a Slack or Discord lane at its auto reset predecessor, empty otherwise

func BuildChannelDirectory

func BuildChannelDirectory(ctx context.Context, adapters *orderedutil.Map[Platform, PlatformAdapter]) (*jsonutil.Object, error)

Builds the directory from connected adapters and session history, persists it and returns it

func BuildFooterLine

func BuildFooterLine(ctx context.Context, platformKey string, in FooterInputs) (string, error)

Footer text for the final response, empty when the footer is off or no field has data

func BuildFromSessions

func BuildFromSessions(ctx context.Context, platformName string) []*jsonutil.Object

Known channels and contacts from session origins, state.db first and sessions.json as the fallback

func BuildIdentifyPayload

func BuildIdentifyPayload() *jsonutil.Object

Default identify answer built from the pid record, code identity and served profiles

func BuildRelayCommandManifest

func BuildRelayCommandManifest() []map[string]any

Discord slash command manifest the relay hello declares, mirroring the native command tree

func BuildSessionContextPrompt

func BuildSessionContextPrompt(ctx context.Context, sc *SessionContext, redactPII bool) string

Current Session Context section with ids hashed for the model when redaction applies on the platform

func BuildSessionKey

func BuildSessionKey(ctx context.Context, source *SessionSource, groupSessionsPerUser, threadSessionsPerUser bool, profile string) (string, error)

Deterministic session key of a message source, the pinned detached route winning

func BuildStatusPayload

func BuildStatusPayload() *jsonutil.Object

Default status answer, the live runtime status stamped with the answering process

func BuildStickerInjection

func BuildStickerInjection(description, emoji, setName string) string

Injection text naming the sticker emoji and pack with its description

func BundledAuthz

func BundledAuthz(name string) map[string]any

Authorization env names a bundled platform declares, empty for other names

func BusyAcceptedHook

func BusyAcceptedHook(ctx context.Context) func(context.Context) error

Busy accepted hook a local session's pre command installed, nil on messaging

func CLITurn

func CLITurn(ctx context.Context, messageID any) *jsonutil.Object

Committed CLI turn fields of the admission whose event id is the message id, empty for any other turn

func CSVExtras

func CSVExtras(extra map[string]any, spec []CSVSpec)

Sets each key to the csv list of its raw text when the list is non empty

func CSVList

func CSVList(value string) []any

Comma separated items stripped with blanks dropped

func CacheAudioFromBytesAsync

func CacheAudioFromBytesAsync(ctx context.Context, data []byte, ext string) (string, error)

Caches audio bytes without blocking the caller

func CacheAudioFromURL

func CacheAudioFromURL(ctx context.Context, rawURL, ext string, retries int) (string, error)

Downloads an audio URL into the audio cache and returns the absolute path

func CacheDocumentFromBytesAsync

func CacheDocumentFromBytesAsync(ctx context.Context, data []byte, filename string) (string, error)

Caches document bytes without blocking the caller

func CacheImageFromBytesAsync

func CacheImageFromBytesAsync(ctx context.Context, data []byte, ext string) (string, error)

Caches image bytes without blocking the caller

func CacheImageFromURL

func CacheImageFromURL(ctx context.Context, rawURL, ext string, retries int) (string, error)

Downloads an image URL into the image cache and returns the absolute path

func CacheStickerDescription

func CacheStickerDescription(ctx context.Context, fileUniqueID, description, emoji, setName string) error

Stores a vision description under the stable sticker id through an atomic JSON write

func CacheVideoFromBytesAsync

func CacheVideoFromBytesAsync(ctx context.Context, data []byte, ext string) (string, error)

Caches video bytes without blocking the caller

func CancelBotReceiptTasks

func CancelBotReceiptTasks(a *SessionAuthority)

Requests cancellation of every Bot receipt watcher the authority started

func CancelQueuedDelivery

func CancelQueuedDelivery(ctx context.Context, profileHome, deliveryID, errText, reason string) (map[string]any, error)

Cancels an ownerless queued receipt, a claim or result that won the lock answered unchanged

func CancelTask

func CancelTask(ctx context.Context, task *AdapterTask)

Cancels the task and waits for it to unwind, a self cancel only requesting cancellation

func CanonicalHome

func CanonicalHome(h string) (string, error)

Canonical absolute home path with host case rules, the key every reservation uses

func CanonicalWhatsAppIdentifier

func CanonicalWhatsAppIdentifier(ctx context.Context, identifier string) (string, error)

Shortest alias of a sender, ties broken by code point order, empty for empty input

func CaptureGatewayArgv

func CaptureGatewayArgv(pid int) []string

Live argv of a running gateway for the update pause, nil when it is not a gateway

func CaptureLease

func CaptureLease(ctx context.Context) (context.Context, func())

Context leasing every path captured under it with no admitting authority until the returned func runs

func CaptureNativeMedia

func CaptureNativeMedia(ctx context.Context, paths []string) ([]any, error)

Captures staged files into the content addressed store as immutable bytes, returning their references

func CaptureWorkRecordLocked

func CaptureWorkRecordLocked(ctx context.Context, conn state.SQLiteConn, roomID, localGatewayID string, throughSeq *int64) (map[string]any, error)

Captures the source evidence of a room inside the caller's transaction

func CarryCallback

func CarryCallback(ctx context.Context, event, rewritten *MessageEvent)

Moves a callback's provenance onto a rebuilt event that keeps the exact source it authenticated

func CarryInboundDedup

func CarryInboundDedup(predecessor, adapter any)

Seeds a rebuilt adapter's dedup caches from the instance it replaces so replayed ids stay suppressed

func CatalogMapping

func CatalogMapping(ctx context.Context, o CatalogOptions) (*jsonutil.Object, error)

Canonical catalog mapping with its digest for the served target profile

func CgroupCleanupMain

func CgroupCleanupMain() int

Reaps the own cgroup under a systemd parent, one on refusal or failure

func ChatRunningKey

func ChatRunningKey(ctx context.Context, runner AuthorityRunner, route string, entry *SessionEntry) (string, error)

Running key of the conversation the chat's route names, for the runner's stop paths

func CheckAPITurn

func CheckAPITurn(ctx context.Context, a *SessionAuthority, ref SessionRef, payload *jsonutil.Object) error

Refuses an admitted API turn its session can no longer run

func CheckDeliveryID

func CheckDeliveryID(value string) error

ValueError a door call raises for a delivery id outside 32 to 64 lowercase hex characters

func CheckLiveOwner

func CheckLiveOwner(profileHome string, owner map[string]any) error

ValueError a door call raises for an owner pin before it looks at the message

func CheckMSGraphWebhookRequirements

func CheckMSGraphWebhookRequirements() bool

Whether the webhook server dependencies are available

func CheckRuntimeReadiness

func CheckRuntimeReadiness(ctx context.Context, requested string, strictProfileScope bool) (*jsonutil.Object, error)

Readiness verdict of the runtime a session would be built with, a failure naming the provider the user pinned

func CheckStartAttestation

func CheckStartAttestation(ctx context.Context, currentPids []int, scanned bool) (string, error)

Warning for a gateway that died after a start reported success, consuming the marker once

func CheckStateDBIntegrity

func CheckStateDBIntegrity(ctx context.Context, h string, deadlineS *float64) string

ok, absent, or the first quick_check complaint of state.db, check-incomplete when the deadline aborts it

func CheckSystemdTimingAlignment

func CheckSystemdTimingAlignment(ctx context.Context, drainTimeout, cronDrainTimeout float64) (*jsonutil.Object, error)

Whether systemd's TimeoutStopSec covers the stop budget, nil when aligned facts cannot be read

func CheckWebhookRequirements

func CheckWebhookRequirements() bool

Whether the platform webhook adapter dependencies are available

func CheckpointAgentKwargs

func CheckpointAgentKwargs(cfg map[string]any) map[string]any

Agent checkpoint arguments of a config with the defaults filled in

func ClassifyDeadError

func ClassifyDeadError(errorText string) string

Dead target kind from a raised error text, only whole chat deaths counting

func ClassifyPressure

func ClassifyPressure(availableKiB, totalKiB any) string

ok, elevated or critical from MemAvailable and MemTotal, unknown when the sample is missing or malformed

func ClassifyRefusedOwner

func ClassifyRefusedOwner(ownSession, ownerSession *uint32, ownElevated bool, ownerElevated *bool) string

Boundary code naming why a same user owner refused this client, empty to keep authorization

func ClassifySendError

func ClassifySendError(exc error, errorText string) string

Send failure kind of an error or error text, unknown when nothing matches

func CleanAttachmentFilename

func CleanAttachmentFilename(name any) string

Reduces an untrusted attachment name to a display safe basename, empty when unusable

func ClearHostRecord

func ClearHostRecord(role string)

Removes this process's record, never another owner's

func ClearIdentity

func ClearIdentity(source *SessionSource)

Drops the pinned identity, the rejection marks and the routed profile so the next event routes afresh

func ClearRestartFailureCount

func ClearRestartFailureCount(ctx context.Context, path, sessionKey string)

Drops a completed session's counter, removing the file once no counter is left

func ClearTakeoverMarker

func ClearTakeoverMarker(targetHome string)

Removes the takeover marker of targetHome, the process home when empty

func CoerceAllowSet

func CoerceAllowSet(raw any) map[string]bool

Allowlist entries of a YAML list, a JSON list literal or a comma separated scalar

func CoerceIDList

func CoerceIDList(raw any) map[string]struct{}

Admin or user id list as a set of strings, exported for the adapters that read allow_admin_from

func CoerceMessageTimestamp

func CoerceMessageTimestamp(value any, tz *time.Location) (float64, bool, error)

Epoch seconds of a number, time, ISO string or bracketed gateway stamp, false when uninterpretable

func CoercePlaintextGatewayCommand

func CoercePlaintextGatewayCommand(event *MessageEvent)

Rewrites an exact plaintext restart request in a DM into the restart command so it never reaches the agent

func CoercePort

func CoercePort(value any, def int) int

Integer of the value or the default when it does not convert or fit

func CoerceSystemdWatchdogSeconds

func CoerceSystemdWatchdogSeconds(value any, key string) int

Bounded positive watchdog interval in seconds, zero when unset or invalid

func CollectHistoryMediaPaths

func CollectHistoryMediaPaths(ctx context.Context, history []any) (map[string]struct{}, error)

Dedup set of media paths prior turns already delivered

func CollectRuntimeReadiness

func CollectRuntimeReadiness(ctx context.Context, configuredModel string, runtimeStatus *jsonutil.Object, activeAPIRuns, processCompletionQueueDepth, activeDelegations int) *jsonutil.Object

Runtime readiness of this home with status and counts only, never config values or paths

func CollectUnheldAPIImages

func CollectUnheldAPIImages(ctx context.Context, db *state.SessionDB) error

Collects API image bytes no admission holds any more

func CommandLineNamesIcebathHome

func CommandLineNamesIcebathHome(commandLC, homeLC string) bool

Whether a lower cased command line assigns exactly home, a space holding unquoted home included

func CommandLineRunsInlineSource

func CommandLineRunsInlineSource(tokens []string) bool

Whether tokens are an interpreter running inline source

func CommandVerdict

func CommandVerdict(name, arg string) (string, error)

Read, control or refused for a canonical registry command on a local session

func CommitAPIImages

func CommitAPIImages(ctx context.Context, content []any) ([]any, error)

Stages every inline data image deterministically and commits the bytes as immutable media

func CommitAndPublish

func CommitAndPublish(ctx context.Context, a *SessionAuthority, live *LiveSession, ref SessionRef, row *jsonutil.Object, response any, outcome string, captured *jsonutil.Object, settlement *TurnSettlement) error

Commits a turn's result off the stream lock and publishes its completion, the claim reading started until then

func CommittedRouteEnvelope

func CommittedRouteEnvelope(ctx context.Context, a *SessionAuthority, entry *SessionEntry) (*jsonutil.Object, error)

Envelope of the route's last committed admission, nil when none is recorded

func CommittedSubmissionPayload

func CommittedSubmissionPayload(ctx context.Context, rpc *HostedRoomAuthorityRPC, prompt string, attachments any) (*jsonutil.Object, error)

Committed admission payload of the producer's turn, its staged images admitted as durable media fields

func CompareScheduledTaskDrift

func CompareScheduledTaskDrift(registeredXML, templateXML string) []string

Drift fragments between a registered task export and the template, empty when aligned or unparsable

func CompileMentionPatterns

func CompileMentionPatterns(raw any, opts MentionPatternOptions) []*regexp2.Regexp

Case insensitive patterns from a config or env value, invalid ones logged and skipped

func CompletionAdmission

func CompletionAdmission(ctx context.Context, runner AuthorityRunner, event map[string]any) (*jsonutil.Object, error)

Admission carrying a completion's identity, for the runner's completion pre flight

func ComputeObligationID

func ComputeObligationID(sessionKey, messageRef, content string) string

Stable 24 hex id over session key, inbound message ref and content

func ConfigConnectedExtra

func ConfigConnectedExtra(keys ...string) func(cfg *PlatformConfig) bool

Config connected check true for a token, an api key or every named extra key

func ConfigDefaultLaunch

func ConfigDefaultLaunch(ctx context.Context) bool

Whether the active launch is a TUI launch whose viewer defaults reasoning from config

func ConfiguredEntryKey

func ConfiguredEntryKey(ctx context.Context, identity string, config map[string]any) string

Bare config key of the configured entry behind a custom identity, empty for anything else

func ConfiguredNofileSoftLimit

func ConfiguredNofileSoftLimit(cfg map[string]any) (int64, bool)

Configured runtime.nofile_soft_limit shared by the in process floor and service generators, false when disabled

func ConstructKwargs

func ConstructKwargs(frame *jsonutil.Object) (*jsonutil.Object, error)

Child side validated agent construct inputs of a bootstrap frame, empty when the owner sent none

func ConsumePlannedStopMarkerForSelf

func ConsumePlannedStopMarkerForSelf() (bool, error)

Whether this process is being intentionally stopped, the request kept as an accepted receipt when the checkpoint fails

func ConsumeRewrittenNotice

func ConsumeRewrittenNotice(defaultHome string) []string

The rewrite notice once more for the update summary, clearing its marker, empty when none is pending

func ConsumeStartAttestation

func ConsumeStartAttestation(ctx context.Context, generation, profileHome string)

Clears the start attestation of a profile home only while it is still the generation acted on

func ConsumeTakeoverMarkerForSelf

func ConsumeTakeoverMarkerForSelf() (bool, error)

Consumes the takeover marker, true for a planned takeover of this process

func ContinuedAPISession

func ContinuedAPISession(ctx context.Context, runner any, sessionID, requestID string) (string, error)

Live session a client addressed chain continues

func ControlHomeFor

func ControlHomeFor(home string, endpoint *GatewayEndpoint) string

Home whose control socket mints tickets for endpoint, the multiplexer's for a served profile

func ConvertTableToBullets

func ConvertTableToBullets(text string) string

Pipe tables rewritten as heading and bullet groups, fenced code left alone

func CoreShipsPlatform

func CoreShipsPlatform(name any) bool

Whether core ships an adapter for the name, a static member or a bundled platform plugin

func CreateRoom

func CreateRoom(ctx context.Context, dbPath string, in CreateRoomInput) (map[string]any, error)

Creates a room, or returns the identical existing room idempotently

func CronExecute

func CronExecute(ctx context.Context, a *SessionAuthority, ref SessionRef, row *jsonutil.Object, policy *LocalSessionPolicy) (string, error)

Runs a cron session's own frozen fire, any other input settling with the read only descriptor

func CronOwnerForHome

func CronOwnerForHome(home string) (authority any, ok bool)

Authority owning cron for a home in this process, false when unbound, foreign or its loop has closed

func CronOwnerOperation

func CronOwnerOperation(ctx context.Context, authority any, op string, params map[string]any) (map[string]any, error)

Runs one cron owner operation on the authority as the profile scheduler, the in process door of cron firing

func CronRPC

func CronRPC(ctx context.Context, connection CronRPCConnection, name string, params map[string]any) (map[string]any, error)

Cron RPC of a gateway connection, run as the connection's actor on its authority

func CurrentCodeSHA

func CurrentCodeSHA() (string, bool)

Full sha of the checkout on disk, false when unresolved

func CurrentGatewayRunner

func CurrentGatewayRunner() any

Gateway runner of this process, nil outside a running gateway

func CurrentMaxIterations

func CurrentMaxIterations(ctx context.Context) int

Per turn iteration budget of the profile in ctx, .env reloaded first for rotated keys outside multiplex

func CurrentProfileName

func CurrentProfileName(ctx context.Context) (string, error)

Exported currentProfileName

func CurrentProfileServedByRunningMultiplexer

func CurrentProfileServedByRunningMultiplexer(ctx context.Context) (bool, error)

Whether a live default multiplexer already serves the current named profile

func CurrentScopeKey

func CurrentScopeKey(ctx context.Context) string

Scope key of the home in ctx

func CurrentTurnMessages

func CurrentTurnMessages(messages []any, historyOffset int) ([]any, error)

Messages of the current turn after the history offset, falling back to the last user row

func DeclineError

func DeclineError(result any) string

Connector decline text verbatim, or the generic relay egress declined text

func DeclinedSend

func DeclinedSend(result *SendResult) bool

True when a send result carries a destination refusal in its raw response or its error text

func DecodeJSONListLiteral

func DecodeJSONListLiteral(raw any) any

JSON list literal of an allowlist decoded, anything else returned unchanged

func DecodeRoomGrant

func DecodeRoomGrant(secret []byte, token, permission string, now *float64) (*jsonutil.Object, error)

Grant payload once its signature, lifetime and operation verify, without a dispatch

func DefaultAttachmentRoot

func DefaultAttachmentRoot(dbPath string) string

Private byte store root beside the room state database

func DefaultGatewayMultiplexes

func DefaultGatewayMultiplexes(ctx context.Context, defaultHome string) (bool, error)

Whether the default profile's gateway serves every profile, the live record first then any explicit flag

func DeferLocalModelPick

func DeferLocalModelPick(ctx context.Context, a *SessionAuthority, live *LiveSession, result provider.ModelSwitchResult, effort string) (*jsonutil.Object, error)

Defers a typed model pick as the local session's canonical model mutation for the next boundary

func DeleteRoomLinkRecords

func DeleteRoomLinkRecords(ctx context.Context, dbPath, roomID string) (int64, error)

Deletes persisted peer routes after their target grants are revoked

func DeliverHeartbeat

func DeliverHeartbeat(ctx context.Context, runner AuthorityRunner, event map[string]any) (*bool, error)

One liveness tick delivered under the heartbeat lock, for the runner's watch notification drain

func DeliverToLiveOwner

func DeliverToLiveOwner(ctx context.Context, profileHome string, owner map[string]any, message, deliveryID, notificationCategory string) (map[string]any, error)

Durable admission answered at once without waiting for the owner

func DeliverToLiveOwnerAuthored

func DeliverToLiveOwnerAuthored(ctx context.Context, profileHome string, owner map[string]any, message, deliveryID, notificationCategory string, author map[string]any) (map[string]any, error)

Durable admission carrying the author of the delivered message

func DeliverToLocalChat

func DeliverToLocalChat(ctx context.Context, home, chatID, content string, diagnostic bool) (*string, error)

Admits a cron result into local chat chatID through this process's owner, nil once admitted else the error text

func DeliverWake

func DeliverWake(ctx context.Context, adapter PlatformAdapter, opts WakeOptions) error

Delivers a wake turn to the session behind the adapter, an error so the caller can retry

func DemoteRoom

func DemoteRoom(ctx context.Context, dbPath string, roomIDValue, observedGatewayValue, observedEpochValue any, now *float64) (map[string]any, error)

Fences this gateway's stale room authority against a proven newer epoch, idempotent per lineage

func DeriveGatewayBusy

func DeriveGatewayBusy(gatewayRunning bool, gatewayState, activeAgents any) (bool, error)

Whether a live serving gateway has active agents

func DeriveGatewayDrainable

func DeriveGatewayDrainable(gatewayRunning bool, gatewayState any) bool

Whether a gateway is live and in a serving state

func DescribeHostRecord

func DescribeHostRecord(r *HostRecord) string

One line human description used by attach messages and conflict logs, a gateway record binding no port

func DescribeProxyError

func DescribeProxyError(err error, proxyURL string) string

"<failure> via <scheme://host:port>" for an error raised through a proxy URL that holds anything its rendering leaves out, user info, a path, a query or a malformed authority; empty when the proxy holds nothing of the kind and the caller keeps the full error text. A transport may repeat the proxy URL in its error text quoted, split or reformatted, so no part of that text is shown

func DetachedRestartWatcherMain

func DetachedRestartWatcherMain(ctx context.Context, args []string, stderr io.Writer) int

Waits up to the bound for the pid to exit, then spawns the command detached with its output discarded

func DetachedRouteOf

func DetachedRouteOf(source *SessionSource) *string

Detached conversation route the source answers on, nil for a chat's live conversation

func DetectCodeSkew

func DetectCodeSkew() (bootRev, diskRev string, ok bool)

Short boot and disk revisions when the checkout drifted since boot

func DetectSupervisor

func DetectSupervisor() string

Supervisor kind of this process, the launch environment answer

func DetectUncleanExit

func DetectUncleanExit(ctx context.Context, h string) (*jsonutil.Object, error)

Evidence of an unclean previous life, nil when the sentinel is clean, absent or held by a live owner

func DisarmStartupWatchdog

func DisarmStartupWatchdog()

Disarms the process wide startup watchdog when one is armed

func DisbandRoom

func DisbandRoom(ctx context.Context, dbPath string, roomIDValue, expectedGatewayValue, expectedEpoch any, now *float64) (map[string]any, error)

Tombstones a room id permanently and idempotently

func DiscardDeadHostRecord

func DiscardDeadHostRecord(role string) bool

Retracts the role record once its owner is provably gone, holding the host lock across the re read and unlink

func DiscardStreamingTTSCompletedTurn

func DiscardStreamingTTSCompletedTurn(adapter PlatformAdapter, sessionKey string, runGeneration int)

Forgets the streamed audio marker of a finished turn so the next turn of the session is not suppressed

func DiscordChannelIDFromLink(value string) (string, bool)

Channel id from a pasted Discord channel link, ok false for message links and anything else

func DiscordToolsLoaded

func DiscordToolsLoaded(ctx context.Context) bool

Whether the agent will have Discord tools this session under the scoped token and toolset config

func DispatchCgroupCleanupEntry

func DispatchCgroupCleanupEntry()

Runs the cgroup reaper and exits when the process was started with the hidden entry argument

func DispatchDetachedRestartWatcherEntry

func DispatchDetachedRestartWatcherEntry(ctx context.Context)

Runs the detached restart watcher entry and exits when this process was launched as one

func DispatchGatewayRestartWatcherEntry

func DispatchGatewayRestartWatcherEntry(ctx context.Context)

Runs the restart watcher entry and exits when this process was launched as one

func DispatchKanbanWorkerClientEntry

func DispatchKanbanWorkerClientEntry(ctx context.Context)

Runs the worker client and exits when argv carries its entry word, always writing the exit trailer

func DispatchSharedBusy

func DispatchSharedBusy(ctx context.Context, adapter PlatformAdapter, event *MessageEvent, sessionKey string, durable bool) error

Commits a busy follow up to the authority FIFO, returning once its place in the chat order is fixed

func DispatchStderrTimestampEntry

func DispatchStderrTimestampEntry()

Runs the wrapper and exits when the process was started with the hidden entry argument

func DispatchSystemdStopMarkEntry

func DispatchSystemdStopMarkEntry(ctx context.Context)

Runs the stop marker and exits when the process was started with the hidden entry argument

func DispatchUpdateHelperEntry

func DispatchUpdateHelperEntry(ctx context.Context)

Runs the update helper entry and exits when this process was launched as one

func DisplaceableBotChat

func DisplaceableBotChat(ctx context.Context, a *SessionAuthority, row *jsonutil.Object) (string, error)

Id holding the canonical title when the Bot Chat is a conversation no delivery can adopt, else empty

func DisplayKindForEvent

func DisplayKindForEvent(ctx context.Context, event DisplayEvent) any

Persisted user row kind of a turn, machinery only for self injected events

func DisplayMetadataForEvent

func DisplayMetadataForEvent(ctx context.Context, event DisplayEvent) map[string]any

Producer card text plus the title preview the canonical admission committed for the event

func DisplayProjection

func DisplayProjection(ctx context.Context, history []map[string]any, profileHome string) ([]any, error)

Display rows of a stored history as viewers render it

func DisplayTurnScope

func DisplayTurnScope(ctx context.Context, admissionID string, committed map[string]any) context.Context

Binds the committed presentation to the admission event for the returned context only

func DocumentMimeToExt

func DocumentMimeToExt() map[string]string

MIME to extension inverse of the supported document table

func Download

func Download(ctx context.Context, service *CanonicalHostedRoomService, actor Principal, params map[string]any) (map[string]any, error)

Reads a committed room file for an actor allowed to read the room

func DrainTranscriptSpool

func DrainTranscriptSpool(ctx context.Context, sessionID string, replay func(message map[string]any) error, dbKnownFailing bool) (int, int, error)

Replays the spooled cap drops of a session in drop order, returning replayed and remaining counts

func DriverAdmitTask

func DriverAdmitTask(ctx context.Context, dbPath string, identity TaskIdentity, payload any, clock DriverClock) (map[string]any, error)

Persists a queued task, or returns the identical admission

func DriverBeginTaskCancel

func DriverBeginTaskCancel(ctx context.Context, dbPath string, identity TaskIdentity, cancelIDValue any, expectedCancelGeneration int64, clock DriverClock) (map[string]any, error)

Persists a stop intent without claiming the remote run stopped

func DriverCancelTask

func DriverCancelTask(ctx context.Context, dbPath string, identity TaskIdentity, cancelIDValue any, expectedCancelGeneration int64, clock DriverClock) (map[string]any, error)

Cancels a queued task before any external work was admitted

func DriverCompleteTaskCancel

func DriverCompleteTaskCancel(ctx context.Context, dbPath string, identity TaskIdentity, cancelIDValue any, expectedCancelGeneration int64, clock DriverClock) (map[string]any, error)

Commits cancellation only after the transport acknowledges the exact Stop

func DriverDeferIndeterminateTask

func DriverDeferIndeterminateTask(ctx context.Context, dbPath string, identity TaskIdentity, lease DriverLease, expectedExecutionGeneration, expectedCancelGeneration int64,
	reasonValue any, clock DriverClock) (map[string]any, error)

Fences one uncertain attempt and releases later room work

func DriverDeferNotAdmittedTask

func DriverDeferNotAdmittedTask(ctx context.Context, dbPath string, attempt TaskAttempt, reason string, clock DriverClock) (map[string]any, error)

Defers a running task whose work never reached its member, the reason kept for the room and its retry

func DriverGetTask

func DriverGetTask(ctx context.Context, dbPath string, identity TaskIdentity) (map[string]any, error)

Reads one task without mutating its state

func DriverGetTaskForTurn

func DriverGetTaskForTurn(ctx context.Context, dbPath string, identity TaskIdentity) (map[string]any, error)

Immutable admission of a turn including older payload versions, nil when none

func DriverListTasks

func DriverListTasks(ctx context.Context, dbPath string, roomIDValue any, status *string) ([]map[string]any, error)

Room tasks in deterministic admission order, optionally of one status

func DriverPrunePublishedTerminalTasks

func DriverPrunePublishedTerminalTasks(ctx context.Context, dbPath string, roomIDValue any, clock DriverClock, retentionSeconds float64, retain any) (int64, error)

Bounds execution rows once their outcomes are durable in the room log

func DriverRecoverRoom

func DriverRecoverRoom(ctx context.Context, dbPath string, lease DriverLease, clock DriverClock) (map[string][]TaskIdentity, error)

Fences abandoned running attempts without requeueing uncertain work, returning queued and indeterminate identities

func DriverReleaseLease

func DriverReleaseLease(ctx context.Context, dbPath string, lease DriverLease, clock DriverClock) (map[string]any, error)

Releases the exact active lease generation idempotently

func DriverRequeueDeferredTask

func DriverRequeueDeferredTask(ctx context.Context, dbPath string, identity TaskIdentity, lease DriverLease, expectedExecutionGeneration, expectedCancelGeneration int64, clock DriverClock) (map[string]any, error)

Retries a fenced deferred turn under a new generation

func DriverRequeueIndeterminateTask

func DriverRequeueIndeterminateTask(ctx context.Context, dbPath string, identity TaskIdentity, lease DriverLease, expectedExecutionGeneration, expectedCancelGeneration int64, clock DriverClock) (map[string]any, error)

Retries uncertain work after an operator accepts at least once risk

func DriverRequeueNotAdmittedTask

func DriverRequeueNotAdmittedTask(ctx context.Context, dbPath string, attempt TaskAttempt, clock DriverClock) (map[string]any, error)

Returns a running task to its durable queue after proven non admission

func DriverResolveIndeterminateCancellation

func DriverResolveIndeterminateCancellation(ctx context.Context, dbPath string, identity TaskIdentity, lease DriverLease, expectedExecutionGeneration, expectedCancelGeneration int64,
	cancelIDValue any, clock DriverClock) (map[string]any, error)

Commits a verified terminal cancellation of an uncertain attempt

func DriverResolveIndeterminateTask

func DriverResolveIndeterminateTask(ctx context.Context, dbPath string, identity TaskIdentity, lease DriverLease, expectedExecutionGeneration, expectedCancelGeneration int64,
	settlementID any, status string, result any, clock DriverClock) (map[string]any, error)

Commits a verified historical receipt under the current room lease

func DriverSettleStoppingTask

func DriverSettleStoppingTask(ctx context.Context, dbPath string, identity TaskIdentity, lease DriverLease, expectedExecutionGeneration, expectedCancelGeneration int64,
	settlementID any, status string, result any, clock DriverClock) (map[string]any, error)

Commits a completion that won the race with an unacknowledged Stop

func DriverSettleTask

func DriverSettleTask(ctx context.Context, dbPath string, attempt TaskAttempt, settlementID any, status string, result any, clock DriverClock) (map[string]any, error)

Commits one terminal result while every lease and task fence still matches

func DropRejectedRoute

func DropRejectedRoute(ctx context.Context, adapter PlatformAdapter, source *SessionSource)

Logs an inbound event whose route targets an unserved profile, refusing it in channel when that profile is parked

func EAActionLabels

func EAActionLabels(ctx context.Context) map[string]string

Localized button label for each of the four approval tiers

func EADefaultReasonLocalized

func EADefaultReasonLocalized(ctx context.Context) string

Localized reason shown when the approval carries none

func EAHeaderLocalized

func EAHeaderLocalized(ctx context.Context) string

Localized approval header in the active display language

func EAReasonLabelLocalized

func EAReasonLabelLocalized(ctx context.Context) string

Localized label in front of the reason the command was flagged

func EASmartDenyLineLocalized

func EASmartDenyLineLocalized(ctx context.Context) string

Localized sentence saying a smart deny override covers one operation only

func EditPluginMessage

func EditPluginMessage(ctx context.Context, target, messageID any, text, pluginID string) map[string]any

Edits message id in place, a surface that cannot edit getting a fresh message marked fallback

func EffectiveStopDrainTimeout

func EffectiveStopDrainTimeout(runner StopTiming) float64

Drain budget of the stop in progress, launchd capped only for a signal driven stop

func EffectiveStopWatchdogDelay

func EffectiveStopWatchdogDelay(runner StopTiming, watchdogDelay any) float64

Watchdog leash of the stop in progress, clamped below the launchd exit timeout for a signal driven stop

func EncodeFrame

func EncodeFrame(frame any) ([]byte, error)

Compact ASCII JSON line of a frame, ValueError past the frame ceiling or for a non finite float

func EncodeHTTPXMultipart

func EncodeHTTPXMultipart(parts []MultipartPart) ([]byte, string, error)

Multipart body and content type of the parts in order under a random hex boundary like httpx

func EndIdleACPSessions

func EndIdleACPSessions(ctx context.Context, a *SessionAuthority) (int, error)

Ends every ACP session of the authority nobody is viewing, the stop being their end

func EndsWithPartialSilenceMarker

func EndsWithPartialSilenceMarker(text any) bool

True while a streamed reply's last line could still become a closing silence marker

func EnsureAuthorityHostedService

func EnsureAuthorityHostedService(ctx context.Context, runner any, a *SessionAuthority) error

Prepares the hosted room transport of one served authority

func EnsureClosedCodeFences

func EnsureClosedCodeFences(text string) string

Text with an orphaned code fence or inline backtick closed so a truncated reply renders sanely

func EnsureGatewayService

func EnsureGatewayService(ctx context.Context, w io.Writer, o ServiceSetupOptions) (bool, error)

Starts an existing gateway service and installs one only with explicit setup consent, false leaving startup to the caller

func EnsureHostStateDir

func EnsureHostStateDir(ctx context.Context) (string, error)

Rendezvous directory created owner only and tightened when a umask left it wider

func EnsureUserSystemdEnv

func EnsureUserSystemdEnv()

Pushes the user manager values onto this process, the env the update pause and fleet restart runners of pkg/selfupdate and the gateway run under systemd hand their children

func EnvExtras

func EnvExtras(ctx context.Context, extra map[string]any, spec []EnvSpec, strip bool)

Writes each spec whose env value is truthy, Int specs parsing an int and skipping a malformed one

func EnvFirst

func EnvFirst(ctx context.Context, envs []string) string

First truthy value among env names, a single name returning its value as is

func EnvHomeChannel

func EnvHomeChannel(ctx context.Context, cfg *GatewayConfig, platform Platform, envBase string, strip bool)

Sets the home channel from the env base and its name and thread id when the platform is configured

func EnvIsConnected

func EnvIsConnected(names ...string) func(ctx context.Context, cfg *PlatformConfig) (bool, error)

Connected check for env only platforms, every named var non blank through the gateway facade env reader at call time

func EnvProxyForRedaction

func EnvProxyForRedaction(targets ...string) string

Proxy value of the environment to hand DescribeProxyError for an error raised by a transport that reads the proxy environment itself: a value that cannot be shown in full before any that can, none when the environment sets no proxy or NO_PROXY keeps every target off the proxy

func EnvReplyMode

func EnvReplyMode(ctx context.Context, cfg *GatewayConfig, platform Platform, env string)

Sets the reply mode from env when it names off, first or all

func EnvironmentPairs

func EnvironmentPairs(value string) (map[string]string, error)

Key value pairs of a systemd environment list, unverified on C escapes or a bare word

func ErrorKindValue

func ErrorKindValue(err error) string

Python exception class an error stands for, empty when it carries none

func EscalateWedgedGateway

func EscalateWedgedGateway(pid int) bool

Bounded SIGTERM then SIGKILL of a gateway whose loop is proven dead, true once it is gone

func EscapeCodeFencesForDisplay

func EscapeCodeFencesForDisplay(text string) string

Text with each triple backtick escaped so it can sit inside an outer code block

func ExclusiveMaintenance

func ExclusiveMaintenance(ctx context.Context, homes []string, purpose string) (context.Context, func(), error)

Reserves the homes' exact locks for maintenance, nested calls under the returned context reusing the reservation

func ExecutingAdmission

func ExecutingAdmission(ctx context.Context) bool

True inside the execution of a claimed admission, where ingress hooks already ran

func ExecutionPolicyMapping

func ExecutionPolicyMapping(ctx context.Context, targetProfile string, cfg any) (*jsonutil.Object, error)

Effective API server policy from the served profile's own config, loaded inside its scope when cfg is nil

func ExecutionResultOf

func ExecutionResultOf(ctx context.Context) *jsonutil.Object

Captured result of the executing admission, nil outside an execution

func ExpandWhatsAppAliases

func ExpandWhatsAppAliases(ctx context.Context, identifier string) (map[string]bool, error)

Phone, LID and JID aliases of a WhatsApp identifier that match the same principal

func ExplicitMultiplexFlag

func ExplicitMultiplexFlag(ctx context.Context, defaultHome string) (*bool, error)

Operator's explicit multiplex choice for the default profile, nil when the setting is left at its default

func ExtForMime

func ExtForMime(mime string, overrides map[string]string, useDefaults, useMimetypes bool, fallback string) string

Dotted extension of a mime from the overrides, the shared table and the mimetypes guess in turn, else the fallback

func ExtraOrSecret

func ExtraOrSecret(ctx context.Context, extra map[string]any, key, env string, def any, blankIsUnset bool) (any, error)

Per profile setting from the scoped env or the setting a folded name moved to, then the profile's YAML extra, then the default

func ExtractCacheBustingConfig

func ExtractCacheBustingConfig(ctx context.Context, userConfig map[string]any) map[string]any

Config values whose change rebuilds the cached agent keyed section dot key, with registry generation and memory identity

func ExtractLocalFiles

func ExtractLocalFiles(ctx context.Context, content string) ([]string, string)

Bare local file paths with deliverable extensions that exist on disk, outside code, and the cleaned text

func FacadeEnvValue

func FacadeEnvValue(ctx context.Context, key string) (string, error)

Value of an env var through the gateway facade env reader at call time

func FactoryModuleDeclares

func FactoryModuleDeclares(entry *PlatformEntry, declares func(AdapterTraits) bool) bool

Whether any adapter class defined beside the entry's factory declares the trait

func FenceStateAfter

func FenceStateAfter(text string, inCode bool, lang string) (bool, string)

Final code fence state and language after walking the lines and toggling on each fence line

func FetchRemoteMedia

func FetchRemoteMedia(ctx context.Context, raw string) (string, error)

Host path of a validated copy of a sandbox file, empty when no remote backend is active or the path is refused

func FilterLocalDeliveryPaths

func FilterLocalDeliveryPaths(ctx context.Context, paths []string, sessionKey string) ([]string, error)

Safe bare local file paths for a session, unsafe ones logged and dropped

func FinalizeUpdateOutput

func FinalizeUpdateOutput(state *UpdateOutputState)

Restores the stream pair of an installed state and closes its update log handle

func FinalizeWebhook

func FinalizeWebhook(ctx context.Context, authority *SessionAuthority, receipt AdmissionReceipt) (bool, error)

Ends only the settled admitted generation of a webhook session, atomically with the epoch fence

func FindCanonicalLiveOwner

func FindCanonicalLiveOwner(ctx context.Context, profileHome string) (map[string]any, error)

Profile authority and its exact Bot Chat without a lease, nil when the profile has no store, a ValueError kind refusal while the authority is not ready

func FindGatewayPIDs

func FindGatewayPIDs(ctx context.Context, h string) ([]int, error)

Running gateway pids of the profile whose home is h

func FindGatewayPIDsFor

func FindGatewayPIDsFor(ctx context.Context, exclude map[int]bool, allProfiles bool) ([]int, error)

Running gateway pids of the profile in effect, or of every profile with allProfiles

func FiniteClarifyReply

func FiniteClarifyReply() *jsonutil.Object

Headless clarify reply of a finite turn whose viewer cannot answer

func FiniteTurnRequired

func FiniteTurnRequired(ctx context.Context) any

Finite turn requirement of the executing admission, nil outside a finite prompt

func FiniteTurnScope

func FiniteTurnScope(ctx context.Context, finite any, unattended bool) context.Context

Context bound to an admission's finite flag, unattended only when the turn is finite too

func FitPrefix

func FitPrefix(text string, budget int, measure func(string) int, suffix string) string

Text unchanged or its longest prefix within the measured budget followed by the suffix

func FixedHostedRooms

func FixedHostedRooms(bindings ...HostedRoomBinding) func() ([]HostedRoomBinding, error)

Fixed room list as a provider

func FloodNotBefore

func FloodNotBefore(updatedAt, lastError any) float64

Earliest moment a flood refused row may be resent, its refusal stamp plus the platform's wait

func FloodRetryDelay

func FloodRetryDelay(seconds any) float64

Redelivery timer sleep for a wait of seconds, capped at fifteen minutes plus two seconds of slack

func FloodWaitSeconds

func FloodWaitSeconds(err any, def float64) float64

Wait the platform asked for in a flood error, def when unreadable or not positive

func FlushAgentHistoryToFile

func FlushAgentHistoryToFile(ctx context.Context, sessionID *string, history []any)

Writes an agent in memory transcript outside the database before teardown, swallowing every failure

func FlushOverflowToFile

func FlushOverflowToFile(ctx context.Context, overflowBySession map[string][]any, reason string) (int, error)

Serialises the FIFO overflow tails one payload per event with its arrival seq and returns the count

func FlushPendingToFile

func FlushPendingToFile(ctx context.Context, pending map[string]*MessageEvent, reason string) (int, error)

Serialises the non empty pending slots of an adapter and returns how many were written

func FlushPendingValuesToFile

func FlushPendingValuesToFile(ctx context.Context, pending map[string]any, reason string) (int, error)

Serialises non empty pending slots holding events, runner text or mappings and returns the count

func FlushRuntimeStatus

func FlushRuntimeStatus(timeout time.Duration) bool

Waits boundedly for every runtime status update submitted so far

func FlushRuntimeStatusAsync

func FlushRuntimeStatusAsync(ctx context.Context, timeout time.Duration) (bool, error)

Flush that returns early with the context error when the caller stops waiting

func FoldCatalogText

func FoldCatalogText(value string) string

Case and accent folded text of a catalog name

func FoldedEnvValue

func FoldedEnvValue(ctx context.Context, name string) (value string, folded bool)

Value of an env name that is the override of a setting, the setting's text for the profile ctx serves, folded false for a name that is no setting

func FollowDetachedPin

func FollowDetachedPin(ctx context.Context, runner AuthorityRunner, evt map[string]any) (map[string]any, error)

Background result on its pinned conversation's detached key, for the runner's notification code

func FollowHandOff

func FollowHandOff(ctx context.Context, a *SessionAuthority, source *SessionSource, route, owner string, localOwner *string) error

Moves the local mount a viewer still holds onto the lane a handoff repointed

func ForeignLockRecovery

func ForeignLockRecovery(path string) string

Recovery text for a foreign gateway.lock this user cannot read

func ForeignSystemdUnitHome

func ForeignSystemdUnitHome(ctx context.Context, system bool) (string, error)

Pinned home of the scope's unit when it belongs to another install, empty otherwise

func FormatApprovalDeadlineLine

func FormatApprovalDeadlineLine(ctx context.Context, timeoutS int) string

Last line of every approval prompt saying that doing nothing is a safe no

func FormatApprovalTimedOutNotice

func FormatApprovalTimedOutNotice(ctx context.Context, timeoutS int) string

Localized timed out notice for a timeout in seconds

func FormatApprovalWindow

func FormatApprovalWindow(seconds int) string

Human wording for a timeout such as 5 minutes, shared with the CLI notice

func FormatChoicePage

func FormatChoicePage[T any](ctx context.Context, options []T, page, perPage int) ([]T, map[string]any)

Clamped picker page of options with page, total_pages, start, end, total and page_info

func FormatContextForLog

func FormatContextForLog(ctx *jsonutil.Object) string

One scannable log line of a shutdown context, parent identity but never argv

func FormatDirectoryForDisplay

func FormatDirectoryForDisplay(ctx context.Context, platforms *jsonutil.Object) (string, error)

Channel directory as the human readable target list shown to the model, the on disk directory when nil

func FormatGatewayProcessNotification

func FormatGatewayProcessNotification(evt map[string]any) string

Important message of a watch pattern event, empty for an event type the gateway does not format

func FormatIngressURLLines

func FormatIngressURLLines(urls map[string]string, indent string) []string

One indented platform and URL line per platform, sorted by platform

func FormatMessageTimestamp

func FormatMessageTimestamp(value any, tz *time.Location) (string, error)

Timestamp rendered as a bracketed weekday, date, time and zone name, empty when unrenderable

func FormatRuntimeFooter

func FormatRuntimeFooter(ctx context.Context, in FooterInputs, fields []string) (string, error)

Footer line of the fields that have data, joined by the separator

func FormatSessionStallNotification

func FormatSessionStallNotification(idleSeconds float64) string

User facing stall notice with the idle minutes, at least one

func ForwardToOwner

func ForwardToOwner(ctx context.Context, home string, forward A2AForward, timeout time.Duration) (map[string]any, error)

Forwards one turn to the home's owner and waits for its terminal receipt, a timeout never cancels accepted work

func GatewayLockDir

func GatewayLockDir() string

Per user rendezvous directory for machine local locks, ICEBATH_GATEWAY_LOCK_DIR overriding

func GatewayLoop

func GatewayLoop(ctx context.Context) (any, bool)

Running runner with an open loop and whether ctx runs on that loop, nil without one

func GatewayPidHome

func GatewayPidHome(ctx context.Context, pid int) string

GatewayPidHome is the home a gateway pid runs on from its live environment, else its ledger witness

func GatewayPidInUpdateScope

func GatewayPidInUpdateScope(ctx context.Context, pid int, scope map[string]bool) (inScope bool, known bool)

GatewayPidInUpdateScope reports whether a gateway pid runs on an owned home, known false when its home is unreadable

func GatewayProfileHome

func GatewayProfileHome(home string) (string, error)

Profile home whose gateway serves home, the owner a private overlay's lock names

func GatewayRestartWatcherMain

func GatewayRestartWatcherMain(ctx context.Context, args []string, stderr io.Writer) int

Waits for the old pid to exit then respawns the command detached, its output in the gateway stdio log

func GatewayRoomGrantSecret

func GatewayRoomGrantSecret(ctx context.Context, root string) ([]byte, error)

Gateway only RoomLink signing secret of the installation root, minted atomically on first use

func GatewayRunArgsForProfile

func GatewayRunArgsForProfile(profile string) []string

Installation bound gateway run argv of a profile, the default profile carrying no selector

func GatewayRunnerRef

func GatewayRunnerRef() plugins.PlatformActionRunner

Runner as the platform actions facade drives it, nil without a runner

func GatewayRuntimeLockPath

func GatewayRuntimeLockPath(h string) string

Runtime lock path of the gateway whose home is h

func GatewaySetup

func GatewaySetup(ctx context.Context, w io.Writer) error

GatewaySetup runs icebath gateway setup, messaging platforms first then the service offer, printing to w

func GatewayTrustEnv

func GatewayTrustEnv(ctx context.Context) bool

Whether gateway HTTP clients of the profile ctx serves honor proxy and certificate env, gateway.trust_env

func GatewayWSTarget

func GatewayWSTarget(endpoint *GatewayEndpoint, ticket string) (string, []string)

WebSocket URL and subprotocols for dialing an owner with a session ticket

func GatewayWSTicketFromSubprotocol

func GatewayWSTicketFromSubprotocol(ws BoundaryPeer) (string, string)

Ticket and outcome none, invalid or ok from an unambiguous gateway WebSocket protocol set

func GenerateLaunchdPlist

func GenerateLaunchdPlist(ctx context.Context) (string, error)

LaunchAgent plist running this profile's supervised gateway with its PATH, home and restart policy

func GenerateSystemdUnit

func GenerateSystemdUnit(ctx context.Context, system bool, runAsUser string) (string, error)

Systemd unit running this profile's supervised gateway, a system unit as the target account

func GetCachedStickerDescription

func GetCachedStickerDescription(ctx context.Context, fileUniqueID string) map[string]any

Cached description entry of a sticker unique id, nil when never described

func GetInstalledSystemdScopes

func GetInstalledSystemdScopes(ctx context.Context) ([]string, error)

Scope labels with an installed unit, user first, each unit path counted once

func GetLaunchdLabel

func GetLaunchdLabel(ctx context.Context) (string, error)

Launchd label of the profile in effect

func GetLaunchdPlistPath

func GetLaunchdPlistPath(ctx context.Context) (string, error)

LaunchAgents plist of the gateway label under the password database home, the real home when lookup fails

func GetLifecycleSentinelPath

func GetLifecycleSentinelPath(ctx context.Context, h string) string

state/gateway.lifecycle.json under the given home or the process home

func GetLoopHeartbeatPath

func GetLoopHeartbeatPath(ctx context.Context, h string) string

state/gateway.heartbeat under the given home or the process home

func GetLoopTickSocketPath

func GetLoopTickSocketPath(ctx context.Context, h string, pid *int) string

state/gateway.loop-tick.<pid>.sock, the pid defaulting to this process

func GetProcessStartTime

func GetProcessStartTime(pid int) any

Start time fingerprint of pid, /proc ticks or psutil birth in centiseconds, nil when unavailable

func GetRestartDrainTimeout

func GetRestartDrainTimeout(ctx context.Context) (float64, error)

Seconds a restart may drain in flight turns, from the environment override else the agent config

func GetRestartExitWaitBudget

func GetRestartExitWaitBudget(ctx context.Context) (float64, error)

CLI wait for gateway exit after SIGUSR1 covering the after turn wait, drain and cron floor

func GetRunningPid

func GetRunningPid(pidPathArg string, cleanupStale bool) (int, bool, error)

Pid of a running gateway proven by the held lock and its records, false when none runs

func GetRunningPidCached

func GetRunningPidCached(pidPathArg string, cleanupStale bool, ttl time.Duration) (int, bool, error)

Running pid cached briefly for polling, invalidated whenever the pid, lock or status file changes

func GetRunningPidIdentityStrict

func GetRunningPidIdentityStrict(pidPathArg string) (int, float64, bool, error)

Verified live gateway identity behind a held lock, an error for ambiguous or malformed runtime state

func GetRuntimeStatusRunningPid

func GetRuntimeStatusRunningPid(runtime *jsonutil.Object, expectedHome string) (int, bool, error)

Live gateway pid of a runtime status record proven against the process and its home, false otherwise

func GetScopedSecret

func GetScopedSecret(ctx context.Context, name, def string, externalFallback bool) (string, error)

Scope aware credential read, an unscoped default profile falling back to the process env

func GetServiceName

func GetServiceName(ctx context.Context) (string, error)

Systemd service name, icebath-gateway for the bare owner and icebath-gateway-suffix otherwise

func GetServicePIDs

func GetServicePIDs(ctx context.Context, allProfiles bool) ([]int, error)

Pids of the systemd and launchd gateway services, the whole fleet with allProfiles

func GetShutdownWatchdogDumpPath

func GetShutdownWatchdogDumpPath(ctx context.Context, h string) string

logs/gateway-shutdown-watchdog.log under the given home or the process home

func GetStartupWatchdogDumpPath

func GetStartupWatchdogDumpPath(h string) string

Path of logs/gateway-startup-watchdog.log under h, the process home when h is empty

func GetSystemdLingerStatus

func GetSystemdLingerStatus(ctx context.Context, username string) (*bool, string)

Linger state of the user or the caller, nil with the reason when it cannot be determined

func GetSystemdUnitPath

func GetSystemdUnitPath(ctx context.Context, system bool) (string, error)

Unit file path of the gateway service in system or user scope

func Getenv

func Getenv(ctx context.Context, name, def string) string

Env value as a string with a default for an unset name, the platform_env getenv adapters call

func GoRunExecutable

func GoRunExecutable() string

Path of this process's executable when `go run` built it, else empty

func GracefulRestartViaSIGUSR1

func GracefulRestartViaSIGUSR1(pid int, drainTimeout float64, onProgress func()) bool

Sends the drain aware restart signal and waits for the exit, false when unsent or alive at the timeout

func GreedyPackBlocks

func GreedyPackBlocks(blocks []string, maxLength int, lenFn func(string) int, sep string, overflow func(block string) []string) []string

Blocks packed greedily into chunks within maxLength, an oversized block going through overflow when given

func GroupMethods

func GroupMethods() []string

Every room method the gateway route serves, in wire order

func HandOverHeldInbound

func HandOverHeldInbound(ctx context.Context, source, target any)

Moves the inbound the source holds to the target when the target can adopt it

func HandedRoomIDs

func HandedRoomIDs(ctx context.Context, source string) (map[string]bool, error)

Every room the source handed to the gateway store, recorded or still only fenced

func HandoffGatewayID

func HandoffGatewayID(ctx context.Context) (string, error)

Authority a standalone room is fenced to once the gateway store holds it

func HandshakeError

func HandshakeError(resp *http.Response, err error) error

Dial error as websockets connect raises it, a refused upgrade naming the HTTP status it got

func HasCredentialPlatform

func HasCredentialPlatform(adapters any, owned any) bool

True when the profile has a bot of its own, a local only adapter map holds no platform credential

func HasLiveListener

func HasLiveListener(host string, port int) bool

Whether something accepts connections on host and port, any failure but a refusal reading as live

func HasMailbox

func HasMailbox(profileHome string) bool

Whether any delivery was ever admitted for this profile, the mailbox existing only after one

func HasPendingMediaDirective

func HasPendingMediaDirective(cleaned string) bool

True while the end of the cleaned streamed text may still become a hidden attachment

func HashChatID

func HashChatID(value string) string

Chat id hashed after its platform prefix, the whole value hashed without one

func HashID

func HashID(value string) string

Twelve character hex sha256 prefix of an identifier

func HashSenderID

func HashSenderID(value string) string

Sender id rendered as user_ and its twelve hex hash

func HoldsAdmission

func HoldsAdmission(ctx context.Context, a *SessionAuthority, sessionID string) (bool, error)

Whether the authority's store holds a canonical admission for the session, true for a retiring store that cannot answer

func HomeInUpdateScope

func HomeInUpdateScope(ctx context.Context, h string, scope map[string]bool) bool

HomeInUpdateScope reports whether a home is one this update owns, the live scope when scope is nil

func HomeModeUnsafe

func HomeModeUnsafe(st *syscall.Stat_t, path string) bool

Whether a home mode lets another user write it, group write private only for the owner's own group

func HostCleanupOnExit

func HostCleanupOnExit(role string)

Registers the role for cleanup at exit and on a terminating signal, other signal handlers still running

func HostHeaderHostname

func HostHeaderHostname(hostHeader string) string

Lowered hostname of a valid Host authority, empty for ambiguous ports, bad brackets or URL syntax

func HostLivenessIsProven

func HostLivenessIsProven(r *HostRecord) bool

Whether the record incarnation probe positively matched, never on an unprovable answer

func HostLockIsHeld

func HostLockIsHeld(role string) *bool

Whether any process holds the role host lock, nil when the lock file cannot be opened

func HostLockPath

func HostLockPath(role string) string

func HostMultiplexerServing

func HostMultiplexerServing(ctx context.Context, profileName string) (string, bool, error)

Label of the host gateway launching profile when it serves the profile for this tenant, the current profile when empty

func HostOwnerSubject

func HostOwnerSubject() string

Subject a native ticket carries on this host, the owner's own OS identity

func HostProcessCreateTime

func HostProcessCreateTime(pid int) *float64

Creation time of pid, this process when zero, nil when unknowable

func HostProfileNameForHome

func HostProfileNameForHome(h string) string

Profile a home belongs to, default for the root home

func HostRecordIsStale

func HostRecordIsStale(r *HostRecord) bool

A record nobody may attach to, absent, of an unknown protocol, dead or a reused pid

func HostRecordPath

func HostRecordPath(role string) string

func HostRendezvousAtExit

func HostRendezvousAtExit()

Runs every registered role cleanup, the exit hook cmd/icebath calls on the way out

func HostServesNamedProfile

func HostServesNamedProfile(ctx context.Context, defaultHome, h string) (verdict, known bool, err error)

Offline boot verdict for named profile home, false for a standalone secondary and unknown when boot settles it

func HostStateDir

func HostStateDir() string

Per OS user rendezvous directory shared by every profile of this user

func HostedDocumentReferences

func HostedDocumentReferences(requestID string, payload *jsonutil.Object) ([]*jsonutil.Object, error)

Retained document references a hosted admission prompt names, empty for every other row

func HostedImportSourceFor

func HostedImportSourceFor(targetDB string) string

Standalone store this gateway store imports from, empty for a named profile or a missing source

func HostedMemberSession

func HostedMemberSession(ctx context.Context, db *state.SessionDB, identity []string) (int, string, error)

Generation and id of the hidden session a hosted room member dispatch lands on

func HostedRoomsDefaultDBPath

func HostedRoomsDefaultDBPath(ctx context.Context) string

Hosted room coordination database of the active install, the shared root store for a profile home

func IcebathHomeAssignments

func IcebathHomeAssignments(command string) []string

Values of every token bounded ICEBATH_HOME assignment in a lower cased command line, trailing slash stripped

func IcebathHomeForPID

func IcebathHomeForPID(ctx context.Context, pid int, requireLaunchIdentity bool) (string, bool, error)

Home a process runs under from its exec time environment and argv, requiring pinned launch identity when asked

func IcebathHomePinnedByUnit

func IcebathHomePinnedByUnit(unitPath string) (string, error)

ICEBATH_HOME the unit file pins, empty when absent or unreadable

func IcebathOwnsWindowsService

func IcebathOwnsWindowsService(name, binpath string, roots []string) bool

True for an SCM service named icebath or whose binary path starts under one of the roots

func IcebathServiceRoots

func IcebathServiceRoots(ctx context.Context) []string

Directories an Icebath owned SCM service binary lives under, the install tree, the binary dir and the launcher dir

func IdentifyGateway

func IdentifyGateway(home string, timeout time.Duration) *jsonutil.Object

identify answer of the gateway serving home

func ImplicitAPISession

func ImplicitAPISession(ctx context.Context, db *state.SessionDB, sessionID, requestID string) (string, error)

Session a derived chat id names, a deleted one replaced by its next generation

func ImpliedHostRoot

func ImpliedHostRoot(ctx context.Context, h string) (string, error)

Root whose gateway must serve named profile home when nothing records a verdict

func ImportAfterReady

func ImportAfterReady(authorities []*SessionAuthority)

Imports standalone rooms once more after the gateway published ready, off the owner loop, waking claimed rooms

func ImportStandaloneRooms

func ImportStandaloneRooms(ctx context.Context, targetDB string, runtimeEpoch *int64) (int, error)

Moves the standalone backend's live rooms into targetDB once, returning the rooms copied and never failing on a retryable error

func InboundReferences

func InboundReferences(ctx context.Context, runner ContextRefsRunner, source *SessionSource, sessionKey, text string) (string, *string)

Inbound turn text with its references expanded in the session workspace, or the typed text and the refusal

func IncrementRestartFailureCounts

func IncrementRestartFailureCounts(ctx context.Context, path string, activeSessionKeys []string)

Counter plus one of every session active at shutdown, every other counter dropped

func IngestReplicaPage

func IngestReplicaPage(ctx context.Context, dbPath string, roomIDValue, roomNameValue, members, page any, now *float64) (map[string]any, error)

Persists one verbatim read_events page idempotently, refusing sequence gaps and epoch regressions

func InitializeLedgerSchema

func InitializeLedgerSchema(ctx context.Context, conn state.SQLiteConn) error

Creates the delivery obligations table on a connection the session recovery copies into

func InlineBootstrapArgv

func InlineBootstrapArgv(tokens []string) ([]string, bool)

Tokens rewritten as the equivalent interpreter -m module argv when the -c source is an icebath bootstrap

func InlineSourceFlagIndex

func InlineSourceFlagIndex(tokens []string) (int, bool)

Index of the -c token when tokens run inline interpreter source, walking operand taking options value aware

func InstallHostedTransport

func InstallHostedTransport(server *GatewayControlServer, authority *SessionAuthority, loop context.Context, attest HostedAttester)

Installs profile selected private routing of hosted attest and producer calls over the authority registry

func InstallPluginServices

func InstallPluginServices(s *plugins.Services)

Fills the plugin services the gateway answers on the services struct the wiring installs

func InstalledGatewayServiceKind

func InstalledGatewayServiceKind(ctx context.Context) (string, bool, error)

Installed service kind of this home, stricter than the service backend since the unit, plist or task must exist

func InstalledServiceKindFor

func InstalledServiceKindFor(ctx context.Context, windows func() (bool, error)) (string, error)

Installed unit or plist kind, else windows when the thunk says so, empty when none

func IntOr

func IntOr(def int) func(string) any

Parser of a base ten int falling back to def on malformed or blank input

func InterruptSideAgents

func InterruptSideAgents(runner any, reason string) int

Hard interrupts the agent of every counted side agent across served authorities, returning how many

func InvalidateHostGatewayCache

func InvalidateHostGatewayCache()

Forgets the memoized host gateway probe, every record write calling it

func IsAPIRequestOptionMissing

func IsAPIRequestOptionMissing(value any) bool

Whether a request service tier value is the absent option sentinel

func IsAcceptedHost

func IsAcceptedHost(hostHeader, boundHost string) bool

Whether the Host header targets the bound interface or a loopback alias of a loopback bind

func IsAnimationURL

func IsAnimationURL(rawURL string) bool

Whether the URL points at an animated GIF

func IsAuthenticatedIdentity

func IsAuthenticatedIdentity(identity any) bool

Whether the identity is a server minted non internal user id and provider pair

func IsAutonomousSilenceResponse

func IsAutonomousSilenceResponse(response any) bool

Loose silence match for cron and webhook lanes, a marker line at either end or a bracketed opener

func IsChatLevelNotFound

func IsChatLevelNotFound(exc error, errorText string) bool

True when a not found failure means the whole chat is gone, a sub chat marker winning

func IsDiscordChannelObfuscated

func IsDiscordChannelObfuscated(channel any) bool

True for a channel Discord hid from the bot, by its flag first and the sentinel name second

func IsEgressDecline

func IsEgressDecline(result any) bool

True when a connector result dict is a definite refusal carrying the decline code or uniform text

func IsFenceAtom

func IsFenceAtom(text string) bool

True when an atomic block is a code block

func IsFloodError

func IsFloodError(err any) bool

True for a flood refusal in the canonical prefix form or the platform's own wording

func IsGatewayRuntimeLockActive

func IsGatewayRuntimeLockActive(lockPath string) (bool, error)

Whether some process owns the gateway runtime lock at lockPath, the process lock when empty

func IsGatewaySupervisorProcess

func IsGatewaySupervisorProcess(environ map[string]string) bool

True when a restarting supervisor owns this process, systemd, launchd, s6 or the explicit opt in

func IsGlobalStartupConflict

func IsGlobalStartupConflict(errorCode string) bool

True for a lock_conflict code or a scoped lock code ending in _lock

func IsHostExcludedByNoProxy

func IsHostExcludedByNoProxy(hostname string, noProxyValue *string) bool

Reports whether the host matches a NO_PROXY entry, the given value overriding the environment

func IsIcebathLaunchdLabel

func IsIcebathLaunchdLabel(label string) bool

Whether a launchd label belongs to an icebath job under the current prefix or a retired one

func IsIdle

func IsIdle(activeWorkCount int, secondsSinceLastInbound, idleTimeoutSeconds float64, hasLiveBackgroundWork bool) bool

No active work, no live background work and no inbound within the idle window

func IsInt

func IsInt(v any) bool

Whether v is a Python int that is not a bool

func IsIntentionalSilenceAgentResult

func IsIntentionalSilenceAgentResult(agentResult map[string]any, response any) bool

Silence markers suppress delivery only for a successful agent turn

func IsIntentionalSilenceResponse

func IsIntentionalSilenceResponse(response any) bool

True only when the response is exactly a silence marker, never for prose or a blank reply

func IsKeyError

func IsKeyError(err error) bool

Whether the error is the KeyError Python raises for a missing mapping key

func IsLinux

func IsLinux() bool

True on Linux hosts

func IsMacOS

func IsMacOS() bool

True on macOS hosts

func IsMachineryDisplayKind

func IsMachineryDisplayKind(displayKind any) bool

Only a machinery turn may vanish on a bare silence marker

func IsMessagingPlatformSource

func IsMessagingPlatformSource(source string) bool

IsMessagingPlatformSource reports whether a row source label names a messaging platform, for the state wiring

func IsNetworkAccessible

func IsNetworkAccessible(ctx context.Context, host string) bool

Reports whether binding the host would expose the server beyond loopback, failing closed on DNS errors

func IsPartialDelivery

func IsPartialDelivery(result any) bool

True when a split payload was partly delivered and its visible head must never be sent again

func IsPartialSilenceMarker

func IsPartialSilenceMarker(text any) bool

True while streamed text could still resolve to a silence marker

func IsPassText

func IsPassText(value any) bool

Whether a settled member result is Discussion silence

func IsPathUnsafe

func IsPathUnsafe(value string) bool

Whether a session id would escape its directory

func IsPidAncestorOfCurrentProcess

func IsPidAncestorOfCurrentProcess(target int) bool

True when target is this process or one of its ancestors

func IsReconnectOnly

func IsReconnectOnly(err any) bool

True for a row only an adapter reconnect may retry with no timer and no backoff

func IsResponseFrame

func IsResponseFrame(frame any) bool

A viewer's answer to an owner request, a string srq id with a result or error and no method

func IsRetryableErrorText

func IsRetryableErrorText(errText string) bool

Whether a send error text names a transient network failure worth retrying

func IsRowRejection

func IsRowRejection(err error) bool

Whether the database refused the row values themselves so no retry can write it

func IsServiceInstalled

func IsServiceInstalled(ctx context.Context) (bool, error)

Whether any gateway service definition is installed for this home

func IsServiceRunning

func IsServiceRunning(ctx context.Context) (bool, error)

Whether the gateway service is running, an active unit, a registered launchd job or a live gateway process

func IsSharedMultiUserSession

func IsSharedMultiUserSession(source *SessionSource, groupSessionsPerUser, threadSessionsPerUser bool) bool

Whether a non DM session is shared across participants under the key isolation rules

func IsSupervisedGatewayLaunch

func IsSupervisedGatewayLaunch(environ map[string]string) bool

True when a generated service or launcher started this gateway rather than a shell

func IsTableAtom

func IsTableAtom(text string) bool

True when an atomic block is a table

func IsTableRow

func IsTableRow(line string) bool

Whether the line could be a table data row

func IsTableSeparatorLine

func IsTableSeparatorLine(line string) bool

Whether the line starts with a markdown table delimiter row

func IsTurnSurface

func IsTurnSurface(name string) bool

Whether the name is a per turn client surface that carries a model bound note

func IsWildcardHost

func IsWildcardHost(host *string) bool

True for the dual stack default and the per family wildcards

func IsWindows

func IsWindows() bool

True on Windows hosts

func IssueRoomGrant

func IssueRoomGrant(ctx context.Context, secret []byte, o RoomGrantIssue) (string, error)

Signed target verifiable bearer grant scoped to one room member

func JoinAuthorityWork

func JoinAuthorityWork(ctx context.Context, a *SessionAuthority, timeout float64) error

Stops the authority's work until none is left, TimeoutError once timeout seconds pass first

func KanbanContextItem

func KanbanContextItem(kctx any, key string) (any, error)

Item of a kanban context, TypeError for a context that is no dict and KeyError for a missing key

func KickStartupWatchdog

func KickStartupWatchdog(extraS any)

Extends the armed watchdog deadline before an intentional idle wait, doing nothing when unarmed

func KillGatewayProcesses

func KillGatewayProcesses(ctx context.Context, w io.Writer, force bool, exclude map[int]bool, allProfiles bool) (int, error)

KillGatewayProcesses signals the running gateways, force kills only after a live argv recheck, and counts the kills

func LastDocumentExtForMime

func LastDocumentExtForMime(mime string) string

Extension of a document MIME as a dict inverted over the document table, the latest extension winning

func LaunchDetachedGatewayRestartByCmdline

func LaunchDetachedGatewayRestartByCmdline(ctx context.Context, oldPid int, runArgv []string, profileHome *string) (bool, error)

Relaunches a gateway with no profile pid file by replaying its captured argv on the home it ran on

func LaunchDetachedProfileGatewayRestart

func LaunchDetachedProfileGatewayRestart(ctx context.Context, profile string, oldPid int) (bool, error)

Relaunches a manually run profile gateway after its current pid exits

func LaunchShowsReasoningActive

func LaunchShowsReasoningActive(ctx context.Context) bool

Whether the active launch policy shows reasoning for a session with no pick of its own

func LaunchSupervisor

func LaunchSupervisor(identity *jsonutil.Object) string

What launched the gateway behind an identify answer, empty when it only says none or nothing usable

func LaunchctlBootstrap

func LaunchctlBootstrap(ctx context.Context, domain, plistPath, label string, timeout time.Duration) error

Bootstraps a launchd job, booting a stale registration out once before the retry

func LaunchctlLabelSupervisingProcess

func LaunchctlLabelSupervisingProcess(ctx context.Context, label string) bool

True when launchd knows the label and runs a process for it

func LaunchctlSupervisedPID

func LaunchctlSupervisedPID(ctx context.Context, label string) (int, bool)

Pid launchd runs for a label, false when unregistered, idle or the probe fails

func LaunchdGatewayLabelsForInstall

func LaunchdGatewayLabelsForInstall(ctx context.Context) ([]string, error)

Launchd labels of every profile of this install, root first then named profiles sorted

func LaunchdGatewayPlistPatterns

func LaunchdGatewayPlistPatterns() []string

LaunchAgent file patterns of every gateway label of every profile, the current base first then each retired one

func LaunchdInstall

func LaunchdInstall(ctx context.Context, w io.Writer, force, startNow, forceUnitPath bool) error

Writes and loads the launchd plist for this home

func LaunchdJobLabel

func LaunchdJobLabel(environ map[string]string) string

The icebath launchd job label from XPC_SERVICE_NAME or the wrapper re-export, empty when neither names one

func LaunchdKickstart

func LaunchdKickstart(ctx context.Context, label, domain string) error

Kickstart with kill of the label in the domain, a failed launchctl returned as the error

func LaunchdPlistIsCurrent

func LaunchdPlistIsCurrent(ctx context.Context) (bool, error)

True when the installed plist matches the generated one apart from the PATH payload

func LaunchdPrintServicePID

func LaunchdPrintServicePID(ctx context.Context, domain, label string) (bool, int, bool, error)

Loaded flag and pid of domain/label, a timeout propagates

func LaunchdProgramArguments

func LaunchdProgramArguments(command []string, stdoutLog, stderrLog string) []string

ProgramArguments running command under osascript so macOS grants the job a Local Network identity

func LaunchdRestart

func LaunchdRestart(ctx context.Context) error

Restarts the launchd gateway gracefully, escalating a wedged loop and reloading an unloaded job

func LaunchdServiceLabel

func LaunchdServiceLabel(environ map[string]string, platform string) string

The launchd job label of this process on darwin, empty on every other platform

func LaunchdServiceRegistered

func LaunchdServiceRegistered(ctx context.Context, label string, timeout time.Duration) (bool, error)

True when launchd knows the label, command failures propagate

func LaunchdStart

func LaunchdStart(ctx context.Context) error

Starts the launchd gateway, regenerating a missing plist and rebootstrapping an unloaded job

func LaunchdStatus

func LaunchdStatus(ctx context.Context, w io.Writer, deep bool) error

Prints the launchd plist freshness, load and supervision state and on deep the recent gateway log

func LaunchdStop

func LaunchdStop(ctx context.Context) error

Stops the launchd gateway by booting the job out then waiting out or killing the recorded pid

func LaunchdUninstall

func LaunchdUninstall(ctx context.Context) error

Boots out the launchd job and removes its plist unless the plist belongs to another home

func LaunchdUnsupportedMarkerExists

func LaunchdUnsupportedMarkerExists(ctx context.Context) bool

True when launchd refused this domain and the gateway runs on the detached fallback

func LaunchedByOtherTenant

func LaunchedByOtherTenant(ownerHome, ourHome string) (bool, error)

Whether the owner home belongs to another tenant root than ours

func LauncherText

func LauncherText(raw []byte) (string, error)

Text of a launcher, UTF-16 behind a byte order mark and UTF-8 with an optional signature otherwise

func LedgerEnabled

func LedgerEnabled(ctx context.Context) bool

Whether replies are recorded so a restart neither loses nor repeats them

func LegacyLaunchdLabelsForInstall

func LegacyLaunchdLabelsForInstall(ctx context.Context, exclude map[string]bool) []string

Launchd labels of this install the profile layout cannot derive, credited by the home each plist pins

func LimitedHTTPClient

func LimitedHTTPClient(limits HTTPXLimits, followRedirects bool) *http.Client

Unguarded client of an adapter talking to its own configured server, env proxies honoured and the pool bounded by limits

func ListRoomLinkRecords

func ListRoomLinkRecords(ctx context.Context, dbPath string) ([]map[string]any, error)

Private RoomLink records, grants unformatted

func ListRooms

func ListRooms(ctx context.Context, dbPath string, includeDisbanded bool, limit, offset any) ([]map[string]any, error)

One bounded read only page of rooms ordered by most recent change

func ListenerBaseURL

func ListenerBaseURL(host *string, port int) string

Base URL clients use to reach a listener bound on host and port, wildcards mapped to loopback

func LiveGatewayPidForHome

func LiveGatewayPidForHome(h string) (int, bool, error)

Verified pid of the gateway owning home from its pid file and lock, then its runtime record

func LiveGatewayPidsIn

func LiveGatewayPidsIn(ctx context.Context, allProfiles bool, profileHome string, pidFilter func([]int) ([]int, error)) ([]int, error)

Live gateway pids of one profile home's pid file, else of the process table, after an optional filter

func LiveRuntimeOwner

func LiveRuntimeOwner(h string) (int, bool, error)

Pid of a live runtime owner of home, a gateway or a reservation not marked as maintenance

func LoadChannelDirectory

func LoadChannelDirectory(ctx context.Context) *jsonutil.Object

Cached channel directory with aliases applied on read, the loader of the send command listing

func LoadGatewayConfigMap

func LoadGatewayConfigMap(ctx context.Context, configPath string) map[string]any

Effective gateway config.yaml mapping for the CLI packages, empty on any failure

func LoadYAMLLayer

func LoadYAMLLayer(ctx context.Context, h string, gwData map[string]any) error

Overlays the YAML layers onto gwData in place, bridging shared keys and plugin hooks for configured platforms

func LocalAdapterMap

Adapters by platform the authority's local sessions restore through

func LocalAuthorityGatewayID

func LocalAuthorityGatewayID(ctx context.Context) (string, error)

Stable server owned identity for hosted room authority, derived from the install identity

func LocalAuthorityLive

func LocalAuthorityLive(runner any, source *SessionSource) (*SessionAuthority, *LiveSession)

Authority and live session of the local session a source belongs to, nils for a messaging chat

func LocalCatalogMapping

func LocalCatalogMapping(ctx context.Context, o CatalogOptions) (*jsonutil.Object, error)

The one truthful catalog advertised by this local process, always a persistent process

func LocalSessionInfo

func LocalSessionInfo(ctx context.Context, a *SessionAuthority, ref SessionRef) (*jsonutil.Object, error)

Session info frame of a local session as its viewers render it

func LocalVoiceEnabled

func LocalVoiceEnabled(sessionID any) (*bool, error)

Voice state of a local session the mounted owner holds, nil when no owner here holds it

func LocalVoiceMode

func LocalVoiceMode(sessionID string) (mode string, held bool, err error)

LocalVoiceMode is the stored voice mode of a local session the running owner holds, held false when none here holds it

func LocalVoiceTransition

func LocalVoiceTransition(source *SessionSource, mode string)

Ends the push to talk capture of a local session turning voice off, when the TUI server runs here

func LocalVoiceViewers

func LocalVoiceViewers(sessionID string) []tuihost.Transport

LocalVoiceViewers are the event transports of the windows viewing a local session, sorted by subscription id

func LocateLaunchdGatewayService

func LocateLaunchdGatewayService(ctx context.Context, label string) (string, int, bool, error)

Domain and pid of a label probing the gui then the user domain, empty domain when unloaded

func LockAnswer

func LockAnswer(requestID, questionID string, answer any, sessionOK func(sessionID string, events *SessionEvents) bool) ([]string, error)

Locks one answer of an open batch, the question ids still unanswered, nil when no batch the caller may answer is open

func LockRecordUnpublished

func LockRecordUnpublished(h string) bool

Whether home's lock record names no live holder other than the caller yet

func LogDecline

func LogDecline(op string, chatID, result any)

Warns about a decline on a lane whose contract cannot carry an error

func LogMultiplexDecision

func LogMultiplexDecision(ctx context.Context, decision MultiplexDecision)

Records the verdict, logs it and prints the boxed notice or warning it calls for

func LogStartupSecurityWarnings

func LogStartupSecurityWarnings(ctx context.Context, dataHome string, force bool) []string

Runs the audit once per process unless forced and logs each finding as a warning

func LooksLikeGatewayCommandLine

func LooksLikeGatewayCommandLine(command string) bool

Whether a command line is a real gateway run process

func LooksLikeGatewayProcess

func LooksLikeGatewayProcess(pid int) bool

Whether the live command line of pid is a gateway run

func LooksLikeGatewayRuntimeCommandLine

func LooksLikeGatewayRuntimeCommandLine(command string) bool

Whether a command line can host the gateway runtime, run or the in process restart fallback

func LooksLikeInt

func LooksLikeInt(value string) bool

True when the value is a whole number in base ten, a sign and underscores between digits allowed

func LooksLikePairingRequestID

func LooksLikePairingRequestID(value string) bool

Whether a value is shaped like a pending request id, sixteen hex characters

func LooksLikeTelegramPrivateChatID

func LooksLikeTelegramPrivateChatID(chatID string) bool

True when the chat id is a positive integer, the Telegram private chat shape

func LookupChannelType

func LookupChannelType(ctx context.Context, platformName, chatID string) (any, error)

Channel type of a chat id in the directory, nil when unknown

func LookupScopedSecret

func LookupScopedSecret(ctx context.Context, name string, externalFallback bool) (string, bool, error)

Scope aware credential read reporting whether the name is set at all, the None of get_scoped_secret as false; a name folded into a setting reads the setting

func LoopHeartbeatForever

func LoopHeartbeatForever(ctx context.Context, loop EventLoop, opts LoopHeartbeatOptions) error

Rewrites the heartbeat off loop on a loop paced cadence and serves the loop tick witness until ctx ends or gated off

func MCPEventDeliveryID

func MCPEventDeliveryID(routeConfig *jsonutil.Object, payload any) (string, bool)

Delivery id of an MCP event occurrence keyed by its event id, false when the payload names none

func MCPStatusRows

func MCPStatusRows(statuses []mcp.ServerStatus) []any

Session info rows of MCP server states, the tool count a whole number

func MaintenanceHolder

func MaintenanceHolder(h, purpose string) *jsonutil.Object

Live holder record of home's gateway.lock when it is a maintenance reservation for purpose

func ManagedTurnCount

func ManagedTurnCount(runner any) int

Unmapped claims, managed workers and owner mutations across the served authorities

func MarkAttempting

func MarkAttempting(ctx context.Context, obligationID string) error

Moves the obligation to attempting right before the send await

func MarkDelivered

func MarkDelivered(ctx context.Context, obligationID string) error

Moves the obligation to delivered after a successful send

func MarkExited

func MarkExited(ctx context.Context, exitCode *int, reason string, h string)

Marks this life cleanly exited unless another process owns the sentinel, keeping its incarnation identity

func MarkFailed

func MarkFailed(ctx context.Context, obligationID, errText string) error

Moves the obligation to failed with the rejection text

func MarkInternalNotification

func MarkInternalNotification(text string) string

Text with the internal notification footer appended once

func MarkManagedWorkerEntryDispatched

func MarkManagedWorkerEntryDispatched()

Records that this binary routes the managed worker entry to its child main

func MarkNotifyMetadata

func MarkNotifyMetadata(metadata map[string]any) map[string]any

Copy of send metadata marked as a notification

func MarkRoomLinkStatus

func MarkRoomLinkStatus(ctx context.Context, dbPath, roomID, memberID, status string) (bool, error)

Persists a route health classification of one link

func MarkStreamingTTSCompletedTurn

func MarkStreamingTTSCompletedTurn(adapter PlatformAdapter, sessionKey string, turnMarker any)

Records that the turn streamed its audio so the whole file reply is suppressed

func MediaDeliveryStrict

func MediaDeliveryStrict(ctx context.Context) bool

Whether strict media delivery is on for the profile in ctx

func MediaDeliveryTrustRecent

func MediaDeliveryTrustRecent(ctx context.Context) bool

Whether freshly produced files are trusted for delivery

func MemberRoster

func MemberRoster(ctx context.Context, authority *SessionAuthority, siblings bool) (*orderedutil.Map[string, string], map[string]HostedMemberRefusal, error)

Seatable profile homes by name for a group on the authority, and the names a new member may not take

func MentionPatterns

func MentionPatterns(value string) any

JSON value of the text, else its comma or newline separated items

func MergeCaption

func MergeCaption(existingText, newText string) string

Caption merge of a batched media event, a repeated caption kept once

func MergePendingMessageEvent

func MergePendingMessageEvent(pending map[string]*MessageEvent, sessionKey string, event *MessageEvent, mergeText bool)

Stores the pending event or merges it into the queued one, photo bursts and media always absorb and text appends when asked

func MergePlatformSections

func MergePlatformSections(yamlCfg map[string]any, gwData map[string]any) (map[string]any, error)

Every platforms.<name> block of config.yaml merged into gwData platforms

func MessagingIsRelayOnlyOrAbsent

func MessagingIsRelayOnlyOrAbsent(platforms []string) bool

True when the only platform named is relay or none is named at all

func MessagingPlatformLabels

func MessagingPlatformLabels() []string

MessagingPlatformLabels is every shipped platform value plus bundled plugin platform names and aliases

func MigrateGatewayProfileIdentity

func MigrateGatewayProfileIdentity(home, oldName, newName string, timeout time.Duration) *jsonutil.Object

Asks the multiplexer serving home to rekey a renamed profile routing from old to new

func MigrateRetiredGatewayServices

func MigrateRetiredGatewayServices(ctx context.Context, w io.Writer) (bool, error)

Moves retired services of the home in effect to the current name, starting the new one when the old one ran

func MimeForExt

func MimeForExt(ext string, overrides map[string]string, fallback string) string

Mime of a dotted extension from the overrides then the shared inverse table, else the fallback

func MirrorToSession

func MirrorToSession(ctx context.Context, platform, chatID, messageText string, opts MirrorOptions) bool

Appends a delivery mirror message to the target session transcript, false when no session matches or the write fails

func MissingOwnerState

func MissingOwnerState(home string) string

Reservation state of a home with no control socket, starting while its runtime lock is held

func MoveRouteWakes

func MoveRouteWakes(ctx context.Context, runner AuthorityRunner, sessionKey, oldSessionID string) error

Route wake move after a rotation, for the runner's reset paths

func MultiplexProfileHomes

func MultiplexProfileHomes(ctx context.Context, cfg *GatewayConfig) ([]profiles.ServedProfile, error)

Profiles this multiplexer serves, the boot reservation once taken, else the live profiles directory

func MultiplexerLivenessForProfile

func MultiplexerLivenessForProfile(profileDir string) (int, *jsonutil.Object, bool, error)

Pid and host gateway_state.json when the live host multiplexer serves the profile at profileDir

func MultiplexerRootFor

func MultiplexerRootFor(h string) string

Default root that may multiplex home when home is a named profile under it, empty otherwise

func MultiplexerServedSecondaries

func MultiplexerServedSecondaries() ([]string, error)

Named profiles the live default multiplexer serves, default excluded

func MultiplexerServesHome

func MultiplexerServesHome(ctx context.Context, h string) (string, error)

Root whose possibly stopped multiplexer serves home by boot policy or its recorded served set

func NamedProfileRefusedUnderMultiplexer

func NamedProfileRefusedUnderMultiplexer(ctx context.Context, w io.Writer, force bool) (bool, error)

Prints the refusal and reports true when a named profile served by the multiplexer must not run its own gateway

func NamedProfileServedByRunningMultiplexerCtx

func NamedProfileServedByRunningMultiplexerCtx(ctx context.Context, profileName *string) (bool, error)

Whether the running default multiplexer serves the named profile, the probe error kept

func NamedProfileServedByRunningMultiplexerFor

func NamedProfileServedByRunningMultiplexerFor(ctx context.Context, profileName *string) (bool, error)

Whether a live default multiplexer serves the named profile, the current profile when the name is nil

func NativeCallback

func NativeCallback(ctx context.Context, runner AuthorityRunner, event *MessageEvent, transportHome, profile *string) (context.Context, error)

Context carrying the native callback of one event, refused without a home on an authority runner

func NeutralizeUntrustedInlineText

func NeutralizeUntrustedInlineText(value any, maxChars int) string

Untrusted text collapsed to one inert unquoted line within the character budget

func NormalizeChoice

func NormalizeChoice(value any, choices map[string]bool, def string) string

Lowered stripped value when it is one of the choices, else the default

func NormalizeUpdatedAt

func NormalizeUpdatedAt(value any) (string, bool, error)

Persisted updated_at coerced to an RFC3339 string, false for garbage, an error for an int too large for float

func NormalizeWhatsAppIdentifier

func NormalizeWhatsAppIdentifier(value any) string

Bare numeric identifier with JID, LID, device and plus syntax stripped

func NormalizeWhatsAppMentionJID

func NormalizeWhatsAppMentionJID(value string) string

Participant JID valid for an outbound mention, empty otherwise

func NormalizedHomeForCompare

func NormalizedHomeForCompare(h string) string

Install identity key of a home so symlinked or differently spelled roots compare equal

func NotifyMultiplexerProfilesChanged

func NotifyMultiplexerProfilesChanged(ctx context.Context, profileName string, timeout time.Duration) ([]string, bool)

Asks the live default multiplexer to rescan profiles, the served list it answered or false when none answered

func ObserveAPIControls

func ObserveAPIControls(ctx context.Context, admitted *APIAdmission, sink func(eventType string, prompt *jsonutil.Object) error) (func(), error)

Projects the admission's approval and clarify prompts to sink until the returned call, replaying pending ones first

func ObserveAPITurn

func ObserveAPITurn(ctx context.Context, admitted *APIAdmission, callbacks map[string]APIObserverCallback) (map[string]any, map[string]any, error)

Settled result and usage of the admission, observing it through its waiter until the drain settles it

func OpenRestartWait

func OpenRestartWait(runner DrainRunner)

Publishes the restart after turn wait as the drain reason unless a drain already named its own

func OpenServerRequests

func OpenServerRequests(events *SessionEvents, sessionID string) []*jsonutil.Object

Requests still waiting on this live session's stream, oldest first, as their frames carried them

func OutsideRestartWait

func OutsideRestartWait(ctx context.Context) context.Context

Context whose gateway connections never attach to an owner in its restart after turn wait

func OwnerHoldsDelivery

func OwnerHoldsDelivery(ctx context.Context, profileHome string, record map[string]any) (bool, error)

Whether the profile authority still holds a record, failing while the authority is unreachable

func OwnerScope

func OwnerScope(ctx context.Context, a *SessionAuthority, hydrateSecrets bool) context.Context

Context scoped to the authority's owning profile, its secrets hydrated when asked

func OwnersAgree

func OwnersAgree(first, second any) bool

True when two stored owner stamps name the same owner either way round

func OwnsAPIRun

func OwnsAPIRun(ctx context.Context, adapter APIRunAdmitter, runID, ownerScope string) (bool, error)

Whether a caller scope owns one canonical API admission, failing closed on every unanswered question

func OwnsGatewayRuntimeLock

func OwnsGatewayRuntimeLock() bool

Whether this process holds the runtime reservation of its launch home

func OwnsHostLock

func OwnsHostLock(role string) bool

Whether this process holds the role host lock, re probing our own flock lying

func PairingCommand

func PairingCommand(ctx context.Context, ns map[string]any, w io.Writer) (int, error)

Runs the pairing subcommands list, approve, revoke and clear-pending over the store of the bound home

func ParseActiveAgents

func ParseActiveAgents(raw any) (any, error)

Non negative active_agents of a persisted value, zero when int raises TypeError or ValueError

func ParseAuthenticatedSubject

func ParseAuthenticatedSubject(subject any) (parts [3]string, ok bool)

Provider, issuer and user of an auth v1 login subject, ok false for any other form

func ParseCronDrainTimeout

func ParseCronDrainTimeout(raw any) float64

Cron and api_server drain floor, 0 opts out

func ParseLaunchdExitTimeout

func ParseLaunchdExitTimeout(printOutput any) *float64

Seconds of the exit timeout line in launchctl print output, nil when absent

func ParseLaunchdPIDFromListOutput

func ParseLaunchdPIDFromListOutput(output string) (int, bool)

Pid of a launchctl list record, false when absent or not positive

func ParseLaunchdPIDFromPrintOutput

func ParseLaunchdPIDFromPrintOutput(output string) (int, bool)

Live pid of a launchctl print record, the first pid line wins

func ParseNonempty

func ParseNonempty(ref string) any

Stripped reference as an explicit chat id whenever it is non empty

func ParseRestartAfterTurnTimeout

func ParseRestartAfterTurnTimeout(raw any) float64

After turn wait cap of an in band restart, 0 keeps the immediate drain

func ParseRestartDrainTimeout

func ParseRestartDrainTimeout(raw any) float64

Configured restart drain timeout, a falsy value including 0 takes the shipped default

func ParseSessionKey

func ParseSessionKey(sessionKey string) map[string]any

Platform, chat type, chat id and any named profile and thread of a session key, nil for other text

func ParseSignalInterruptGraceTimeout

func ParseSignalInterruptGraceTimeout(raw any) float64

Post interrupt grace of an unexpected signal, non finite input takes the default

func ParseSystemdDurationToUS

func ParseSystemdDurationToUS(raw string) *big.Int

Microseconds of a systemd duration such as 1min 30s, nil on anything unexpected

func ParseTargetRef

func ParseTargetRef(ctx context.Context, platformName, targetRef string) (chatID, threadID *string, explicit bool)

Chat id, thread id and explicitness of a target ref under the platform rules

func PauseGatewayForUpdate

func PauseGatewayForUpdate(home string, timeout time.Duration) *jsonutil.Object

Drain and exit acknowledgement of the gateway serving home for an update

func PeerCommand

func PeerCommand(ctx context.Context, h string, ns map[string]any, w io.Writer) (int, error)

Runs icebath peer from the parsed namespace, stdout to w and diagnostics to stderr

func PeerFileScope

func PeerFileScope(claims *jsonutil.Object) (string, error)

Scope of a verified room grant, one member seat of one room home, surviving grant refreshes

func PeerMemberTurnInput

func PeerMemberTurnInput(ctx context.Context, dbPath, scope string, dispatch *HostedMemberDispatch) (any, error)

Turn input of a dispatch, documents named by retained path and images as image parts like a home member

func PeerRoomGrantIsCurrent

func PeerRoomGrantIsCurrent(ctx context.Context, dbPath string, claims *jsonutil.Object, now *float64) (bool, error)

Whether a grant matches the target's current live reservation

func PeerWaitAdmission

func PeerWaitAdmission(ctx context.Context, a *SessionAuthority, record map[string]any) (string, bool, error)

Admission a live waiter must follow and whether it is interim, empty once the delivery settled for good

func PersistDelegationDelivery

func PersistDelegationDelivery(ctx context.Context, adapter PlatformAdapter, text, sessionID string, evt map[string]any) error

Persists an async delegation completion as a durable delivery row without running a turn

func PersistHomeChannel

func PersistHomeChannel(ctx context.Context, h *HomeChannel, enabledIfNew bool) error

Writes the home channel into the platform's block of the profile ctx serves, enabling the platform only when asked and not yet set

func PersistResolvedDefault

func PersistResolvedDefault(ctx context.Context, decision MultiplexDecision, defaultHome string) bool

Writes gateway.multiplex_profiles true into the default profile's config once, never on a guard refusal

func PersistedUserMetadataForEvent

func PersistedUserMetadataForEvent(ctx context.Context, event DisplayEvent) map[string]any

Display metadata plus the canonical admission submission id

func PidExists

func PidExists(pid int) bool

Whether pid names a live process through the handle based check on Windows

func PidFromRecord

func PidFromRecord(record *jsonutil.Object) (int, bool)

Pid the record names under its pid key

func PidIsOtherUsers

func PidIsOtherUsers(ctx context.Context, pid int) bool

True when another Unix user than this non root caller owns the pid

func PidPath

func PidPath() string

Path of this home's gateway pid file

func PidRecordBelongsToCurrentProfile

func PidRecordBelongsToCurrentProfile(record *jsonutil.Object) (bool, error)

Whether a pid record names this process home's profile

func PidUID

func PidUID(ctx context.Context, pid int) (int, bool)

Owner uid of a live process from proc, ps on macOS, false when unknown

func PlannedRestartMarkerPath

func PlannedRestartMarkerPath(h string) string

Planned restart marker under the given home, the process home when empty

func PlannedStopMarkerPath

func PlannedStopMarkerPath() string

Path of the planned stop marker of this home

func PlannedStopMarkerTargetsSelf

func PlannedStopMarkerTargetsSelf() (bool, error)

Whether a live planned stop marker names this process, never unlinking a matching marker

func PlatformBindsPort

func PlatformBindsPort(platformValue string, extra map[string]any) bool

True when the platform actually binds a port for its extra config

func PlatformGateEnv

func PlatformGateEnv(ctx context.Context, name, def string) string

Allow or deny gate value of the profile ctx serves: the setting a folded name moved to, else the env isolated per profile

func PlatformHTTPClient

func PlatformHTTPClient(ctx context.Context, opts PlatformHTTPClientOptions) *http.Client

SSRF guarded client for a platform adapter with redirect hop checks and the shared keepalive limits

func PlatformRegistryService

func PlatformRegistryService() plugins.PlatformRegistry

Platform registry service the wiring installs into plugins.Services.Platforms

func PlatformSection

func PlatformSection(yamlCfg map[string]any, name string) (any, bool)

Platform block of a config the loader picks, a top level block first

func PlatformStatus

func PlatformStatus(ctx context.Context, p SetupPlatform) (string, error)

Plain status text of a platform row, uncolored for menu width math

func PolicyScope

func PolicyScope(ctx context.Context, policy *LocalSessionPolicy, a *SessionAuthority, body func(ctx context.Context) error) error

Runs body under the session's frozen launch policy, the policy scope of a turn

func PolicyTurnToolsets

func PolicyTurnToolsets(ctx context.Context, policy *LocalSessionPolicy, cfg map[string]any) ([]string, error)

Toolsets of a local turn, a copy of the policy's current set

func PostPluginMessage

func PostPluginMessage(ctx context.Context, target any, text, pluginID string) map[string]any

First message of a handle, an adapter failure returned as a send_failed result

func PrefixWithinUTF16Limit

func PrefixWithinUTF16Limit(s string, limit int) string

Longest prefix of s within limit UTF-16 code units, never splitting a surrogate pair

func PrepareAPIExecution

func PrepareAPIExecution(ctx context.Context, a *SessionAuthority, ref SessionRef, payload *jsonutil.Object) (*jsonutil.Object, error)

Execution state of one admitted API turn, its adapter, settings, history and content

func PrepareBeforeSubmit

func PrepareBeforeSubmit[T any](prepare func() (T, error)) (T, error)

Runs a member turn's file preparation, a failure marked refused before submit or proven not admitted

func PrepareModel

func PrepareModel(ctx context.Context, a *SessionAuthority, live *LiveSession, payload, prepared *jsonutil.Object) (*jsonutil.Object, error)

Model pick of a prepared snapshot frozen into its policy, the committed policy and refusal as the mutation returns them

func PrepareProfileGatewayUpdateRestart

func PrepareProfileGatewayUpdateRestart(ctx context.Context, profile string, pid int) (string, bool, error)

Who relaunches a profile gateway after an update, its external supervisor, the profile watcher or the argv replay

func PrepareRetryAction

func PrepareRetryAction(roomID string, room map[string]any) map[string]any

Retry row of a stalled room, its member id naming who was not woken

func PrepareSendMessagePlatforms

func PrepareSendMessagePlatforms(ctx context.Context)

Loads the enabled standalone platform plugins before tool schemas and cache keys are built

func PrincipalSubject

func PrincipalSubject(identity map[string]any) (string, error)

Subject a connection acts as, every login collapsing onto the host owner and native grants keeping theirs

func PrintIndented

func PrintIndented(text string, emit func(string))

Prints each line of text indented by two spaces through emit

func ProbeGatewayLoopLiveness

func ProbeGatewayLoopLiveness(ctx context.Context, pid int, o LoopLivenessOptions) string

Classifies the event loop of a gateway pid as alive, wedged or unknown from its heartbeat and tick witness

func ProbeHostedRoom

func ProbeHostedRoom(ctx context.Context, dbPath string, roomID any) (bool, error)

Room ownership check that never creates or migrates the shared store and fails fast under contention

func ProbeLaunchdServiceRunning

func ProbeLaunchdServiceRunning(ctx context.Context) (bool, error)

True when the plist exists and launchd runs a process for this profile's label

func ProbePeerRoomReservation

func ProbePeerRoomReservation(ctx context.Context, dbPath string, roomID, targetProfile any, now *float64) (bool, error)

Peer reservation check that never creates or migrates shared state

func ProbeSystemdServiceRunning

func ProbeSystemdServiceRunning(ctx context.Context, system bool) (bool, bool, error)

Selected scope and whether its unit is active

func ProcessHome

func ProcessHome() string

Home this process resolves as its own

func ProducerIdentity

func ProducerIdentity(ctx context.Context, runner any, event map[string]any) (string, error)

Compact JSON delivery identity of a producer event, for the runner's notification code

func ProfileFlagValue

func ProfileFlagValue(command string) (string, bool)

Lower cased -p or --profile argument of a case preserving command line, false when absent

func ProfileLabelForHome

func ProfileLabelForHome(h string) string

Profile label of a home for callers outside this package, empty when unknown

func ProfileNameForHome

func ProfileNameForHome(profileHome string) (string, bool)

Profile id of any home, the profiles child name, default for the default root, false otherwise

func ProfilePlatformsFromMultiplexer

func ProfilePlatformsFromMultiplexer(runtime *jsonutil.Object, profile string) *jsonutil.Object

A multiplexer record's entries for profile re-keyed to bare platform names plus its listener mirrors

func ProfileRouteIdentity

func ProfileRouteIdentity(ctx context.Context, config map[string]any) (string, error)

Identity the profile's own model block resolves to, custom for an endpoint naming no provider

func ProfileRuntimeScope

func ProfileRuntimeScope(ctx context.Context, profileHome string, hydrateSecrets bool) context.Context

Profile scoped context for the relay and CLI packages, the launch profile's runtime scope under multiplex

func ProfileScoped

func ProfileScoped(ctx context.Context) bool

True inside a multiplexed secondary profile's scope, for the platform adapters

func ProfileSuffix

func ProfileSuffix(ctx context.Context) (string, error)

Service suffix of the home in effect, empty for the bare name owner, the profile name or an eight digit path hash

func PromoteReplica

func PromoteReplica(ctx context.Context, dbPath string, roomIDValue, reason any, now *float64) (map[string]any, error)

Continues a replicated room on this gateway at the next epoch behind a lineage proving claim

func ProxySafeErrorText

func ProxySafeErrorText(err error, proxyURL string) string

Text of a failed request for a log line or a send result: the redacted form when the request went through a proxy whose URL holds a secret the raw text could repeat, the raw text otherwise

func PruneDisbandedRooms

func PruneDisbandedRooms(ctx context.Context, dbPath string, now *float64) (int, error)

Purges deleted Group Chat payloads while reserving their identities

func PrunePhysicalWorkers

func PrunePhysicalWorkers(a *SessionAuthority)

Prunes every tracked turn worker whose thread exited

func PublishAPIObserverCallback

func PublishAPIObserverCallback(ctx context.Context, a *SessionAuthority, sessionID string, generation int64, key string, args []any, kwargs map[string]any) (bool, error)

Runs the admission observers' callback for key fenced to the running claim, false when it moved or none accepted

func PublishAPIToolEvent

func PublishAPIToolEvent(ctx context.Context, a *SessionAuthority, sessionID string, generation int64, eventType, callID, toolName string, args, result any) error

Real tool arguments and results for the admission's API observers, never part of the viewer stream

func PublishAPIToolProgress

func PublishAPIToolProgress(ctx context.Context, a *SessionAuthority, sessionID string, generation int64, args []any, kwargs map[string]any) error

Producer emitted tool progress event for the admission's progress only observers, fenced to the running claim

func PublishCompletion

func PublishCompletion(ctx context.Context, a *SessionAuthority, live *LiveSession, ref SessionRef, row, settled *jsonutil.Object, response any, captured *jsonutil.Object) error

Publishes a settled turn's completion frame under the stream lock the caller holds

func PublishControl

func PublishControl(ctx context.Context, a *SessionAuthority, sessionID string, onlyIfPresent, onlyIfChanged bool) error

Pushes one live session's control snapshot to every viewer as session.control.update

func PublishControlAsync

func PublishControlAsync(ctx context.Context, a *SessionAuthority, sessionID string, onlyIfPresent, onlyIfChanged bool) error

Publish with the snapshot read under the owner scope, dropped when a later ticket painted or the session was remounted

func PublishPendingMultiplexDecision

func PublishPendingMultiplexDecision(ctx context.Context)

Writes the decision held back before the runtime lock claim

func PublishRuntimeStatus

func PublishRuntimeStatus(ctx context.Context, u RuntimeStatusUpdate) (int, error)

Merges and queues a status update without waiting for persistence

func PublishSharedIngress

func PublishSharedIngress(ctx context.Context, adapter PlatformAdapter, app *HTTPApp, ingressPath string)

Freezes the app, exposes it to the default listener and records the profile prefixed callback URL

func PurgeGatewayProfileIdentity

func PurgeGatewayProfileIdentity(home, name string, timeout time.Duration) *jsonutil.Object

Asks the multiplexer serving home to drop a deleted profile routing identity in memory and on disk

func PurposeCapabilities

func PurposeCapabilities(purpose string) map[string]bool

Capabilities a bootstrap purpose grants, nil for an unknown purpose

func PutBehind

func PutBehind(events *EventQueue, item any)

Queues a local item behind every frame read so far, never dropped

func QueryGatewayControl

func QueryGatewayControl(home, verb string, params *jsonutil.Object, timeout time.Duration) *jsonutil.Object

result payload of a control verb answered ok true by the gateway serving home, nil on any failure

func QueryIdentify

func QueryIdentify(home string, timeout time.Duration) (*jsonutil.Object, error)

identify result of home's control socket, keeping timeout, access and protocol failures as errors

func QueueReplicaOp

func QueueReplicaOp(ctx context.Context, dbPath, roomID, op string, params map[string]any) (int64, error)

Queues one operation of a local user for the room's home, which applies it on its next sync

func ReactionShortcode

func ReactionShortcode(emoji string) (string, bool)

Reaction name of an emoji for platforms that react by name, a bare or colon wrapped name kept as given

func ReadAuthorityHistoryLocked

func ReadAuthorityHistoryLocked(ctx context.Context, conn state.SQLiteConn, roomID, gatewayID string, epoch int64) ([]any, error)

Committed authority transfers read inside the caller's room state transaction, nil for none to certify

func ReadDefinition

func ReadDefinition(path string) ([]byte, error)

Bytes of a regular service definition up to one MiB, never blocking on a FIFO

func ReadDeliveryResult

func ReadDeliveryResult(ctx context.Context, profileHome, deliveryID string) (map[string]any, error)

Admission, claim or terminal state of a delivery without waiting or deleting its receipt

func ReadDownload

func ReadDownload(ctx context.Context, service *HostedRoomService, roomID string, params map[string]any) (map[string]any, error)

One committed file with its bytes as base64 for a live room viewer on either route

func ReadEvents

func ReadEvents(ctx context.Context, dbPath string, roomIDValue, sinceSeqValue, limitValue any, includeDisbanded bool) (map[string]any, error)

Monotonic room log delta after sinceSeq within the page byte budget

func ReadFrame

func ReadFrame(stream *bufio.Reader) (*jsonutil.Object, error)

One framed line of the pipe, EOFError at end, ValueError for an oversized, unterminated or non dict frame

func ReadGatewayLockRecord

func ReadGatewayLockRecord(p string) *jsonutil.Object

Parsed gateway.lock record at a path for callers outside this package, nil when absent or unreadable

func ReadHTTPBodyWithLimit

func ReadHTTPBodyWithLimit(ctx context.Context, resp *http.Response, mediaType string) ([]byte, error)

Response body read under the inbound media cap, an oversized declared length rejected before any chunk

func ReadLaunchdExitTimeoutS

func ReadLaunchdExitTimeoutS(q LaunchdExitTimeoutQuery) *float64

Live launchd ExitTimeOut seconds of this gateway job, nil when no launchd budget applies

func ReadPeerRunFile

func ReadPeerRunFile(ctx context.Context, dbPath, scope, fileID string, offset int64) (map[string]any, error)

One chunk of a reply file staged for this room member seat, the home checking the whole digest

func ReadPidRecord

func ReadPidRecord(p string) *jsonutil.Object

Parsed pid record at p, nil when missing or unreadable

func ReadPriorExitLabel

func ReadPriorExitLabel(profileHome string) string

clean, unclean or unknown for the last gateway life of a profile home

func ReadProcessCmdline

func ReadProcessCmdline(pid int) (string, bool)

Live command line of pid, false when it cannot be read

func ReadRuntimeStatus

func ReadRuntimeStatus(path string) *jsonutil.Object

Reads gateway_state.json of this process home, or of another home when path is set

func ReadSystemdUnitProperties

func ReadSystemdUnitProperties(ctx context.Context, system bool, properties ...string) (map[string]string, error)

Unit state properties, the default ActiveState SubState Result ExecMainStatus MainPID set when none are named

func ReadSystemdUserFromUnit

func ReadSystemdUserFromUnit(unitPath string) (string, error)

Account named by the unit's User line, empty when the unit is absent or names none

func ReadYAMLLayers

func ReadYAMLLayers(ctx context.Context, h string) (map[string]any, error)

User config.yaml with env references expanded and the managed overlay applied, an absent file an empty layer

func ReadinessFailure

func ReadinessFailure(err error) *jsonutil.Object

Runtime check answer for a resolve that raised, the error code riding along only for an unrepairable failure

func ReapCgroup

func ReapCgroup(cgroupPath string) (int, bool, error)

SIGKILLs every pid of the cgroup but the caller from a fresh read, refused false while a live gateway remains

func ReapGatewayChildren

func ReapGatewayChildren(children []gatewayChild, parentPid int, timeout time.Duration) int

Terminates the orphaned descendants of a dead gateway, killing survivors after the timeout, returning the count

func ReapUnsupervisedGatewayOrphans

func ReapUnsupervisedGatewayOrphans(ctx context.Context, extraExclude map[int]bool, minAgeS float64) (bool, error)

Reaps unsupervised orphan gateways of this home before a restart

func ReconcileAutostartLaunchers

func ReconcileAutostartLaunchers(ctx context.Context) ([]string, []string, error)

Converges logon persistence to one mechanism, returning done and warning messages

func ReconcileScheduledTask

func ReconcileScheduledTask(ctx context.Context, taskName string) (bool, error)

Re-registers a drifted task from the current template, true only when schtasks accepted it

func RecordBootFingerprint

func RecordBootFingerprint()

Snapshots the checkout revision at gateway startup once

func RecordCrashLeftReply

func RecordCrashLeftReply(ctx context.Context, o DeliveryObligation, since float64) error

Adopts an unowned attempting reply a killed process persisted, unless the same reply was ledgered since the turn start

func RecordInterruptedExecution

func RecordInterruptedExecution(ctx context.Context)

RecordInterruptedExecution settles the executing admission of the context as an interrupted empty turn

func RecordLooksLikeGateway

func RecordLooksLikeGateway(record *jsonutil.Object) bool

Whether a pid record carries the gateway argv shape

func RecordMultiplexDecision

func RecordMultiplexDecision(ctx context.Context, decision MultiplexDecision)

Publishes a guard refusal into the runtime status once this process owns the lock, holding it back before

func RecordNamesLiveOwner

func RecordNamesLiveOwner(r *HostRecord) bool

Whether the record incarnation is proven and its host lock is not observed free

func RecordObligation

func RecordObligation(ctx context.Context, o DeliveryObligation) error

Records a final response as owed to the platform in state pending and prunes in the same transaction

func RecordRestartInterruptedBoot

func RecordRestartInterruptedBoot(ctx context.Context, windowSeconds int, now *float64, maxGapSeconds int) ([]float64, error)

Records a restart interrupted boot and returns the linked chain ending with it

func RecordServiceChoice

func RecordServiceChoice(ctx context.Context, choice string) error

Saves the durable service install choice of the profile ctx names, gateway.service_install_choice

func RecordStartFailure

func RecordStartFailure(ctx context.Context, frame *jsonutil.Object, cause error) error

Books the one shot credential exit of a worker that died before any turn ran, nothing without a card or kanban

func RecordStartup

func RecordStartup(ctx context.Context, h string, deferIntegrityCheck bool) *jsonutil.Object

Reports an unclean previous exit then claims the sentinel for this life, returning the evidence

func RecordTerminalFailure

func RecordTerminalFailure(ctx context.Context, result *jsonutil.Object) *jsonutil.Object

Records an owner side terminal failure on the executing admission and returns it

func RecordUnexecutedFailure

func RecordUnexecutedFailure(ctx context.Context, reply, reason string, failure any) string

RecordUnexecutedFailure commits a failed result for the executing admission of a turn that never ran, returning the reply

func RecordWorkerResult

func RecordWorkerResult(ctx context.Context, kctx any, code int, lastOutput string) error

Ends the submitter watch and appends the attempt's worker_result event while this process is still the bound worker

func RecordedGatewayHomeConflicts

func RecordedGatewayHomeConflicts(record *jsonutil.Object, expectedHome string) bool

Whether a persisted record names a different home than expected, failing closed when the comparison errors

func RecordedServedProfiles

func RecordedServedProfiles(defaultRoot string) ([]string, bool, error)

served_profiles the live default gateway recorded, recorded false when the key is absent or no gateway runs

func RecordedStandaloneReason

func RecordedStandaloneReason(statePath string) string

Guard refusal a live standalone gateway published in its runtime status, empty for history or none

func RecordedStandaloneWarningLines

func RecordedStandaloneWarningLines(ctx context.Context) []string

Standalone warning box rebuilt from the live gateway runtime status of this home

func RecoverAPITurns

func RecoverAPITurns(ctx context.Context, adapter PlatformAdapter) error

Recovers committed API work once the real API adapter is published, each served profile under its own scope

func RecoverAuthorityAPITurns

func RecoverAuthorityAPITurns(ctx context.Context, a *SessionAuthority) error

Queued API turns of the authority's store, recovered on the published API adapter

func RecoverBotMailbox

func RecoverBotMailbox(ctx context.Context, a *SessionAuthority) error

Owner startup Bot Chat recovery, skipped with a warning when this token cannot use the mailbox directory

func RecoverDetachedSessions

func RecoverDetachedSessions(ctx context.Context, a *SessionAuthority, pending map[string]bool) ([]string, error)

Boot schedule of detached conversations' queued input, for the runner's startup recovery

func RecoverGatewayPending

func RecoverGatewayPending(ctx context.Context, store *SessionStore, cfg *GatewayConfig) (int, error)

Replays every pending spool the gateway owns, the launch home first then each served profile home

func RecoverLocalSessions

func RecoverLocalSessions(ctx context.Context, a *SessionAuthority, schedule bool) error

Restores every boot receipt of the authority, scheduling pending input when asked

func RecoverPendingSpool

func RecoverPendingSpool(ctx context.Context, sessionDB TranscriptAppender, resolver SpoolSessionResolver) (int, map[string]bool, error)

Replays flush files deleting each on success, returning the count and the sessions held back

func RecoverProfileNativeSessions

func RecoverProfileNativeSessions(ctx context.Context, runner any, authority *SessionAuthority) (*jsonutil.Object, error)

Binds one authority's queued native rows to the adapters connected now, returning each session's verdict

func RecoverWebhookFinalizations

func RecoverWebhookFinalizations(ctx context.Context, authority *SessionAuthority) (map[string]string, error)

Closes settled original webhook sessions whose current route authorization still holds, per session outcome

func RedactApprovalCommand

func RedactApprovalCommand(ctx context.Context, text any) string

Approval command or description with credential shaped values redacted for a client prompt

func RedactPhone

func RedactPhone(phone string) string

Phone number for logs keeping the country code and last four digits

func RedirectTargetFromResponse

func RedirectTargetFromResponse(resp *http.Response) string

Redirect target of a response for adapters outside the package, empty when it is not a redirect

func RedundantAutostartEntries

func RedundantAutostartEntries(ctx context.Context) ([]string, error)

Startup entries that fire the gateway a second time at logon beside a task or the vbs fallback

func RefreshLaunchdPlistIfNeeded

func RefreshLaunchdPlistIfNeeded(ctx context.Context) (bool, error)

Rewrites a stale installed plist and reloads it so launchd reads the new definition, true when reloaded

func RefreshPluginSessions

func RefreshPluginSessions(ctx context.Context, home, pluginKey, note string) error

Appends a newly live plugin's MCP tools to the open chats of a home and queues its note, nothing to do in a process that serves no chats

func RefreshSystemdUnitIfNeeded

func RefreshSystemdUnitIfNeeded(ctx context.Context, system bool) (bool, error)

Rewrites the installed systemd unit when its definition is out of date, true when it was rewritten

func RefuseForeignLaunchdPlist

func RefuseForeignLaunchdPlist(ctx context.Context, verb string) error

Exits 1 rather than operate a LaunchAgent that pins another home

func RefuseForeignSystemdUnit

func RefuseForeignSystemdUnit(ctx context.Context, action string, system bool) error

Exits 1 with guidance instead of operating another install's unit

func RefuseUnseatable

func RefuseUnseatable(members any, refused map[string]HostedMemberRefusal) error

Named refusal of the first local member whose profile the refusals name, nil when every one is seatable

func RefusedOwnerRemedy

func RefusedOwnerRemedy(reason string, pid int, ownerSession *uint32) string

User facing remedy for a refused owner boundary

func RefusesContainerUserScopeInstall

func RefusesContainerUserScopeInstall(w io.Writer, system bool) bool

Prints the refusal and reports true for a user scope unit install inside a container

func RegexGroupsParser

func RegexGroupsParser(pattern string, threadGroup bool) func(ref string) any

Parser explicit on a full match of the Python pattern, group one the chat id and group two the thread

func RegexStrippedParser

func RegexStrippedParser(pattern string) func(ref string) any

Parser explicit on a full match of the Python pattern that returns the whitespace stripped reference

func RegisterAdapterModule

func RegisterAdapterModule(classes ...*AdapterClass)

Records adapter classes under the package of their constructor so a lambda factory's module can be scanned

func RegisterBuiltinPlatformModule

func RegisterBuiltinPlatformModule(module string, attrs map[string]any)

Adds a platform module's attributes to the builtin adapter table

func RegisterBundledEnv

func RegisterBundledEnv(directory, prefix string, rows BundledEnvRows)

Records the gateway_env declarations of a bundled platform directory, called from the adapter package init

func RegisterRelayAdapter

func RegisterRelayAdapter(ctx context.Context) (bool, error)

Registers the relay platform when a connector URL resolves, never over an explicit profile disable

func RegisterRelayAdapterWith

func RegisterRelayAdapterWith(ctx context.Context, force bool, url *string) (bool, error)

Registers the relay platform for a resolved or given URL, a forced one without a URL building a transportless adapter

func RegisterSessionVoiceCaptureStop

func RegisterSessionVoiceCaptureStop(stop func(sessionID string))

Installs the TUI server's session voice capture stopper, the module tui_gateway.server loading in this process

func RegisterTransportHome

func RegisterTransportHome(runner AuthorityRunner, profile *string, profileHome *string) error

Records the transport home a server created a callback for, never from event home fields

func RegisterWorkerConfigHooks

func RegisterWorkerConfigHooks(ctx context.Context, failureMessage string, level slog.Level)

Registers the shell hooks and outbound webhooks of the current scope config, a failure logged at level

func RegisterWorkerHooks

func RegisterWorkerHooks(ctx context.Context, policy *LocalSessionPolicy) error

Registers the session's shell hooks and outbound webhooks from the frozen config in the worker, nothing for a bypass session

func RehydrateAPIImages

func RehydrateAPIImages(ctx context.Context, content any, media any) (any, error)

Transient content of an admitted API turn with its committed media references restored

func RelayAnsweredByProxy

func RelayAnsweredByProxy(exc *RelayHTTPError) bool

True when a response header names a proxy hop rather than the connector

func RelayCallback

func RelayCallback(ctx context.Context, transport, event any) context.Context

Context binding the authenticated relay reader's transport to its event

func RelayConnectionAuth

func RelayConnectionAuth(ctx context.Context) (string, string)

Enrolled gateway id and upgrade secret, both empty when either is absent

func RelayConnectorReason

func RelayConnectorReason(body []byte) string

Connector refusal reason from a JSON error object body, empty for anything else

func RelayDescribeHTTPError

func RelayDescribeHTTPError(exc *RelayHTTPError, body []byte, secrets ...string) string

HTTP status with the redacted origin headers and a one line redacted body excerpt

func RelayDisplayName

func RelayDisplayName(ctx context.Context) string

Customized agent display name capped at 64 characters, empty for the stock brand or when unset

func RelayEndpoint

func RelayEndpoint(ctx context.Context) string

Public inbound URL asserted at provision, empty for an outbound only gateway

func RelayExplicitlyDisabled

func RelayExplicitlyDisabled(ctx context.Context) (bool, error)

Explicit platforms.relay enabled false in the profile YAML, read with the gateway loader merge rules

func RelayFrontedPlatforms

func RelayFrontedPlatforms(ctx context.Context) map[string]bool

Fronted platforms raising a malformed relay config the way the uncaught Python exception does

func RelayFrontedPlatformsChecked

func RelayFrontedPlatformsChecked(ctx context.Context) (map[string]bool, error)

Logical platforms the relay fronts minus the generic relay fallback, empty when relay is explicitly disabled

func RelayInstanceID

func RelayInstanceID(ctx context.Context) string

Stable instance id forwarded at provision, empty when unset

func RelayMakeToken

func RelayMakeToken(payload, secret string, ttlSeconds int) string

Unpadded base64url of payload, expiry and signature, expiry zero when the ttl is not positive

func RelayMakeUpgradeToken

func RelayMakeUpgradeToken(gatewayID, secret string, ttlSeconds int) string

WS upgrade bearer whose payload is the gateway id the connector indexes its verify list by

func RelayMediaBaseURL

func RelayMediaBaseURL(relayDialURL string) string

HTTP connector base of a ws or wss relay dial URL

func RelayPassthroughEvent

func RelayPassthroughEvent(ctx context.Context, transport, forward, event any) context.Context

Context moving the reader's relay proof from the raw forward onto its decoded event

func RelayPlatformIdentities

func RelayPlatformIdentities() [][2]string

Ordered platform and bot id pairs the relay fronts for this process's profile, the generic relay pair when nothing is set

func RelayPlatformIdentity

func RelayPlatformIdentity() [2]string

Primary platform and bot id pair, the first of the fronted identities

func RelayProvisionPending

func RelayProvisionPending(ctx context.Context) bool

True when a relay is configured but this process holds no per gateway secret yet

func RelayReadErrorBody

func RelayReadErrorBody(exc *RelayHTTPError) []byte

Bounded body of an HTTP error response, empty when there is none

func RelayRedactExcerpt

func RelayRedactExcerpt(text string, secrets ...string) string

Text with every exact secret replaced then generically redacted

func RelayRelevancePolicy

func RelayRelevancePolicy(ctx context.Context, platform *string) *jsonutil.Object

Connector relevance policy of a fronted platform, nil when relay is generic or nothing non default is configured

func RelayRouteKeys

func RelayRouteKeys(ctx context.Context) []string

Route discriminators of gateway.relay_route_keys (or GATEWAY_RELAY_ROUTE_KEYS), each trimmed, empty when none

func RelayRoutedPlatform

func RelayRoutedPlatform(ctx context.Context, platformName string) (bool, error)

Whether a send to the platform would egress over the relay connector

func RelaySign

func RelaySign(payload, secret string) string

HMAC SHA256 hex digest of the payload under the secret, the connector sign

func RelayURL

func RelayURL(ctx context.Context) string

Effective connector URL raising a malformed relay config the way the uncaught Python exception does

func RelayURLChecked

func RelayURLChecked(ctx context.Context) (string, error)

Effective connector URL, empty when unset or vetoed by an explicit platform disable

func RelayURLOpen

func RelayURLOpen(req *http.Request, timeout time.Duration) ([]byte, error)

Body of a 2xx relay response, a non 2xx final status failing as RelayHTTPError and transport failures as RelayURLError

func RelayWakeURL

func RelayWakeURL(ctx context.Context) *string

Wake URL the connector pokes to revive a suspended gateway, nil when none is registered

func ReleaseAllScopedLocks

func ReleaseAllScopedLocks(ownerPid *int, ownerStartTime any) int

Removes scoped lock files, only those of ownerPid and ownerStartTime when given, returning the count

func ReleaseFileLock

func ReleaseFileLock(f *os.File)

Releases the lock of an open file, failures ignored

func ReleaseGatewayRuntimeLock

func ReleaseGatewayRuntimeLock()

Releases only this process's profile reservations, never their lock files

func ReleaseHostLock

func ReleaseHostLock(role string)

Releases the role host lock when this process holds it

func ReleaseRetiredWaiters

func ReleaseRetiredWaiters(a *SessionAuthority)

Releases every observer still waiting on an admission of a retired authority as runtime_draining

func ReleaseRuntimeClaim

func ReleaseRuntimeClaim(ctx context.Context, obligationID, errText string) (bool, error)

Returns this process's unsent runtime claim to failed without spending an attempt

func ReleaseScopedLock

func ReleaseScopedLock(scope, identity string)

Releases a scope lock owned by this pid whatever its recorded start time

func ReleaseSoon

func ReleaseSoon(lease LeaseReleaser)

Retires the lease from this process registry view now and queues its durable release on one worker

func ReleaseUnheldMediaRetainingHistory

func ReleaseUnheldMediaRetainingHistory(db *state.SessionDB, references []any) error

Releases unheld retained media, the transcript keeping every reference it still names

func ReleaseUnknownTurnMarkers

func ReleaseUnknownTurnMarkers(ctx context.Context, runner any, store *SessionStore) error

Clears crash left turn markers whose canonical admission recovered unknown, so no reply is owed

func ReloadGatewayPlugins

func ReloadGatewayPlugins(home, profileHome string, timeout time.Duration) *jsonutil.Object

Asks the gateway serving home to rediscover plugins for profileHome, home when empty

func ReloadGatewayPluginsAnswer

func ReloadGatewayPluginsAnswer(home, profileHome string, timeout time.Duration) map[string]any

Reload answer as a plain map for the plugin services, nil when no gateway answered

func RemotePathIsDenied

func RemotePathIsDenied(p string, remoteHome string) bool

Whether a sandbox path hits the host denylist, an unknown home matching home entries at any component

func RemoteRunReceipt

func RemoteRunReceipt(ctx context.Context, dbPath string, record map[string]any) (map[string]any, error)

Exact durable remote run handle of one task attempt, nil when none

func RemoveErasedHomeRendezvous

func RemoveErasedHomeRendezvous(homes ...string) []string

Removes the host records and scope locks of an erased home whose owner is gone, then the emptied lock dir and its icebath parent

func RemoveLegacyLaunchers

func RemoveLegacyLaunchers(ctx context.Context) error

Deletes the stray launchers, naming the exact elevated command for a task that needs elevation

func RemovePidFile

func RemovePidFile()

Removes the pid file only when it names this process

func RemoveRetiredGatewayServices

func RemoveRetiredGatewayServices(ctx context.Context, w io.Writer) (removed, running, system bool, err error)

Stops and deletes every retired service of the home in effect, reporting whether any ran and whether any was system scope

func RenameRoom

func RenameRoom(ctx context.Context, dbPath string, roomIDValue, eventIDValue, nameValue any, now *float64) (map[string]any, error)

Renames a live room and appends its replay event atomically

func RenderMCPEventPrompt

func RenderMCPEventPrompt(adapter *WebhookAdapter, routeConfig *jsonutil.Object, payload, eventType any, routeName string) (string, bool, error)

Prompt of an MCP event occurrence whose template names the data field, false for any other route

func RenderUserContentWithTimestamp

func RenderUserContentWithTimestamp(content, value any, tz *time.Location) (any, error)

User message for model context with exactly one timestamp prefix, an embedded stamp winning over value

func RendersExecApprovalButtons

func RendersExecApprovalButtons(adapter any) bool

Whether the adapter renders native approval buttons, a duck type counting when it sends approvals itself

func RepairExplicitComputerUseMediaPaths

func RepairExplicitComputerUseMediaPaths(response string, messages []any) string

Response with model mangled capture paths in explicit media tags restored to this turn's canonical paths

func RepairExplicitComputerUseMediaPathsAt

func RepairExplicitComputerUseMediaPathsAt(ctx context.Context, response string, messages []any, historyOffset int) string

Repair over the messages after the history offset, the response unchanged on any failure

func ReplaceIncompatibleOwner

func ReplaceIncompatibleOwner(ctx context.Context, h string, deadline float64) string

Stops the older gateway answering for home like gateway stop, empty once gone, else a refusal code

func ReplicaDownload

func ReplicaDownload(ctx context.Context, dbPath, roomID string, params map[string]any) (map[string]any, error)

A fetched file of a replicated event, else a fetch queued for the home and a refusal saying it is on its way

func ReplicaLink(ctx context.Context, dbPath, roomID string) (map[string]any, error)

Home link of a replicated room, nil when the room is no replica here

func ReplicaReadEvents

func ReplicaReadEvents(ctx context.Context, dbPath, roomID string, sinceValue, limitValue any) (map[string]any, error)

Monotonic replica log delta after sinceSeq, the page shape the home serves

func ReplicaRoom

func ReplicaRoom(ctx context.Context, dbPath, roomID string, includeDisbanded bool) (map[string]any, error)

One replicated room, a not found error when absent or disbanded and not asked for

func ReplicaRooms

func ReplicaRooms(ctx context.Context, dbPath string, includeDisbanded bool) ([]any, error)

Replicated rooms most recently changed first, disbanded ones only when asked

func ReplicaState

func ReplicaState(ctx context.Context, dbPath string, roomIDValue any) (map[string]any, error)

Stored replica coverage and authority lineage

func ReplicaStateView

func ReplicaStateView(ctx context.Context, dbPath, roomID string) (map[string]any, error)

Coverage, home, sync time, queued operations and recent refusals of one replica

func ReplicaUpload

func ReplicaUpload(ctx context.Context, dbPath, roomID string, params map[string]any) (map[string]any, error)

Keeps one composer file of a local user until the home takes it with the message that names it

func ReplyAnchorForEvent

func ReplyAnchorForEvent(event *MessageEvent) *string

Message id a reply to the event should anchor on, nil for none

func ReplyExpectedMetadata

func ReplyExpectedMetadata(replyExpected *bool) map[string]any

Persisted reply_expected key, only when the adapter knew

func ReportPrepareStall

func ReportPrepareStall(ctx context.Context, dbPath, roomID string, cause error)

Appends the room's one stall notice, a stall already last in the log not repeated

func ReportProfileStopFailure

func ReportProfileStopFailure(ctx context.Context, w io.Writer) int

ReportProfileStopFailure prints absence when proven, else the unconfirmed stop error and host hint with exit code 1

func ReportStartupProgress

func ReportStartupProgress(expectedS any, phase string)

Declares a phase owned progress lease on the armed watchdog, doing nothing when unarmed

func RequestBrokeredSuspend

func RequestBrokeredSuspend(ctx context.Context, rawURL string, timeout float64, client *http.Client) bool

POSTs the NAS sleep URL, true only on a 2xx and never raising

func RequestGatewaySelfRestart

func RequestGatewaySelfRestart(pid int) bool

Asks a gateway ancestor to restart itself through SIGUSR1, true when the signal went out

func RequestRoomStop

func RequestRoomStop(ctx context.Context, dbPath string, roomID, cancelIDValue, expectedGatewayID, expectedEpoch any) (map[string]any, error)

Appends an idempotent fence that supersedes earlier user turns

func RequestServeProfileHot

func RequestServeProfileHot(home, name string) *jsonutil.Object

Asks the multiplexer serving home to hot serve name

func RequestUnserveProfile

func RequestUnserveProfile(home, name string) *jsonutil.Object

Asks the multiplexer serving home to stop serving name

func RequireRootForSystemService

func RequireRootForSystemService(action string) error

SystemScopeRequiresRootError unless this process runs as root

func RescanGatewayProfiles

func RescanGatewayProfiles(home string, timeout time.Duration) *jsonutil.Object

Asks the multiplexer serving home to reconcile profiles now

func ReservePeerRoom

func ReservePeerRoom(ctx context.Context, dbPath string, claims *jsonutil.Object, expiresAt float64, now *float64) error

Fences direct local prompts for a room before the first peer run is admitted

func ReserveWaitingOutTransientHolders

func ReserveWaitingOutTransientHolders(ctx context.Context, ownership *ProfileOwnership, homes []string, wait time.Duration, cancel <-chan struct{}) error

Reserves homes, retrying while every contender is transient, until wait passes or cancel closes

func ResolveChannelPrompt

func ResolveChannelPrompt(configExtra map[string]any, channelID string, parentID string) (string, bool)

Channel prompt for the channel id, then the parent id, with blank prompts counting as absent

func ResolveChannelSkills

func ResolveChannelSkills(configExtra map[string]any, channelID string, parentID string) ([]string, bool)

Auto loaded skills bound to the channel id, then the parent id, deduplicated in order, ok false when none

func ResolveClientSocketPath

func ResolveClientSocketPath(home string) (string, error)

Socket a client connects to for home, empty when neither the direct socket nor a live pointer target exists

func ResolveCronDrainBudget

func ResolveCronDrainBudget(drainTimeout, cronDrainTimeout, watchdogDelay, elapsed, cleanupReserveS any) float64

Seconds the stop drain may wait on cron and api_server work, bounded by the watchdog leash and never below the drain

func ResolveFooterConfig

func ResolveFooterConfig(ctx context.Context, platformKey string) (bool, []string)

Whether the footer is on for a platform and the fields it shows, the platform's own choice winning

func ResolveGatewayModel

func ResolveGatewayModel(ctx context.Context, cfg map[string]any) string

Profile model of a config or the gateway config, else the claimed welcome trial model

func ResolveLaunchRoute

func ResolveLaunchRoute(ctx context.Context, params, cfg map[string]any) (map[string]any, error)

Launch params with an explicit model decoded for callers outside the package, the resume policy check of the CLI

func ResolveLaunchdCappedDrain

func ResolveLaunchdCappedDrain(drainTimeout, launchdExitTimeoutS, cleanupReserveS any) float64

Stop drain clamped to the launchd exit timeout minus the cleanup reserve, never extended

func ResolveMemoryHighMB

func ResolveMemoryHighMB(setting any) *int

Absolute MB budget, auto from the cgroup limit or total memory, a positive number literal, off words disabling the pass

func ResolvePluginMessageTarget

func ResolvePluginMessageTarget(ctx context.Context, runner any, sessionKey string, route any, pluginHome, pluginID string) (any, map[string]any, error)

Post target for the session key names, or the refusal, the live route serving an unstored session

func ResolveProxyURL

func ResolveProxyURL(ctx context.Context, platformEnvVar string, targetHosts []string, configured string) (string, error)

Proxy URL from the scoped platform var, the configured value, the trusted env or the macOS system proxy

func ResolveRelayIdentityToken

func ResolveRelayIdentityToken(ctx context.Context) (string, error)

Caller identity bearer the connector introspects, client credentials or an ambient endpoint of the configured IdP

func ResolveRestartExitWaitBudget

func ResolveRestartExitWaitBudget(drainTimeout, afterTurnTimeout, cronDrainTimeout, headroom any) (float64, error)

Seconds a CLI waits for the gateway to exit after SIGUSR1, infinite for a non finite drain

func ResolveSendTarget

func ResolveSendTarget(ctx context.Context, platform, ref string, passUnresolvedReferences bool) (chatID string, threadID *string, resolutionError string)

Chat and thread ids for one send target the same way for the model tool, the CLI and cron

func ResolveServerRequest

func ResolveServerRequest(frame *jsonutil.Object, sessionOK func(sessionID string, events *SessionEvents) bool) bool

Settles the open request a response frame answers, false when nothing here waits for its id

func ResolveServerSocketPath

func ResolveServerSocketPath(home string) (bindPath, pointerFile string, err error)

Bind path and pointer file of the server socket, the pointer set only for the short fallback path

func ResolveSessionIdleSecondsFromActivity

func ResolveSessionIdleSecondsFromActivity(activity map[string]any, now *float64) *float64

Idle seconds of an activity summary, its own idle figure else derived from the last activity stamp, nil without one

func ResolveShutdownWatchdogDelay

func ResolveShutdownWatchdogDelay(drainTimeout, graceS any) float64

Wall clock leash of the shutdown watchdog, the drain plus the grace

func ResolveStartupWatchdogTimeout

func ResolveStartupWatchdogTimeout(ctx context.Context) float64

Startup deadline seconds of the profile ctx serves, floor clamped, the default for a value of zero or below

func ResolveSystemdTimeoutStopSec

func ResolveSystemdTimeoutStopSec(drainTimeout, cronDrainTimeout, cleanupReserveS, headroomS, floorS any) (*big.Int, error)

Seconds systemd TimeoutStopSec must cover, int() of the float so infinity and NaN raise as Python does

func ResolvedRoute

func ResolvedRoute(ctx context.Context, block any, config any) (string, string, error)

Provider identity and effective base URL the runtime resolves a model block to

func RestartArgvIsHostGateway

func RestartArgvIsHostGateway(ctx context.Context, argv []string) bool

True when argv relaunches the host multiplexer, decided by settled identity before the default root comparison

func RestartLoopCheckAndRecord

func RestartLoopCheckAndRecord(ctx context.Context, maxRestarts, windowSeconds int, now *float64, maxGapSeconds int) (bool, error)

Records this boot and reports whether the chain reached the restart limit so auto resume is skipped

func RestartWaitOpen

func RestartWaitOpen(runner DrainRunner) bool

True while the runner is draining, still running and in a restart after turn wait

func RestoreAPIImages

func RestoreAPIImages(ctx context.Context, content []any, media []any) ([]any, error)

Transient content keeping its pixels with the committed reference of each inline image appended to its text

func RestoreAPISession

func RestoreAPISession(ctx context.Context, a *SessionAuthority, sessionID string) error

Restores an API session the authority bound earlier

func RestoreAttachments

func RestoreAttachments(ctx context.Context, frame *jsonutil.Object) ([]string, []string, error)

Committed attachment media urls and types of a bootstrap frame, nil for a text only frame

func RestoreCompletionRoute

func RestoreCompletionRoute(ctx context.Context, runner any, sessionKey string) error

Restores the ended local session a background completion reports to after a restart left it unrestored

func RestoreDisplay

func RestoreDisplay(committed any) (map[string]any, error)

Committed display_v1 crossing a process boundary is accepted only when admission could have committed it

func RestoreOutcome

func RestoreOutcome(res map[string]any) (tuigateway.RollbackRestoreResult, error)

Typed outcome of a checkpoint restore, a key the contract does not declare refused

func ResultFrame

func ResultFrame(result *jsonutil.Object) *jsonutil.Object

Worker side receipt fields of a run_conversation result, scalars only and text bounded

func RetireAfterReview

func RetireAfterReview(ctx context.Context, a *SessionAuthority, ref SessionRef, live *LiveSession) error

Retires a closed local session once its review finished, a no op while the session is still open

func RetiredOptOutNoticeLines

func RetiredOptOutNoticeLines() []string

Boxed one time notice of a rewritten multiplex opt out

func RetryNotBefore

func RetryNotBefore(updatedAt, lastError any, attempts int) (float64, bool)

Earliest resend moment of a failed row, false for a dead chat or one holding the last budgeted attempt

func RetrySelfProvision

func RetrySelfProvision(ctx context.Context, onProvisioned func()) (bool, error)

Retries provisioning until credentials exist, true only when this loop obtained them

func RetrySelfProvisionWith

func RetrySelfProvisionWith(ctx context.Context, onProvisioned func(), sleep func(context.Context, float64) error) (bool, error)

Retry loop pacing each attempt through the given sleep

func RevokeRoomGrantScope

func RevokeRoomGrantScope(ctx context.Context, dbPath string, claims *jsonutil.Object, expiresAt float64, now *float64) error

Revokes every grant issued at or before now for one exact room scope

func RichSentLookup

func RichSentLookup(ctx context.Context, chatID, messageID any) (string, bool)

Stored text of the chat and message, false when none was recorded

func RichSentLookupMedia

func RichSentLookupMedia(ctx context.Context, chatID, messageID any) [][2]string

Stored path and mime pairs of the chat and message whose file still exists

func RichSentRecord

func RichSentRecord(ctx context.Context, chatID, messageID any, text string)

Persists text sent or received for the chat and message, nothing for empty text or a missing key

func RichSentRecordMedia

func RichSentRecordMedia(ctx context.Context, chatID, messageID any, media [][2]string)

Persists local attachment path and mime pairs for the chat and message

func RoomGrantIsRevoked

func RoomGrantIsRevoked(ctx context.Context, dbPath string, claims *jsonutil.Object, now *float64) (bool, error)

Whether a grant predates its exact scope's revocation fence

func RoomGrantNeedsDispatchRefresh

func RoomGrantNeedsDispatchRefresh(token string, now *float64, leewaySeconds float64) bool

Whether grant timing alone calls for a dispatch refresh, true for any unreadable token

func RoomPeerRegistry

func RoomPeerRegistry(ctx context.Context) ([]any, error)

Registered peers with their URL, key presence and note, sorted by name

func RoomSessionTitle

func RoomSessionTitle(roomID string) string

Canonical hidden session title of one hosted room

func RoomShareSync

func RoomShareSync(ctx context.Context, runner any, body *jsonutil.Object) (map[string]any, error)

Takes one sync of a room home, storing its pages and status, answering cursors and the operations local users queued

func RoomShares

func RoomShares(ctx context.Context, dbPath, roomID string) ([]any, error)

Share rows of one room, or of every room for an empty id

func RoomState

func RoomState(ctx context.Context, dbPath string, roomIDValue any, includeDisbanded bool) (map[string]any, error)

Durable replay and authority state of one room

func RouteLaunchKey

func RouteLaunchKey(ctx context.Context, authority *SessionAuthority, policy *LocalSessionPolicy, config map[string]any) (*string, error)

Launch key a turn on the config sends under the authority, nil once the route left the bound endpoint

func RouteOwnerLock

func RouteOwnerLock(ctx context.Context, runner any, sessionID string) (*sync.Mutex, error)

Owner mutation lock held across a route rotation, for the runner's reset paths

func RouteRuntime

func RouteRuntime(ctx context.Context, policy *LocalSessionPolicy, frozen map[string]any, model, key *string, fallback bool) (*provider.Runtime, map[string]any, error)

RouteRuntime resolves a launch policy route on the frozen config and launch key, walking its own fallback chain when allowed

func RoutingAgentKwargs

func RoutingAgentKwargs(cfg map[string]any, model, providerName, baseURL string) map[string]any

Provider routing agent arguments of a frozen session config, a static fast tier carrying its request overrides

func RowInt

func RowInt(row *jsonutil.Object, key string) *int64

Integer column of a session row, nil for NULL or a non numeric value

func RunAPIStepsOffLoop

func RunAPIStepsOffLoop(ctx context.Context, adapter APITurnAdapter, steps WriteSteps) (any, error)

Drives an API admission step sequence off the caller in admission order, an orphaned admission still drained

func RunAPITurn

func RunAPITurn(ctx context.Context, adapter APITurnAdapter, turn *APITurn) (map[string]any, map[string]any, error)

Admits and observes one API turn, a streaming caller's run id bound to the admission's shared approval prompt

func RunBoundTurn

func RunBoundTurn(ctx context.Context, name, arg, taskID, platform string) (string, error)

Turn of a bound command for one session, an empty turn refused as unavailable

func RunDeferredIntegrityCheck

func RunDeferredIntegrityCheck(ctx context.Context, evidence *jsonutil.Object, h string, deadlineS float64) (verdict string)

Post connect state.db scan of an unclean exit appending a second diag record, never panics

func RunFollowupProcessingHook

func RunFollowupProcessingHook(ctx context.Context, adapter PlatformAdapter, event *MessageEvent, hookName string, outcome ProcessingOutcome)

Fires one lifecycle hook for a runner drained follow up, a no op unless the follow up hooks apply

func RunPostDeliveryCallback

func RunPostDeliveryCallback(ctx context.Context, callback PostDeliveryCallback, timeout float64)

Runs the callback bounded by the timeout with every error swallowed, nothing for a nil callback

func RunSecurityAudit

func RunSecurityAudit(ctx context.Context, dataHome string) []string

Every posture finding as readable text, a check that panics contributing nothing

func RunStepsOffLoop

func RunStepsOffLoop(ctx context.Context, a *SessionAuthority, steps WriteSteps) (any, error)

Drives write steps as one tracked task, each write off the caller in admission order

func RuntimeStatusHeartbeatAgeS

func RuntimeStatusHeartbeatAgeS(record *jsonutil.Object) (int, bool, error)

Whole seconds since the snapshot updated_at, false when missing or unparseable

func RuntimeStatusIsStale

func RuntimeStatusIsStale(record *jsonutil.Object, ttl int) bool

Whether the snapshot updated_at is older than ttl or missing

func RuntimeStatusPidIsLive

func RuntimeStatusPidIsLive(record *jsonutil.Object) bool

Whether the snapshot pid is alive and passes the start time reuse guard

func SSRFRedirectGuard

func SSRFRedirectGuard(env *tools.Env, target string) error

Refuses a redirect whose target is a private or internal address

func SafeProxyURLForLog

func SafeProxyURLForLog(raw string) string

scheme://host[:port] of a proxy URL for a log line, cut at the log limit, the placeholder when the URL has no clean authority

func SafeURLForLog

func SafeURLForLog(raw string, maxLen int) string

URL for a log line: scheme://host[:port] and the file name of a media path, never the query, fragment, user info or any other path segment; a local file URL without an authority is kept up to its query; text with no parsed authority is replaced by a fixed placeholder, since no part of it can be told apart from a credential

func SameIcebathHome

func SameIcebathHome(left, right string) (bool, error)

Compares two home paths with the host platform case rules for callers outside this package

func SameOwner

func SameOwner(stored, subject any) bool

True when a stored owner stamp belongs to subject, older sign in stamps reading as the host owner's

func SameRoute

func SameRoute(ctx context.Context, a, b any, config any) (bool, error)

Whether both model blocks resolve to one endpoint, auto on either side keeping the route

func SampleMemory

func SampleMemory() *jsonutil.Object

Own RSS, MemTotal, MemAvailable and swap used in KiB from proc, empty off Linux

func SanitizeModelOverride

func SanitizeModelOverride(override any) *jsonutil.Object

Copy of a dict override with only persistable non empty keys as strings, nil when nothing is left

func SanitizePromptPin

func SanitizePromptPin(pin any) *jsonutil.Object

Validated durable snapshot of the ephemeral prompt inputs, nil when malformed or of another version

func SaveRoomLink(ctx context.Context, dbPath string, link StoredRoomLink) error

Persists one link and keeps the store private on POSIX

func ScaleToZeroEnabled

func ScaleToZeroEnabled(ctx context.Context) bool

Whether gateway.scale_to_zero.enabled (or its ICEBATH_SCALE_TO_ZERO override) is on for the profile ctx serves

func ScaleToZeroIdleTimeoutSeconds

func ScaleToZeroIdleTimeoutSeconds(ctx context.Context) float64

Idle window in seconds before an armed instance suspends, the default for a value of zero or below

func ScopedLockOwnerLabel

func ScopedLockOwnerLabel(record any) string

Profile label of a scoped lock owner from its profile field or its recorded home, empty when unknown

func SeedCompressionCount

func SeedCompressionCount(live *LiveSession, agent any)

Seeds the agent compression counter from the count the live session carried

func SeedExtraFromEnv

func SeedExtraFromEnv(ctx context.Context, spec []EnvSeedRow, homeEnv, homeDefault string) (map[string]any, error)

Extra seeded from the profile scoped env, with the home channel from homeEnv and its name var

func SelectSystemdScope

func SelectSystemdScope(ctx context.Context, system bool) (bool, error)

Effective scope, the system scope when only the system unit is installed

func SelfProvisionRelay

func SelfProvisionRelay(ctx context.Context) (bool, error)

Self provisions the relay at boot, true only when credentials were obtained, never failing for connector trouble

func SelfSuspendAvailable

func SelfSuspendAvailable(env map[string]string) bool

True when Fly machine identity is present and the local Machines API socket exists

func SendError

func SendError(message any) map[string]any

Standalone sender failure envelope with vendor exception text redacted

func SendRelayPolicy

func SendRelayPolicy(ctx context.Context) (bool, error)

Declares the relevance policy per fronted platform, true when the connector accepted at least one

func ServedProfileIngressURLs

func ServedProfileIngressURLs(profile string) (*jsonutil.Object, error)

Profile to platform to URL for every secondary inbound platform the live multiplexer serves, narrowed to profile when set

func ServedProfileName

func ServedProfileName(profileHome string) string

Canonical profile id of a served home, default for the root and any custom home

func ServedProfileUnservedPlatforms

func ServedProfileUnservedPlatforms(profile string) (*jsonutil.Object, error)

Platform to reason for a served profile's platforms the multiplexer deliberately does not run

func ServerProcessArgv

func ServerProcessArgv(argv []string) (bool, error)

Reports whether argv launches a foreground gateway, the one long lived server

func ServiceBackendName

func ServiceBackendName(ctx context.Context, windows bool) string

Host service manager name in the canonical predicate order, empty when none applies

func ServiceCall

func ServiceCall(ctx context.Context, backend, verb string, system bool) error

Runs start, stop, restart or uninstall on the named service backend

func ServiceHomeForUnit

func ServiceHomeForUnit(ctx context.Context, unitPath string, system bool) (string, error)

Pinned home of the systemd unit file

func ServicePinnedHome

func ServicePinnedHome(definition string) (string, error)

ICEBATH_HOME pinned by the systemd unit or launchd plist at definition, empty when it pins none

func ServiceScopeLabel

func ServiceScopeLabel(system bool) string

Scope label of a systemd scope

func ServiceSuffix

func ServiceSuffix(ctx context.Context, h string) (string, error)

Host service suffix of the requested home, empty for the native default and a path hash for a foreign root

func SessionBusyMode

func SessionBusyMode(ctx context.Context, runner AuthorityRunner, live *LiveSession) (string, error)

Busy mode the local session's next input runs under, its own pin, else its policy, else the runner's

func SessionKeyNamespace

func SessionKeyNamespace(profile string) string

Key prefix agent main for the default profile, agent main tilde for a profile named main, else agent and the name

func SessionOwnSetting

func SessionOwnSetting(ctx context.Context, live *LiveSession, key string) (any, bool)

Value a local live session chose for a setting itself, false when it follows the profile

func SessionOwnedByProfile

func SessionOwnedByProfile(ctx context.Context, cfg *GatewayConfig, profile string, sessionID string) bool

Whether served profile's own session store canonically owns a stateless raw session id

func SessionPrefill

func SessionPrefill(ctx context.Context, a *SessionAuthority, policy *LocalSessionPolicy, sessionID string) ([]any, error)

Prefill messages a local session policy freezes for the session

func SessionRouting

func SessionRouting(ctx context.Context, a *SessionAuthority, policy *LocalSessionPolicy) (map[string]any, error)

Provider routing a local session policy freezes for its agents

func SessionTicket

func SessionTicket(home string, endpoint *GatewayEndpoint, purpose string) (string, error)

Ticket of the given purpose the endpoint's owner mints for this home, the _session_ticket a worker dials with

func SetActiveAPIRunner

func SetActiveAPIRunner(runner AuthorityRunner)

Records the runner the session API mount serves, nil when the mount closes

func SetAuthorizationProfileHome

func SetAuthorizationProfileHome(source *SessionSource, transportHome string)

Stamps the transport home a secondary bot's event authorizes against

func SetCronOwnerHooks

func SetCronOwnerHooks(h *CronOwnerHooks)

Installs the cron scheduler functions the owner reaches

func SetGatewayRunnerRef

func SetGatewayRunnerRef(runner any)

Records the gateway runner of this process, nil clearing it, the run.py weak reference

func SetLocalVoiceMode

func SetLocalVoiceMode(sessionID any, mode string) (*bool, error)

SetLocalVoiceMode sets and persists a local session's voice mode on the running owner, nil when no owner here holds it

func SetResolveChannelNameFn

func SetResolveChannelNameFn(fn func(ctx context.Context, platformName, name string) (string, error)) func(context.Context, string, string) (string, error)

Replaces the channel directory lookup and returns the one it replaced

func SetTransportAdapterRef

func SetTransportAdapterRef(source *SessionSource, adapter PlatformAdapter)

Pins the adapter that built a source

func SettingList

func SettingList(ctx context.Context, e settings.Entry) []string

Items a list setting holds for the profile ctx serves, each trimmed and blank ones dropped; nil for a setting that is no list

func SettingSet

func SettingSet(ctx context.Context, e settings.Entry) map[string]bool

Set of the items a list setting holds for the profile ctx serves

func SettingText

func SettingText(ctx context.Context, e settings.Entry) string

Text of a setting the profile ctx serves set: a list comma joined, a switch true or false, a length of time in seconds, empty while only the default applies

func SettingsContext

func SettingsContext(ctx context.Context) context.Context

Context whose settings reads resolve in the profile a platform task serves, the secret scope's home when no home is bound

func SettleHeldDelivery

func SettleHeldDelivery(ctx context.Context, profileHome string, owner map[string]any, message, deliveryID string, author map[string]any) (map[string]any, error)

Finalizes an unadmitted refusal under the same identity, or answers the receipt that admitted it meanwhile

func SettleRuntimeStatus

func SettleRuntimeStatus()

Waits until every runtime status update submitted so far was written or failed

func SettleStoreOutageMessage

func SettleStoreOutageMessage(path string)

Deletes the copy of a re-dispatched message once its turn settled

func SettledExplicitFlag

func SettledExplicitFlag(value *bool) *bool

How boot reads an explicit flag, true final and the retired false settling like unset

func SetupStandardPlatform

func SetupStandardPlatform(ctx context.Context, p SetupPlatform) error

Runs the standard setup form of a platform row for the platform plugins

func SetupTelegram

func SetupTelegram(ctx context.Context) error

Telegram credentials and allowlist wizard of the CLI setup

func SharedIngressProfile

func SharedIngressProfile(adapter PlatformAdapter) string

Profile name when the adapter was built in shared listener mode, empty otherwise

func SharedListenerBase

func SharedListenerBase(runner any) string

Base URL of the default profile's live listener, api_server first then webhook, empty when neither runs

func SharedListenerMirrorPlatformsFor

func SharedListenerMirrorPlatformsFor(runtime *jsonutil.Object, profile string) *jsonutil.Object

The api_server and webhook mirrors a served profile gets from the default listener

func ShouldArm

func ShouldArm(enabled, relayOnlyOrAbsent bool, wakeURL *string) bool

Arms the idle watcher only with the flag on, relay only messaging and a registered wake URL

func ShouldAutoTTSForChat

func ShouldAutoTTSForChat(adapter PlatformAdapter, chatID string) bool

Whether the adapter synthesizes speech for the chat on its own

func ShouldBypassProxy

func ShouldBypassProxy(targetHosts []string) bool

Reports whether NO_PROXY matches at least one of the target hosts

func ShouldClearSessionStallNotification

func ShouldClearSessionStallNotification(timeoutSeconds float64, idleSeconds *float64, hasPendingInbound bool) bool

Whether the stall latch clears, unknown progress holding it

func ShouldEmitSessionStallNotification

func ShouldEmitSessionStallNotification(timeoutSeconds float64, idleSeconds *float64, hasPendingInbound, alreadyNotified bool) bool

Whether a pending inbound session idle past the timeout owes its one stall notice

func ShouldRedactPII

func ShouldRedactPII(ctx context.Context, platform Platform, enabled bool) bool

Whether PII is redacted for the platform when the privacy config enables it

func ShouldSendMediaAsAudio

func ShouldSendMediaAsAudio(platform Platform, ext string, isVoice bool) bool

True when a media file goes through the platform audio sender, Telegram taking only voice or MP3 and M4A

func SideScope

func SideScope(ctx context.Context, a *SessionAuthority, policy *LocalSessionPolicy, taskID string, body func(ctx context.Context, env *tools.Env) error) error

Runs body in the owning profile scope and frozen policy with its secrets, the task session identity and workspace bound

func SilenceAllowed

func SilenceAllowed(displayKind any, replyExpected, allowSilence *bool, agentResult map[string]any) bool

Existing exemptions, or a room opt in backed by a healthy completed result

func SlackToolsLoaded

func SlackToolsLoaded(ctx context.Context) bool

Whether the Slack tools are loaded for the session context renderer gate

func SnapshotShutdownContext

func SnapshotShutdownContext(receivedSignal *int) *jsonutil.Object

Fast snapshot of who asks this process to shut down, never blocking and never failing

func SniffIngressImageMime

func SniffIngressImageMime(data []byte) string

Admission image type the bytes really are, empty for anything else

func SourceSurface

func SourceSurface(label string) string

Agent surface a creation label runs on, a free source tag running on the cli surface, empty for no valid label

func SpawnAsyncDiagnostic

func SpawnAsyncDiagnostic(logPath, signalName string, timeoutSeconds float64) (int, bool)

Pid of a detached process listing appended to logPath, false on failure or Windows

func SpawnDetachedGateway

func SpawnDetachedGateway(ctx context.Context) (bool, error)

Starts the gateway as a detached background process, false when the spawn failed

func SpawnDetachedIn

func SpawnDetachedIn(ctx context.Context, profileHome string) (int, error)

Launches the gateway of a profile home fully detached, the caller's own gateway when empty

func SpawnGatewayRestartWatcher

func SpawnGatewayRestartWatcher(ctx context.Context, oldPid int, runArgv []string, host *bool, profileHome string) (bool, error)

Spawns the detached watcher that respawns runArgv once oldPid exits, false when it could not be started

func SpawnSideAgent

func SpawnSideAgent(ctx context.Context, a *SessionAuthority, ref SessionRef, taskID, eventType string,
	body func(ctx context.Context) (string, error), extra *jsonutil.Object, holder SideAgentHolder) *jsonutil.Object

Runs body on its own goroutine counted as owner work, publishing its text or error on the session

func SplitAtParagraphBoundary

func SplitAtParagraphBoundary(text string, maxChars int, lenFn func(string) int) (string, string)

Head within maxChars cut at a blank line, a sentence end, a newline or the window edge, plus the tail

func SplitMarkdownAtoms

func SplitMarkdownAtoms(text string) []string

Fenced code blocks, tables and paragraphs as indivisible atoms, blank lines belonging to none

func SplitMarkdownTableRow

func SplitMarkdownTableRow(line string) []string

Stripped cells of a markdown table row

func SplitTextFenceAware

func SplitTextFenceAware(text string, limit int, lenFn func(string) int, preferParagraphs, balanceFences bool) []string

Markdown split into chunks within limit respecting fences, by paragraphs or by newlines

func SpoolDroppedTranscriptMessage

func SpoolDroppedTranscriptMessage(ctx context.Context, sessionID string, message map[string]any) string

Spools one cap evicted transcript message as a private payload, empty when the write failed

func StagePeerRunFiles

func StagePeerRunFiles(ctx context.Context, dbPath, scope, runID, output string) (string, []any, error)

Reply text of a finished run without MEDIA directives, the files they name staged for the room home

func StampLine

func StampLine(line string) string

Line with a leading timestamp unless it already has one, ending in exactly one newline

func StandaloneLauncher

func StandaloneLauncher(ctx context.Context) (bool, error)

Whether the launching home is a named profile that opted out with gateway.standalone

func StandaloneRescanMessage

func StandaloneRescanMessage(profile string) string

func StandaloneWarningLines

func StandaloneWarningLines(ctx context.Context, source, reason string, unserved []string, haveUnserved bool) []string

Boxed warning of a guard kept standalone gateway on a host with unserved profiles, empty otherwise

func StartDetachedReplacement

func StartDetachedReplacement(ctx context.Context, profileHome string, force bool, stdout, stderr io.Writer) int

Starts a stopped owner's replacement in the background, exit 1 with the reason when it cannot

func StartExistingGatewayService

func StartExistingGatewayService(ctx context.Context, service *ExistingService, deadline float64) error

Requests one start of a stopped service, never treating the request as readiness

func StartReadyHostedServices

func StartReadyHostedServices(runner any) error

Starts a fully prepared served set behind the published ready gate, then imports once more

func StartTimeFingerprintsMatch

func StartTimeFingerprintsMatch(recorded, current any, tolerance int) (bool, error)

Whether two start time fingerprints are the same incarnation within tolerance, an error for junk

func StartupFailureReport

func StartupFailureReport(ctx context.Context, profileHome string, offset int64, status int, pid *int) string

Exit status, redacted tail of this launch's output and the command showing the whole log

func StartupWatchdogDisabled

func StartupWatchdogDisabled(ctx context.Context) bool

Whether gateway.startup_watchdog (or its ICEBATH_STARTUP_WATCHDOG override) is off for the profile ctx serves

func StderrTimestampMain

func StderrTimestampMain(argv []string) int

Runs the child with stamped stdout and stamped stderr appended to the error log, returning the supervisor exit status

func StdinConsoleModeOK

func StdinConsoleModeOK() *bool

Windows console mode verdict of stdin, nil off Windows where isatty alone decides

func StdinIsInteractive

func StdinIsInteractive(isatty bool, consoleModeOK *bool) bool

Whether stdin can answer a prompt, a tty that also passes the Windows console mode check

func StdioLogPath

func StdioLogPath(profileHome string) string

Append only stdio log a detached daemon writes before its logging is up

func StdioLogSize

func StdioLogSize(profileHome string) int64

Offset where this launch's output starts in the stdio log, zero when it cannot be read

func StopAuthorityTurns

func StopAuthorityTurns(runner any, a *SessionAuthority, inProcess bool, reason *string) int

Cooperative stop of every turn the authority executes, recording reason on each signalled worker

func StopAuthorityWork

func StopAuthorityWork(a *SessionAuthority)

Stops every turn, hard interrupts each live worker and side agent and cancels cron runs

func StopHostedService

func StopHostedService(ctx context.Context, runner any, timeout float64) bool

Stops the hosted room service of every authority within one shared deadline, true when all stopped

func StopManagedTurns

func StopManagedTurns(runner any, reason *string) int

Cooperative stop of every turn across every served authority, the whole runtime shutdown

func StopProfileGateway

func StopProfileGateway(ctx context.Context) (bool, error)

Stops only this profile's own gateway through its pid file then reaps orphans, true when a process was stopped

func StopTypingWithMetadata

func StopTypingWithMetadata(ctx context.Context, adapter PlatformAdapter, chatID string, metadata map[string]any) error

Stops the adapter typing indicator scoped to the thread metadata of the turn

func StoreUpload

func StoreUpload(ctx context.Context, service *HostedRoomService, roomID string, params map[string]any) (map[string]any, error)

Retains one composer file for a later groups.send manifest on either route

func StoredRoomAuthority

func StoredRoomAuthority(ctx context.Context, dbPath, roomID string) (string, bool, error)

Authority gateway id the room store records for a room, false when the store has no such room

func StreamingTTSShouldSkipWholeFile

func StreamingTTSShouldSkipWholeFile(completedTurns map[string]struct{}, sessionKey string, turnMarker any, event *MessageEvent) bool

Whether the turn already streamed its audio so the whole file auto TTS is skipped

func StreamingTTSTurnCompleted

func StreamingTTSTurnCompleted(adapter PlatformAdapter, sessionKey string, generation int) bool

Whether streaming TTS already delivered this turn's audio on the adapter

func StreamingTTSTurnKey

func StreamingTTSTurnKey(sessionKey string, turnMarker any, event *MessageEvent) (string, bool)

Turn scoped suppression key from the run generation or else the event message or update id

func StripImageTagsForDisplay

func StripImageTagsForDisplay(text string) string

Text with the image tags delivered as attachments hidden along with up to two line breaks after each

func StripLeadingMessageTimestamps

func StripLeadingMessageTimestamps(content any, tz *time.Location) (any, *float64)

Leading gateway timestamp prefixes removed, with the epoch of the prefix closest to the text

func StripLower

func StripLower(value string) any

Value stripped and lower cased

func StripMarkdown

func StripMarkdown(text string, keepLinkTargets bool) string

Markdown stripped for plain text platforms, link targets kept as bare urls when asked

func StripMediaDirectives

func StripMediaDirectives(ctx context.Context, text string) (string, error)

Removes MEDIA directives from a message body

func StripMediaDirectivesForDisplay

func StripMediaDirectivesForDisplay(ctx context.Context, text string) (string, error)

Display text without media directives, extensionless tags hidden only when they validate

func StripSlash

func StripSlash(value string) any

Value with trailing slashes removed

func StripTrailingSilenceMarker

func StripTrailingSilenceMarker(response any) any

Reply without a silence marker that closes it on its own line, a bare marker unchanged

func SubmissionPayload

func SubmissionPayload(ctx context.Context, rpc *HostedRoomAuthorityRPC, prompt string, attachments any) (map[string]any, error)

Turn payload of the producer's member from event bound authorized bytes only, never a caller path

func SubmissionTurnScope

func SubmissionTurnScope(ctx context.Context, admissionID, submissionID string) context.Context

Binds the client submission id to the admission event for the returned context only

func SubmitAPIWorker

func SubmitAPIWorker(submit func(counted func() (any, error)) error, fn func() (any, error)) error

Submits fn through submit with the worker lifetime count held until the worker itself returns

func SubmitDisplayFields

func SubmitDisplayFields(params map[string]any) map[string]any

Raw per turn presentation fields of a prompt.submit request forwarded to admission

func SupersedeHostSignalCleanup

func SupersedeHostSignalCleanup()

Drops the SIGTERM cleanup once the gateway loop owns the signal, the way its later handler replaces the earlier one

func SupportsSystemdServices

func SupportsSystemdServices(ctx context.Context) bool

True when this host can manage the gateway as a systemd service

func SurfaceTurn

func SurfaceTurn(ctx context.Context) *jsonutil.Object

Committed surface of the executing admission, nil outside a surface turn scope

func SurfaceVoiceTurn

func SurfaceVoiceTurn(ctx context.Context) bool

Whether the executing admission is a spoken voice turn on the voice chat route

func SuspendAvailable

func SuspendAvailable(env map[string]string) bool

Whether an in guest or brokered suspend lever exists

func SuspendSelf

func SuspendSelf(env map[string]string, socketPath string, timeout float64) bool

POSTs the local flaps suspend for this machine over its unix socket, true when flaps answered 2xx

func SwapCronExecutionIDGuard

func SwapCronExecutionIDGuard(guard func(executionID string) bool) func(executionID string) bool

Replaces the fresh admission colon guard and returns the one it replaced

func SyncIcebathHomeFromSystemdUnit

func SyncIcebathHomeFromSystemdUnit(ctx context.Context, system bool) error

Adopts the system unit's pinned home into ICEBATH_HOME so runtime status and pid reads follow the unit

func SystemServiceIdentity

func SystemServiceIdentity(runAsUser string) (string, string, string, int, error)

Account, group, home dir and uid a system unit would run as, the ServiceUserError refusal otherwise

func SystemUnitDir

func SystemUnitDir() string

Directory system scope unit files live in

func SystemctlCmd

func SystemctlCmd(system bool) []string

Systemctl argv prefix of a scope, run with UserSystemdEnv so the user scope reaches this user's manager

func SystemdInstall

func SystemdInstall(ctx context.Context, w io.Writer, force, system bool, runAsUser string, enableOnStartup, nonInteractive, forceUnitPath bool) error

Writes the systemd unit for this home and enables it as asked

func SystemdMainPID

func SystemdMainPID(ctx context.Context, system bool) (int, bool, error)

MainPID of the gateway unit when positive

func SystemdNotify

func SystemdNotify(message string) bool

Sends one sd_notify datagram when systemd configured a socket, false on any failure

func SystemdOwnerForPid

func SystemdOwnerForPid(ctx context.Context, pid int) (unit, scope string, ok bool)

Unit and scope of the systemd unit whose MainPID is pid, the scope empty when the cgroup omits it

func SystemdRestart

func SystemdRestart(ctx context.Context, system bool) error

Restarts the systemd gateway service gracefully, escalating a wedged loop and recovering a pending restart

func SystemdRestartCommands

func SystemdRestartCommands(unit string, scope any) ([]string, error)

Commands restarting a systemd unit in its scope, both forms for an unknown scope, an error for an unhashable one

func SystemdStart

func SystemdStart(ctx context.Context, system bool) error

Starts the systemd gateway service of the scope after refreshing its unit

func SystemdStatus

func SystemdStatus(ctx context.Context, w io.Writer, deep, system, full bool, printRuntimeHealth func() error) error

Prints the systemd unit state, restart and linger notes, health and on deep the recent journal

func SystemdStop

func SystemdStop(ctx context.Context, system bool) error

Stops the systemd gateway service of the scope after marking the stop as planned

func SystemdStopMarkMain

func SystemdStopMarkMain(ctx context.Context, argv []string) (code int)

Writes the planned stop marker for the supervised pid, exiting zero whatever happens

func SystemdUninstall

func SystemdUninstall(ctx context.Context, system bool) error

Stops, disables and removes the systemd gateway unit of the scope unless it belongs to another home

func SystemdUnitBelongsToCurrentHome

func SystemdUnitBelongsToCurrentHome(ctx context.Context, system bool) (bool, error)

False with a warning when the installed unit pins another home, so removing it would take down another install

func SystemdUnitIsActive

func SystemdUnitIsActive(ctx context.Context, system bool) (bool, error)

True when the scope's unit is installed and systemctl reports it active

func SystemdUnitIsCurrent

func SystemdUnitIsCurrent(ctx context.Context, system bool) (bool, error)

True when the installed unit matches the generated one apart from optional directives, after syncing the unit home

func SystemdWatchdogIntervalSeconds

func SystemdWatchdogIntervalSeconds() *float64

Watchdog interval systemd requested in seconds, nil when unset, invalid or not positive

func TUIBootstrapControlQuery

func TUIBootstrapControlQuery(home string, request []byte, timeout time.Duration) ([]byte, error)

One response line of at most 65537 bytes from the private control socket, each receive bounded by timeout

func TUIContextID

func TUIContextID(ctx context.Context, a *SessionAuthority, ref SessionRef) (string, error)

Compression tip the session's model context lives in

func TUIModelHistory

func TUIModelHistory(ctx context.Context, db *state.SessionDB, tip string) ([]map[string]any, error)

Active rows of the tip as live replay loads them without session_meta bookkeeping

func TUIStoredID

func TUIStoredID(ctx context.Context, a *SessionAuthority, ref SessionRef) string

Stored row id a TUI read renders for the session, its local receipt's entry winning

func TakeOverScopedLockHolder

func TakeOverScopedLockHolder(ctx context.Context, record *jsonutil.Object, gracefulAttempts, forceAttempts int) (int, bool)

Terminates one verified scoped lock holder for replace, the owner pid once that exact identity exited

func TaskMemberID

func TaskMemberID(task map[string]any) string

Member id of a task, its target profile when no member id is set

func TerminatePid

func TerminatePid(pid int, force bool, expectedStartTime any) error

Terminates pid with SIGTERM or a guarded force kill, taskkill tree kill for a Windows force

func TextHasUnclosedFence

func TextHasUnclosedFence(text string) bool

True when the text ends inside an unclosed code fence

func TextToSpeech

func TextToSpeech(ctx context.Context, text, outputPath string) (string, error)

Speech synthesized into the output path for callers outside the gateway, refused without the speech backends

func ToWhatsAppJID

func ToWhatsAppJID(value string) string

Bridge safe outbound JID, a bare phone gaining the user server and a device suffix dropped

func ToolCompletePayload

func ToolCompletePayload(ctx context.Context, callID, toolName, args, result any, isError *bool) *jsonutil.Object

Tool complete payload with the error flag and the text the call printed

func ToolFrame

func ToolFrame(ctx context.Context, callID, name any, args any, result ...any) (*jsonutil.Object, error)

Tool callback arguments as the owner builds the shared tool event from them, args and result bounded

func ToolLifecyclePayload

func ToolLifecyclePayload(ctx context.Context, callID, toolName, args any) *jsonutil.Object

Tool start payload of the lifecycle contract with the call id, name and bounded args

func ToolNameByCallID

func ToolNameByCallID(messages []any) (map[string]string, error)

Assistant tool call ids mapped to their tool names

func TranscodeToOggOpus

func TranscodeToOggOpus(ctx context.Context, path, bitrate string, timeout time.Duration, outputPath string) (string, error)

Encodes the file to voip tuned Ogg Opus through ffmpeg, empty when ffmpeg is missing or the encode fails

func TranscriptTarget

func TranscriptTarget(ctx context.Context, a *SessionAuthority, ref SessionRef) (string, error)

Physical transcript a local session's history reads, its compression continuation when rotated

func TransportProfileOf

func TransportProfileOf(source *SessionSource) string

Receiving bot profile to persist with a route, empty outside multiplexing or for an inferred messaging transport

func TrimTerminalSentinel

func TrimTerminalSentinel(text string) string

Text with a terminal run of end of sequence tokens cut and the remainder right stripped

func TruncateMessage

func TruncateMessage(content string, maxLength int, lenFn func(string) int) []string

Splits a long message into chunks that close and reopen split code fences and carry part indicators

func TruncatePreview

func TruncatePreview(text string, budget int, suffix string) string

Text cut to budget code points with the suffix appended when it was cut

func TrustEnvHTTPClient

func TrustEnvHTTPClient(ctx context.Context, timeout time.Duration) *http.Client

HTTP client with a total timeout reading proxy env vars only when the gateway trusts the environment

func TrustedEnvProxyForRedaction

func TrustedEnvProxyForRedaction(ctx context.Context, targets ...string) string

Proxy value of the environment to hand DescribeProxyError for an error raised by a client that reads the proxy environment only while the gateway trusts it, none when gateway.trust_env is off

func TruthyToken

func TruthyToken(value string) any

Whether the lower cased value is a truthy token, surrounding blanks not stripped

func TruthyValue

func TruthyValue(value string) any

Shared truthy coercion of an env string, blanks stripped

func TryAcquireFileLock

func TryAcquireFileLock(f *os.File) bool

Takes the exclusive non blocking lock of an open file, false when another holder has it

func TurnReferences

func TurnReferences(ctx context.Context, runner ContextRefsRunner, event *MessageEvent, source *SessionSource, sessionKey, text string) (*string, error)

Turn text with the model read references expanded, nil when refused with the local refusal left on the event

func TypingMetadataForTurn

func TypingMetadataForTurn(adapter any, chatID string, anchor *string, metadata map[string]any) map[string]any

Typing metadata of a turn for the platform adapters, the adapter hook taking the turn anchor

func URLSafetyEnv

func URLSafetyEnv(ctx context.Context) *tools.Env

URL safety env of the readonly config for adapters outside the package

func UTF16Len

func UTF16Len(s string) int

UTF-16 code units of the text, astral characters counting two as Telegram measures them

func UnattendedTurn

func UnattendedTurn(ctx context.Context) bool

True while the bound turn is a finite one that auto approves because nobody can answer a prompt

func UnauthorizedActionNoticeFor

func UnauthorizedActionNoticeFor(ctx context.Context, platform Platform) string

Localized private bot refusal naming the platform, resolved per refusal so the language follows the config

func UnbindCronOwner

func UnbindCronOwner(a *SessionAuthority)

Drops the authority's cron owner binding of its store home when it still holds it

func UncountedRuntimeWork

func UncountedRuntimeWork(runner any) int

Claims absent from the ordinary agent map across the served authorities, pre bootstrap managed turns included

func UndoHint

func UndoHint(mgr *tools.CheckpointManager, cwd string, since float64, known bool) *tuigateway.UndoRollbackHint

Wire hint of an undone span that started at a known time, nil when the span changed no file

func UndoSpanStart

func UndoSpanStart(target any, kept []map[string]any) (float64, bool)

Start of an undone span, the undone user message's stamp or the newest kept message's when that is later, false when neither is known

func UnknownPlatformError

func UnknownPlatformError(ctx context.Context, platformName string) string

Error naming an unregistered plugin platform with its install command when it left core

func UnmanagedGatewayCommand

func UnmanagedGatewayCommand(h string, idleExit, force bool) ([]string, error)

Argv of an unmanaged gateway run for a resolved home, a root home pinned to the default profile

func UnreadableLockRecovery

func UnreadableLockRecovery(path string) (string, bool)

Recovery a client prints for a gateway.lock it cannot open read only, false when it can

func UnservedProfiles

func UnservedProfiles(ctx context.Context) ([]string, error)

Named profiles a standalone gateway of this home leaves without a bot

func UpdateHelperMain

func UpdateHelperMain(ctx context.Context, args []string, stderr io.Writer) int

Runs the command with both outputs in the output file, then writes its exit code through a temp file and rename

func UpdateRoomLinkStatus

func UpdateRoomLinkStatus(ctx context.Context, dbPath, roomID, memberID, status string, now *float64) (bool, error)

Persists a non secret route health classification

func UpdateScopeHomes

func UpdateScopeHomes(ctx context.Context) map[string]bool

UpdateScopeHomes lists the resolved homes the running update owns, the invoking home, the root and its profiles

func Upload

func Upload(ctx context.Context, service *CanonicalHostedRoomService, actor Principal, params map[string]any) (map[string]any, error)

Retains a composer file for an actor allowed to submit to the room

func UpsertRemoteRunReceipt

func UpsertRemoteRunReceipt(ctx context.Context, dbPath string, record map[string]any, now *float64) error

Durably binds one logical peer task attempt to its remote run handle

func UpsertRoomLinkRecord

func UpsertRoomLinkRecord(ctx context.Context, dbPath string, record map[string]any, maxLinks int) error

Atomically inserts or replaces one private RoomLink record

func UsageFrame

func UsageFrame(stats *jsonutil.Object) *jsonutil.Object

Session usage event payload carrying the TUI usage view and the cumulative counters in one frame

func UserEventID

func UserEventID(clientEventID any) (string, error)

Server owned user event id a client retry key maps to

func UserSystemdEnv

func UserSystemdEnv() []string

Process env with the user manager values over it, the env a service command child is spawned with

func UserSystemdUnitDir

func UserSystemdUnitDir(ctx context.Context) string

XDG_CONFIG_HOME/systemd/user with the account home .config as the default base

func ValidateAttachmentManifest

func ValidateAttachmentManifest(value any) ([]map[string]any, error)

Validated attachment manifest of one message

func ValidateCoalesceConfig

func ValidateCoalesceConfig(routeName string, route *jsonutil.Object) error

Startup check of a route coalesce block, the ValueError a malformed block raises

func ValidateMediaDeliveryPath

func ValidateMediaDeliveryPath(ctx context.Context, path, sessionKey string) (string, error)

Safe absolute file path for native media delivery, empty when the denylist or strict policy refuses it

func ValidateRoomLinkURL

func ValidateRoomLinkURL(value any) (string, string, error)

RoomLink endpoint and its transport, plaintext HTTP accepted only toward loopback

func ValidateTaskInput

func ValidateTaskInput(value any) (map[string]any, error)

Bounded immutable input references of a compacting policy task

func ValidateUserPayload

func ValidateUserPayload(value any) (map[string]any, error)

Validated and normalized message.user payload

func ValidateWorkRecord

func ValidateWorkRecord(value any) (map[string]any, error)

Validates one passive work record completely, returning it unchanged

func ValuesEqual

func ValuesEqual(a, b any) bool

Python equality of two decoded JSON values

func VerifyGatewayArgv

func VerifyGatewayArgv(argv []string, h string, wrapped bool) error

Accepts only an installer form of gateway run for home with its quiet and supervisor flags

func VerifyHome

func VerifyHome(h, configured string) error

Accepts the same home, refuses a sibling profile as a mismatch and another root as foreign

func VerifyLaunchdLoaded

func VerifyLaunchdLoaded(output, h string, uid int, username string) error

Binds launchctl print output of a loaded job to this account, home and gateway argv

func VerifyLaunchdPlist

func VerifyLaunchdPlist(definition map[string]any, label, h string) error

Binds an installed launchd plist to its label, this home and a gateway argv

func VerifyRoomGrant

func VerifyRoomGrant(secret []byte, token string, dispatch *HostedMemberDispatch, permission string, now *float64) (*jsonutil.Object, error)

Grant payload once it verifies against the exact recipient dispatch coordinates

func VerifySystemd

func VerifySystemd(props map[string]string, managerEnv, h string, system bool) error

Binds loaded systemd properties and the manager environment to this account, home and gateway argv

func VerifyWindowsTask

func VerifyWindowsTask(definition, h, account, sid string) error

Binds a scheduled task definition to this account, the vendor launcher, this home and a gateway argv

func VideoMimeToExt

func VideoMimeToExt() map[string]string

MIME to extension inverse of the supported video table

func ViewerDriven

func ViewerDriven(authority *SessionAuthority, sessionID, registry string) bool

Whether a local viewer drives the session's goal and loop judging, or its heartbeat ticks for viewer_heartbeat

func VisionImageNotes

func VisionImageNotes(ctx context.Context, env *tools.Env, userText string, imagePaths []string) string

Text with a vision description and the cached path of each attached image prepended

func WSClientReason

func WSClientReason(ws BoundaryPeer, state *ListenerState) string

Rejection token for the WebSocket peer address under the listener state, empty when allowed

func WSHostReason

func WSHostReason(ws BoundaryPeer, state *ListenerState) string

Host mismatch token of a WebSocket handshake under the listener state, empty when allowed

func WSMethodRefusedWhileDraining

func WSMethodRefusedWhileDraining(runner DrainRunner, method string) bool

True when an interactive WebSocket verb is refused because the runner is draining

func WaitForAPIServerPortFree

func WaitForAPIServerPortFree(ctx context.Context, timeout float64) (bool, error)

Waits until the api server port is free for the next gateway

func WaitForGatewayExit

func WaitForGatewayExit(timeout float64) bool

Waits for the recorded gateway pid to exit without force killing it, true once gone

func WaitForGatewayExitForcing

func WaitForGatewayExitForcing(timeout, forceAfter float64) bool

Waits for every gateway process to exit, force killing survivors after forceAfter seconds

func WaitForGatewayReadyIn

func WaitForGatewayReadyIn(ctx context.Context, timeoutS float64, allProfiles bool, profileHome string, pidFilter func([]int) ([]int, error)) ([]int, error)

Polls for a gateway that stays visible through the confirmation window, empty at the timeout

func WaitForLaunchdServicePID

func WaitForLaunchdServicePID(ctx context.Context, label string, oldPid int, haveOld bool, timeout float64, domain string) (bool, error)

True once the label runs a pid other than the old one within the timeout

func WantsServiceInstall

func WantsServiceInstall(ctx context.Context, interactive, install bool) (bool, error)

Whether setup may install the service, asking once on an interactive terminal and recording a decline

func WarnLegacyLaunchers

func WarnLegacyLaunchers(ctx context.Context) (bool, error)

Names every stray pre suffix launcher with the uninstall remedy, true when any exist

func WebhookIsUsableSecret

func WebhookIsUsableSecret(secret any) bool

Whether a secret is a string with at least one non space character

func WhenReturnedInputsDurable

func WhenReturnedInputsDurable(ctx context.Context, adapter PlatformAdapter, persist func(ctx context.Context) error) error

Runs persist once every input a serial reader returned on is committed, the newest deferred persist winning

func WindowsInstall

func WindowsInstall(ctx context.Context, o WindowsInstallOptions) error

Installs the gateway as a Windows Scheduled Task with the Startup folder fallback, always reconciling

func WindowsIsInstalled

func WindowsIsInstalled(ctx context.Context) (bool, error)

Whether the Scheduled Task or the Startup fallback is present

func WindowsIsTaskRegistered

func WindowsIsTaskRegistered(ctx context.Context) (bool, error)

Whether schtasks answers the gateway task query with exit code zero

func WindowsPipeName

func WindowsPipeName(home string) (string, error)

Per home named pipe path of the Windows control transport

func WindowsRestart

func WindowsRestart(ctx context.Context) error

Stops then starts once the old gateway is gone, failing loudly when either side does not converge

func WindowsStart

func WindowsStart(ctx context.Context) error

Starts the gateway through the detached launch, offering login persistence when none is installed

func WindowsStartupEntryInstalled

func WindowsStartupEntryInstalled(ctx context.Context) (bool, error)

Whether a Startup folder entry of the gateway, current or legacy, exists

func WindowsStatus

func WindowsStatus(ctx context.Context, w io.Writer, deep bool) error

Prints the Windows scheduled task or login item state, the gateway process and on deep each liveness probe

func WindowsStop

func WindowsStop(ctx context.Context) error

Stops the gateway with the planned stop marker, then schtasks End, then a bounded kill of known pids

func WindowsUninstall

func WindowsUninstall(ctx context.Context) error

Removes the Scheduled Task, the Startup folder entries, the task scripts and the legacy launchers

func WithActivePolicy

func WithActivePolicy(ctx context.Context, policy ActiveLaunchPolicy) context.Context

Binds the launch policy of the turn executing in ctx

func WithBusyAccepted

func WithBusyAccepted(ctx context.Context, hook func(context.Context) error) context.Context

Context whose mid run dispatch awaits hook once it accepts a command and before it acts

func WithListingRead

func WithListingRead(ctx context.Context) context.Context

Context marking a listing read that must not push back a restored conversation's retirement

func WithLiveSource

func WithLiveSource(ctx context.Context, source *SessionSource) context.Context

Binds the live inbound source of a call dispatched before its session is stored

func WizardPrintln

func WizardPrintln(text string)

Prints a line on the setup console like a bare print in a platform wizard

func WorkEncode

func WorkEncode(value any) (string, error)

Sorted compact JSON that refuses NaN, the evidence canonical form

func WorkRosterDigest

func WorkRosterDigest(members any) (string, error)

SHA-256 of the canonical member roster

func WorkerDisplayKwargs

func WorkerDisplayKwargs(ctx context.Context) map[string]any

Persistence keyword arguments of the managed child single admitted turn

func WorkerKanbanContext

func WorkerKanbanContext(frame *jsonutil.Object) (any, error)

Decoded kanban context of a bootstrap frame's policy, nil for a chat turn

func WorkerPolicyScope

func WorkerPolicyScope(ctx context.Context, policy *LocalSessionPolicy, body func(ctx context.Context) error) error

Runs body under the frozen policy with no owner authority, the managed worker child's scope

func WorkerRoute

func WorkerRoute(ctx context.Context, policy *LocalSessionPolicy, construct map[string]any) (map[string]any, error)

Child side api key, base url and api mode overrides of the worker's agent, resolved as the in process turn resolves its route

func WorkerTurnScope

func WorkerTurnScope(ctx context.Context, frame *jsonutil.Object) (context.Context, error)

Child side of turn_v1 binding the finite flags, the route's yolo and the committed surface and display

func WorkerWorkspace

func WorkerWorkspace(ctx context.Context, env *tools.Env, frame *jsonutil.Object, body func(taskID string) error) error

Runs body in the session workspace with its session vars bound, the session id as task id when scoped

func WorkspaceUnavailableResult

func WorkspaceUnavailableResult(ctx context.Context, policy *LocalSessionPolicy) *jsonutil.Object

Failed never run result of a session whose working folder is gone

func WriteLoopHeartbeat

func WriteLoopHeartbeat(ctx context.Context, pid *int, startTime *float64, h string, extra *jsonutil.Object) string

Rewrites the loop heartbeat file atomically with pid, time, memory and extra fields, returning its path

func WriteMultiplexFlag

func WriteMultiplexFlag(ctx context.Context, defaultHome string, value bool) error

Sets gateway.multiplex_profiles in the default profile config through the guarded config writer

func WritePeerFileChunk

func WritePeerFileChunk(ctx context.Context, dbPath, scope, fileID string, offset int64, data []byte) (map[string]any, error)

Writes one chunk at the offset this gateway reached, the whole file checked against its digest and type

func WritePidFile

func WritePidFile(ctx context.Context) error

Writes this process pid record with O_EXCL so a racing gateway sees fs.ErrExist

func WritePlannedRestartMarker

func WritePlannedRestartMarker(ctx context.Context, viaService, detached bool)

Records that the gateway is going down for a restart, never failing the restart itself

func WritePlannedStopMarker

func WritePlannedStopMarker(ctx context.Context, targetPid int) bool

Records that targetPid is being stopped intentionally so its exit is clean

func WriteRuntimeStatus

func WriteRuntimeStatus(ctx context.Context, u RuntimeStatusUpdate, reloadExisting bool, waitTimeout *time.Duration) (bool, error)

Durably persists one status update for CLI callers, waiting at most waitTimeout when it is set

func WriteStartAttestation

func WriteStartAttestation(ctx context.Context, pids []int, via string)

Records the gateway pids a start vouched for so a later death is reported

func WriteTakeoverMarker

func WriteTakeoverMarker(ctx context.Context, targetPid int, targetHome string, targetStartTime any, startTimeGiven bool) bool

Records that targetPid is being replaced by this process, the target start time captured unless given

func WriteWindowsTaskScript

func WriteWindowsTaskScript(ctx context.Context) (string, error)

Rewrites the installed Windows gateway launcher scripts in place, the script path

Types

type A2AForward

type A2AForward struct {
	Agent     string
	Tenant    string
	Peer      string
	ContextID string
	InputID   string
	Text      string
}

One forwarded A2A turn the owner admits under the exact peer conversation identity

type APIAdmission

type APIAdmission struct {
	Authority *SessionAuthority
	Ref       SessionRef
	Row       *jsonutil.Object
}

One committed API admission with its authority, session and ledger row

func AdmitAPITurn

func AdmitAPITurn(ctx context.Context, adapter APITurnAdapter, turn *APITurn) (*APIAdmission, error)

Admits one API turn inline, each write run by the caller

func AdmitAPITurnAsync

func AdmitAPITurnAsync(ctx context.Context, adapter APITurnAdapter, turn *APITurn) (*APIAdmission, error)

Admits one API turn with every SQLite write off the caller, in admission order

func (*APIAdmission) Admitted

func (x *APIAdmission) Admitted() *APIAdmission

Admission itself, the first three members of any admission tuple a step sequence returns

type APIAgentRuntimeResolver

type APIAgentRuntimeResolver interface {
	ResolveRuntimeAgentKwargs(ctx context.Context) (map[string]any, error)
	ResolveRuntimeAgentKwargsForProvider(ctx context.Context, providerName, targetModel string) (map[string]any, error)
	LoadReasoningConfig(ctx context.Context, model string) map[string]any
	LoadFallbackModel(ctx context.Context) []map[string]any
	ReapGatewayTurnProcesses(ctx context.Context, taskID string, baseline map[string]bool, source string, isStillCurrent func() bool) int
}

Gateway run module functions an API server agent is built and reaped with

var APIAgentRuntime APIAgentRuntimeResolver

Resolver the gateway runner package installs at init

type APIItemCounterKey

type APIItemCounterKey = apiItemCounterKey

Item counter key of a durable response

type APIObserver

type APIObserver struct {
	Callbacks map[string]APIObserverCallback
}

Sinks one API request registered for its admission's execution, keyed by callback name

type APIObserverCallback

type APIObserverCallback func(args []any, kwargs map[string]any) error

One request owned API sink, args positional and kwargs by name as the Python callback receives them

type APIRunAdmitter

type APIRunAdmitter interface {
	RunAdmission(ctx context.Context, runID string) (*SessionAuthority, *jsonutil.Object, error)
}

API adapter whose run ids resolve to canonical API admissions

type APIServerRunner

type APIServerRunner interface {
	AuthorizationAdapter(ctx context.Context, platform Platform, profile *string) PlatformAdapter
	SessionModelOverrideFor(ctx context.Context, sessionKey string) map[string]any
}

Runner surface the API server adapter reads, the authorization adapter map and the session model override

type APITurn

type APITurn struct {
	UserMessage              any
	ConversationHistory      any
	SessionID                string
	GatewaySessionKey        string
	BindDeclaredConversation bool
	Settings                 map[string]any
	HistoryFromSession       bool
	RunOwnerScope            any
	TurnAuthor               any
	ResumeUnansweredTurn     bool
	RelayMetadata            any
	RequestID                string
	ActiveRunID              string
	WalkedFrom               string
	Observers                map[string]APIObserverCallback
	ApprovalNotifyCallback   func(data map[string]any) error
	ApprovalSessionKey       string
}

Keyword arguments of one API turn, its settings holding exactly the setting keys the caller passed

type APITurnAdapter

type APITurnAdapter interface {
	PlatformAdapter
	EnsureSessionDB(ctx context.Context) (*state.SessionDB, error)
	ConfiguredModelRoute(alias any) map[string]any
	BindRunAdmissionAlias(key, admissionID string)
	ReleaseRunAdmissionAlias(key, admissionID string)
}

API adapter surface the admission of a canonical API turn reads

type AccessLog

type AccessLog struct {
	Disabled bool
	Logger   *slog.Logger
}

Access log options of a bound listener, the aiohttp.access logger unless disabled or replaced

type ActiveLaunchPolicy

type ActiveLaunchPolicy interface {
	PolicyPlatform() string
	PolicyCwd() string
}

Frozen launch policy a local session turn runs under, gateway/session_policy.py LocalSessionPolicy

func ActivePolicy

func ActivePolicy(ctx context.Context) ActiveLaunchPolicy

Launch policy of the turn executing in ctx, nil for standalone serve and messaging turns

type AdapterClass

type AdapterClass struct {
	Name   string
	New    func(ctx context.Context, config *PlatformConfig) (PlatformAdapter, error)
	Traits AdapterTraits
}

Adapter class a platform module exports, its constructor and the class attributes it declares

func BuiltinAdapterImport

func BuiltinAdapterImport(module, adapterName, requirement string) (*AdapterClass, any, error)

Adapter class and requirements probe of a gateway platform module, the import or attribute error when absent

type AdapterFactory

type AdapterFactory func(ctx context.Context, cfg *PlatformConfig) (any, error)

Builds an adapter for a platform config

type AdapterMap

type AdapterMap = orderedutil.Map[Platform, PlatformAdapter]

Live adapters of one profile keyed by platform

type AdapterTask

type AdapterTask = adapterTask

Adapter owned goroutine handle the platform adapters hold and cancel

func CurrentAdapterTask

func CurrentAdapterTask(ctx context.Context) *AdapterTask

Task running under the context for the platform adapters, nil outside an adapter task

func SpawnAdapterTask

func SpawnAdapterTask(ctx context.Context, fn func(ctx context.Context) error) *AdapterTask

Starts fn as an adapter task for the platform adapters, detached from the caller's cancellation

type AdapterTraits

type AdapterTraits struct {
	SupportsCodeBlocks           bool
	SupportsStatusText           bool
	SupportsAsyncDelivery        bool
	SplitsLongMessages           bool
	TypedCommandPrefix           string
	SupportsInchannelContinuable bool
	InteractiveResume            bool
	ServesProfilePrefix          bool
	RequiresEditFinalize         bool
	SupportsMessageEditing       bool
	SupportsNativeStreaming      bool
	SerialReceiveLoop            bool
	MaxMessageLength             int
	AckEmoji                     string
	OkEmoji                      string
	FailEmoji                    string
	RuntimeStatusPlatformKey     string
	EACodeOpen                   string
	EACodeClose                  string
	EADeadlinePrefix             string
	EACmdBudget                  int
	EAReasonBudget               int
	EAActionStyles               map[string]string
}

AdapterTraits are the class attributes a concrete adapter overrides by assignment in its constructor

func DefaultAdapterTraits

func DefaultAdapterTraits() AdapterTraits

Class attribute defaults of the base adapter

type AdmissionQueuedError

type AdmissionQueuedError struct{ *state.RuntimeStoreError }

Owner retired while this API admission was still queued, its input committed for the next owner

func (*AdmissionQueuedError) Error

func (e *AdmissionQueuedError) Error() string

func (*AdmissionQueuedError) ErrorKind

func (e *AdmissionQueuedError) ErrorKind() string

Kind label of the error

func (*AdmissionQueuedError) Unwrap

func (e *AdmissionQueuedError) Unwrap() error

type AdmissionReceipt

type AdmissionReceipt struct {
	AdmissionID         string
	Ref                 SessionRef
	Sequence            int64
	Status              string
	Outcome             *string
	AuthorityEpoch      int64
	ExecutionGeneration *int64
}

Durable admission state of one submitted input, nil outcome and generation when absent

func AdmitProcessNotice

func AdmitProcessNotice(ctx context.Context, runner AuthorityRunner, a *SessionAuthority, adapter PlatformAdapter, event *MessageEvent, evt map[string]any) (AdmissionReceipt, error)

Process notice admission, for the runner's watch notification injection

func AdmitProducer

func AdmitProducer(ctx context.Context, adapter PlatformAdapter, event *MessageEvent) (*AdmissionReceipt, error)

Commits a producer delivery, nil when a plugin skipped or consumed it or the chat's in flight work answered it

type AgentCacheBounds

type AgentCacheBounds struct {
	MaxSize             *int
	IdleTTLSecs         *float64
	MemoryHighMB        *int
	MaxEvictionsPerPass int
	ProtectRecent       int
}

Operator agent cache bounds, unset size and ttl keeping the runner defaults and a nil budget turning pressure off

func ResolveAgentCacheBounds

func ResolveAgentCacheBounds(ctx context.Context) AgentCacheBounds

Agent cache bounds of the profile in ctx, a non positive size, lifetime or sweep size leaving the runner's own

type AllowlistSnapshotAdapter

type AllowlistSnapshotAdapter interface {
	PurgeAllowlistSnapshots(keep func(entry string) bool)
}

Adapter keeping allowlist snapshots, a purge keeping only the entries the predicate accepts

type AppendEventInput

type AppendEventInput struct {
	RoomID, EventID, Kind, Actor, Payload any
	AuthorityGatewayID, AuthorityEpoch    any
	Now                                   *float64
	ExpectedLatestSeq                     any
	ControlReserve                        bool
}

One event append, ExpectedLatestSeq nil for no cursor check

type AsyncSessionStore

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

Async boundary for the synchronous thread safe SessionStore, each call running on the caller goroutine

func NewAsyncSessionStore

func NewAsyncSessionStore(store *SessionStore) *AsyncSessionStore

Facade over store

func (*AsyncSessionStore) Store

func (a *AsyncSessionStore) Store() *SessionStore

Wrapped store whose methods the facade offloads

type AttachmentCommit

type AttachmentCommit struct {
	RoomID             any
	EventID            any
	Manifest           any
	RecipientMemberIDs []string
	ViewerAccess       bool
	RetentionSeconds   *float64
	HoldUntilEvent     bool
}

Commit options of one message manifest

type AttachmentConflictError

type AttachmentConflictError struct{ *AttachmentError }

Idempotency or ownership key reused with different content

func (*AttachmentConflictError) Unwrap

func (e *AttachmentConflictError) Unwrap() error

type AttachmentData

type AttachmentData struct {
	Attachment map[string]any
	Data       []byte
}

Verified canonical bytes plus safe attachment metadata

type AttachmentError

type AttachmentError struct{ Msg string }

A hosted room attachment contract failure, a ValueError

func (*AttachmentError) Error

func (e *AttachmentError) Error() string

type AttachmentIntegrityError

type AttachmentIntegrityError struct{ *AttachmentError }

Canonical blob bytes no longer match their durable metadata

func (*AttachmentIntegrityError) Unwrap

func (e *AttachmentIntegrityError) Unwrap() error

type AttachmentNotFoundError

type AttachmentNotFoundError struct{ *AttachmentError }

Attachment id unknown, expired or unavailable to the caller

func (*AttachmentNotFoundError) Unwrap

func (e *AttachmentNotFoundError) Unwrap() error

type AttachmentQuotaError

type AttachmentQuotaError struct{ *AttachmentError }

Bounded room or gateway quota would be exceeded

func (*AttachmentQuotaError) Unwrap

func (e *AttachmentQuotaError) Unwrap() error

type AttachmentStoreOptions

type AttachmentStoreOptions struct {
	Root              string
	Clock             func() float64
	RoomQuotaBytes    *int64
	GatewayQuotaBytes *int64
	RoomQuotaCount    *int64
	GatewayQuotaCount *int64
}

Store options, zero quotas meaning the module defaults

type AttachmentsUnsupportedError

type AttachmentsUnsupportedError struct{ Msg string }

Member route that cannot carry the turn's files, refused before submit

func (*AttachmentsUnsupportedError) Error

type AttrAdapter

type AttrAdapter interface {
	AdapterAttr(name string) any
}

Adapter exposing its Python attributes by name, the getattr reads of the runner's credential and listener claims

type AudioFormat

type AudioFormat struct {
	SampleRate  int
	Channels    int
	SampleWidth int
}

Declared PCM format of a streaming TTS session, raw little endian samples at this shape

func DefaultAudioFormat

func DefaultAudioFormat() AudioFormat

Mono 24 kHz int16 PCM, the dataclass defaults

type AuthorityConflictError

type AuthorityConflictError struct{ *HostedRoomError }

Successful authority claim of a hosted room peer reservation that a newer authority outranks

func (*AuthorityConflictError) Reason

func (e *AuthorityConflictError) Reason() string

Stable wire reason of a stale authority

func (*AuthorityConflictError) Unwrap

func (e *AuthorityConflictError) Unwrap() error

type AuthorityConnection

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

Authenticated projection of one client socket onto the authority, its principal, subscriptions and sibling routes

func NewAuthorityConnection

func NewAuthorityConnection(a *SessionAuthority, transport tuihost.Transport, identity map[string]any, operator bool) (*AuthorityConnection, error)

Connection of a verified identity, its capabilities emptied for a missing user or a foreign instance

func (*AuthorityConnection) Actor

func (c *AuthorityConnection) Actor() Principal

Principal the connection acts as

func (*AuthorityConnection) AwaitsProfileStart

func (c *AuthorityConnection) AwaitsProfileStart(ctx context.Context, request map[string]any, held []string) (string, <-chan struct{}, bool, error)

Hold of a host scoped frame naming a starting or held profile, its started signal nil for a held key

func (*AuthorityConnection) Close

func (c *AuthorityConnection) Close(ctx context.Context) error

Tears the connection down, orphaning its subscriptions and arming the close of sessions it kept in the background

func (*AuthorityConnection) ConnectionAuthority

func (c *AuthorityConnection) ConnectionAuthority() *SessionAuthority

Authority the connection acts on, for the finite turn checks

func (*AuthorityConnection) CronActor

func (c *AuthorityConnection) CronActor() *Principal

Principal the connection acts as, for the cron RPCs

func (*AuthorityConnection) CronAuthority

func (c *AuthorityConnection) CronAuthority() *SessionAuthority

Authority the connection acts on, for the cron RPCs

func (*AuthorityConnection) Dispatch

func (c *AuthorityConnection) Dispatch(ctx context.Context, request *jsonutil.Object) (*jsonutil.Object, error)

One WS frame of a viewer answered on the owner, session_controls.py dispatch L282

func (*AuthorityConnection) HostScoped

func (c *AuthorityConnection) HostScoped() bool

Whether the grant acts for every profile this process serves

func (*AuthorityConnection) NativeOwner

func (c *AuthorityConnection) NativeOwner() bool

Whether the connection is the native bootstrap owner

func (*AuthorityConnection) Operator

func (c *AuthorityConnection) Operator() bool

Whether a verified transport gate granted the operator capability

func (*AuthorityConnection) SessionAuthority

func (c *AuthorityConnection) SessionAuthority() *SessionAuthority

Authority the connection acts on

func (*AuthorityConnection) Submission

func (c *AuthorityConnection) Submission(ctx context.Context, ref SessionRef, params *jsonutil.Object) (Submission, error)

Submission parser of the queued row verbs

type AuthorityHistoryError

type AuthorityHistoryError struct{ Msg string }

A recorded authority sequence that cannot explain the current room

func (*AuthorityHistoryError) Error

func (e *AuthorityHistoryError) Error() string

type AuthorityRegistryRunner

type AuthorityRegistryRunner = authorityRegistryRunner

Runner keeping the registry of every profile authority it serves

type AuthorityRunner

type AuthorityRunner interface {
	DrainRunner
	SessionStore() *SessionStore
	AdapterForSource(ctx context.Context, source *SessionSource) (PlatformAdapter, error)
	MultiplexProfiles() bool
}

Runner surface the session authority reads, the gateway runner's drain state, session store and adapters

func ActiveAPIRunner

func ActiveAPIRunner() AuthorityRunner

Runner the session API mount serves, nil when none is mounted

type AuthoritySpan

type AuthoritySpan struct {
	GatewayID string
	Epoch     int64
	FromSeq   int64
}

One authority epoch and the first sequence it owns

func AuthorityAtSequence

func AuthorityAtSequence(history []AuthoritySpan, seq int64) (AuthoritySpan, error)

Span that owns sequence seq

func ValidateAuthorityHistory

func ValidateAuthorityHistory(value any, gatewayID string, epoch int64) ([]AuthoritySpan, error)

Contextual epochs of a recorded history ending at the current owner, never a grant of control

func (AuthoritySpan) AsMapping

func (s AuthoritySpan) AsMapping() map[string]any

Wire mapping of the span

type AuthorizationAdapterRunner

type AuthorizationAdapterRunner interface {
	AuthorizationAdapter(ctx context.Context, platform Platform, profile *string) PlatformAdapter
}

Profile aware fail closed adapter lookup of a runner that never borrows the default bot, gateway/authz_mixin.py _authorization_adapter

type AuthorizationCheck

type AuthorizationCheck func(userID string, chatType, chatID *string, opts AuthorizationOpts) (any, error)

AuthorizationCheck answers whether a sender is allowed, any non boolean result reads as unknown

type AuthorizationOpts

type AuthorizationOpts struct {
	IsBot    bool
	ThreadID *string
}

AuthorizationOpts carries the keyword only arguments forwarded to the runner's authorization check

type BasePlatformAdapter

type BasePlatformAdapter struct {
	Config        *PlatformConfig
	Platform      Platform
	GatewayRunner any
	Traits        AdapterTraits
	// contains filtered or unexported fields
}

BasePlatformAdapter is the shared instance state and default behaviour every platform adapter embeds

func NewBasePlatformAdapter

func NewBasePlatformAdapter(config *PlatformConfig, platform Platform, self PlatformAdapter) *BasePlatformAdapter

Base adapter bound to the concrete adapter that embeds it, with the constructor defaults

func (*BasePlatformAdapter) AbortStreamingTTS

func (b *BasePlatformAdapter) AbortStreamingTTS(ctx context.Context, handle *StreamingTTSHandle, errText *string) error

Aborts the audio stream idempotently, nothing by default

func (*BasePlatformAdapter) AcquirePlatformLock

func (b *BasePlatformAdapter) AcquirePlatformLock(ctx context.Context, scope, identity, resourceDesc string) (bool, error)

Takes the adapter's scoped lock, an armed replace takes over a live holder once, a conflict is a retryable fatal error

func (*BasePlatformAdapter) ActiveSessionEvent

func (b *BasePlatformAdapter) ActiveSessionEvent(sessionKey string) *InterruptEvent

Interrupt event of a session's active processing guard, nil when the session holds none

func (*BasePlatformAdapter) ApplyTopicRecovery

func (b *BasePlatformAdapter) ApplyTopicRecovery(event *MessageEvent)

Applies the runner topic recovery hook to the event source

func (*BasePlatformAdapter) AuthorizationIsUpstream

func (b *BasePlatformAdapter) AuthorizationIsUpstream() bool

Whether a trusted upstream already authorized inbound, relay adapters only

func (*BasePlatformAdapter) AutoTTSChats

func (b *BasePlatformAdapter) AutoTTSChats(enabled bool) map[string]struct{}

Chat set of the adapter's auto TTS overrides, the enabled set or the disabled set, mutated in place

func (*BasePlatformAdapter) AwaitPendingTextBatches

func (b *BasePlatformAdapter) AwaitPendingTextBatches(ctx context.Context, timeout time.Duration) (timedOut bool)

Waits up to timeout for the pending flush tasks, cancels the stragglers, then clears both batch maps

func (*BasePlatformAdapter) BackgroundTasks

func (b *BasePlatformAdapter) BackgroundTasks() []*AdapterTask

Tracked detached tasks that have not finished yet

func (*BasePlatformAdapter) Base

The base itself, the embedded value every adapter exposes

func (*BasePlatformAdapter) BeginStreamingTTS

func (b *BasePlatformAdapter) BeginStreamingTTS(ctx context.Context, chatID string, format AudioFormat, metadata map[string]any) (*StreamingTTSHandle, error)

Opens a streaming audio session, nil declines so the whole file fallback runs

func (*BasePlatformAdapter) BuildSource

func (b *BasePlatformAdapter) BuildSource(ctx context.Context, chatID string, f SourceFields) *SessionSource

Session source of an inbound chat stamped with the routed profile and this adapter as its transport

func (*BasePlatformAdapter) BusySessionHandler

func (b *BasePlatformAdapter) BusySessionHandler() BusySessionHandler

Installed handler for messages arriving during active sessions

func (*BasePlatformAdapter) BusyTextPolicy

func (b *BasePlatformAdapter) BusyTextPolicy() (mode string, debounceSeconds, hardCapSeconds float64)

Busy follow up mode, debounce window and hard cap the adapter applies

func (*BasePlatformAdapter) CancelBackgroundTasks

func (b *BasePlatformAdapter) CancelBackgroundTasks(ctx context.Context)

Cancels in flight background tasks within five seconds per round, flushes pending input to disk and clears all state

func (*BasePlatformAdapter) CancelSessionProcessing

func (b *BasePlatformAdapter) CancelSessionProcessing(ctx context.Context, sessionKey string, releaseGuard, discardPending bool)

Cancels in flight processing of one session within five seconds, keeping the guard or pending input on request

func (*BasePlatformAdapter) ClearTextBatches

func (b *BasePlatformAdapter) ClearTextBatches()

Clears every buffered text batch and its flush task slot

func (*BasePlatformAdapter) CoerceFloatExtra

func (b *BasePlatformAdapter) CoerceFloatExtra(key string, def, minValue float64, maxValue *float64) float64

Float from config extra clamped to the bounds, a non finite, negative or unparseable value reading as the default

func (*BasePlatformAdapter) ConfigureTextBatchDelays

func (b *BasePlatformAdapter) ConfigureTextBatchDelays()

Reads the text batch delay and split delay from config extra at the shared cadence

func (*BasePlatformAdapter) CreateHandoffThread

func (b *BasePlatformAdapter) CreateHandoffThread(ctx context.Context, parentChatID, name string) (string, bool, error)

Thread created for a handoff, false when the platform has none and the watcher uses the parent chat

func (*BasePlatformAdapter) DeleteMessage

func (b *BasePlatformAdapter) DeleteMessage(ctx context.Context, chatID, messageID string) (bool, error)

Deletion of a sent message, false on platforms without a deletion API so callers leave it

func (*BasePlatformAdapter) DetachedFatalTaskCount

func (b *BasePlatformAdapter) DetachedFatalTaskCount() int

Fatal error handler runs still in flight

func (*BasePlatformAdapter) DispatchTextBatch

func (b *BasePlatformAdapter) DispatchTextBatch(ctx context.Context, event *MessageEvent) error

Hands a flushed batch to the message pipeline

func (*BasePlatformAdapter) DropUnresolved

func (b *BasePlatformAdapter) DropUnresolved(ctx context.Context, event *MessageEvent) bool

Whether an event whose routing identity cannot resolve was dropped

func (*BasePlatformAdapter) EAActionLabelsFor

func (b *BasePlatformAdapter) EAActionLabelsFor(ctx context.Context) map[string]string

Button labels of the approval tiers, adapters with their own wording override it

func (*BasePlatformAdapter) EADeadlineLine

func (b *BasePlatformAdapter) EADeadlineLine(ctx context.Context) string

Deadline line with the configured approvals timeout after the deadline prefix

func (*BasePlatformAdapter) EAEscape

func (b *BasePlatformAdapter) EAEscape(text string) string

Escape hook for the command preview and reason, unchanged by default

func (*BasePlatformAdapter) EAFit

func (b *BasePlatformAdapter) EAFit(text string, budget int, suffix string, escape func(string) string) string

Raw prefix that fits budget once escaped and measured in platform length units

func (*BasePlatformAdapter) EAHeader

func (b *BasePlatformAdapter) EAHeader(ctx context.Context) string

Warning sign, the localized header and a blank line

func (*BasePlatformAdapter) EAReasonLabel

func (b *BasePlatformAdapter) EAReasonLabel(ctx context.Context) string

Localized reason label followed by a colon and a space

func (*BasePlatformAdapter) EASmartDenyLine

func (b *BasePlatformAdapter) EASmartDenyLine(ctx context.Context) string

Blank line then the localized smart deny sentence

func (*BasePlatformAdapter) EditMessage

func (b *BasePlatformAdapter) EditMessage(ctx context.Context, chatID, messageID, content string, finalize bool) (SendResult, error)

Edit of a sent message, unsupported by default so callers send anew

func (*BasePlatformAdapter) EmitMediaWarning

func (b *BasePlatformAdapter) EmitMediaWarning(ctx context.Context, chatID, notice, caption, replyTo string, metadata, shownMetadata map[string]any) (SendResult, error)

Media diagnostic that keeps the caption, a failed result carrying the notice when the warning is hidden

func (*BasePlatformAdapter) EmitWarning

func (b *BasePlatformAdapter) EmitWarning(ctx context.Context, chatID, content, replyTo string, metadata map[string]any, logicalPlatform Platform) (*SendResult, error)

Classified channel diagnostic sent in the caller's scope, nil when the warning policy hides it

func (*BasePlatformAdapter) EnforcesOwnAccessPolicy

func (b *BasePlatformAdapter) EnforcesOwnAccessPolicy() bool

Whether the adapter enforces its own config driven access policy at intake

func (*BasePlatformAdapter) EnqueueTextEvent

func (b *BasePlatformAdapter) EnqueueTextEvent(ctx context.Context, event *MessageEvent) error

Buffers a text event into the pending batch of its key and restarts the flush timer

func (*BasePlatformAdapter) EventSessionKey

func (b *BasePlatformAdapter) EventSessionKey(ctx context.Context, event *MessageEvent) (string, error)

Adapter level session key of an event, profile namespaced like the agent run

func (*BasePlatformAdapter) ExecApprovalActions

func (b *BasePlatformAdapter) ExecApprovalActions(ctx context.Context, allowPermanent, allowSession, smartDenied bool) []ExecApprovalAction

Approval button rows, a smart deny offering neither the session nor the permanent tier

func (*BasePlatformAdapter) ExecApprovalCmdBudget

func (b *BasePlatformAdapter) ExecApprovalCmdBudget(ctx context.Context, description string, smartDenied bool) int

Characters of command preview that fit, platforms with a hard message cap compute it

func (*BasePlatformAdapter) FatalErrorCode

func (b *BasePlatformAdapter) FatalErrorCode() *string

Recorded fatal error code

func (*BasePlatformAdapter) FatalErrorMessage

func (b *BasePlatformAdapter) FatalErrorMessage() *string

Recorded fatal error message

func (*BasePlatformAdapter) FatalErrorRetryable

func (b *BasePlatformAdapter) FatalErrorRetryable() bool

Whether the recorded fatal error may be retried

func (*BasePlatformAdapter) FinishStreamingTTS

func (b *BasePlatformAdapter) FinishStreamingTTS(ctx context.Context, handle *StreamingTTSHandle, interrupted bool) error

Signals the normal end of the audio stream, nothing by default

func (*BasePlatformAdapter) FlushTextBatch

func (b *BasePlatformAdapter) FlushTextBatch(ctx context.Context, key string) error

Waits the quiet period then dispatches the batch unless a newer flush owns the key, the dispatch shielded from cancel

func (*BasePlatformAdapter) FlushTextBatchNow

func (b *BasePlatformAdapter) FlushTextBatchNow(ctx context.Context, key string) error

Dispatches the pending batch of a key at once without the quiet period

func (*BasePlatformAdapter) FormatExecApproval

func (b *BasePlatformAdapter) FormatExecApproval(ctx context.Context, command string, description *string, smartDenied bool) string

Header, fenced truncated command, flagged reason and deadline line, plus the smart deny line

func (*BasePlatformAdapter) FormatMessage

func (b *BasePlatformAdapter) FormatMessage(content string) string

Content formatted for this platform, unchanged by default

func (*BasePlatformAdapter) FormatToolEvent

func (b *BasePlatformAdapter) FormatToolEvent(ctx context.Context, event StreamEvent, mode string, previewMaxLen int) (string, bool)

Rendered chrome of a tool call chunk, false when the event is not one

func (*BasePlatformAdapter) FormatToolPreview

func (b *BasePlatformAdapter) FormatToolPreview(preview tools.ToolPreview) string

Platform native formatting of a compact tool preview, the plain text by default

func (*BasePlatformAdapter) GetPendingMessage

func (b *BasePlatformAdapter) GetPendingMessage(sessionKey string) *MessageEvent

Takes and clears the pending follow up of a session

func (*BasePlatformAdapter) HandleMessage

func (b *BasePlatformAdapter) HandleMessage(ctx context.Context, event *MessageEvent) error

Admits an incoming message, spawning its background turn or routing it as a busy follow up

func (*BasePlatformAdapter) HandleMessageWhileActive

func (b *BasePlatformAdapter) HandleMessageWhileActive(ctx context.Context, event *MessageEvent, sessionKey string) error

Routes a message arriving while the session is busy, the adapter busy path without the stale lock heal

func (*BasePlatformAdapter) HasActiveSession

func (b *BasePlatformAdapter) HasActiveSession(sessionKey string) bool

Whether the session currently holds an active processing guard

func (*BasePlatformAdapter) HasAuthorizationCheck

func (b *BasePlatformAdapter) HasAuthorizationCheck() bool

Whether the runner installed a platform bound authorization callback

func (*BasePlatformAdapter) HasFatalError

func (b *BasePlatformAdapter) HasFatalError() bool

Whether a fatal error is recorded

func (*BasePlatformAdapter) HasPendingInterrupt

func (b *BasePlatformAdapter) HasPendingInterrupt(sessionKey string) bool

Whether the session's active guard has been signalled to interrupt

func (*BasePlatformAdapter) HumanDelayRangeMs

func (b *BasePlatformAdapter) HumanDelayRangeMs() *[2]int

Installed human delay range in milliseconds, nil keeping the configured env policy

func (*BasePlatformAdapter) InstallSessionGuard

func (b *BasePlatformAdapter) InstallSessionGuard(sessionKey string, guard *InterruptEvent)

Installs the guard as the session's active marker with no processing task behind it

func (*BasePlatformAdapter) InterruptSessionActivity

func (b *BasePlatformAdapter) InterruptSessionActivity(ctx context.Context, sessionKey, chatID string, metadata map[string]any)

Signals the active session loop to stop and clears typing at once

func (*BasePlatformAdapter) IsConnected

func (b *BasePlatformAdapter) IsConnected() bool

Whether the adapter is connected

func (*BasePlatformAdapter) IsSenderAuthorized

func (b *BasePlatformAdapter) IsSenderAuthorized(userID string, chatType, chatID *string, opts AuthorizationOpts) *bool

True or false from the registered check, nil when no check exists, it fails or answers a non boolean

func (*BasePlatformAdapter) KeepTyping

func (b *BasePlatformAdapter) KeepTyping(ctx context.Context, chatID string, interval float64, metadata map[string]any, stopEvent *InterruptEvent)

Refreshes the typing indicator every interval until cancelled or stopped, skipping paused chats

func (*BasePlatformAdapter) MarkConnected

func (b *BasePlatformAdapter) MarkConnected(ctx context.Context, listenerBase string)

Marks the adapter running, clears the fatal error and publishes connected or degraded status

func (*BasePlatformAdapter) MarkDegraded

func (b *BasePlatformAdapter) MarkDegraded(ctx context.Context)

Publishes the connected but degraded runtime status while polling recovers

func (*BasePlatformAdapter) MarkDisconnected

func (b *BasePlatformAdapter) MarkDisconnected(ctx context.Context)

Marks the adapter stopped and publishes disconnected unless a fatal error stands

func (*BasePlatformAdapter) MaxMessageLengthForChat

func (b *BasePlatformAdapter) MaxMessageLengthForChat(chatID string) (int, error)

Per chat maximum length, the adapter's declared cap or 4096

func (*BasePlatformAdapter) MediaDeliveryScope

func (b *BasePlatformAdapter) MediaDeliveryScope(ctx context.Context, source *SessionSource) (context.Context, func())

Delivery scope of the source's routed profile and its release

func (*BasePlatformAdapter) MergePendingMessage

func (b *BasePlatformAdapter) MergePendingMessage(sessionKey string, event *MessageEvent, mergeText bool)

Merges the event into the session's pending slot under the adapter lock, text joined when mergeText

func (*BasePlatformAdapter) MessageHandler

func (b *BasePlatformAdapter) MessageHandler() MessageHandler

Installed incoming message handler

func (*BasePlatformAdapter) MessageHandlerOwner

func (b *BasePlatformAdapter) MessageHandlerOwner() any

Owner the message handler was bound from, the runner of a bound method and nil for a closure

func (*BasePlatformAdapter) MessageLenFn

func (b *BasePlatformAdapter) MessageLenFn() func(string) int

Length measure of message size, code points unless the platform counts differently

func (*BasePlatformAdapter) MessageLenFnForChat

func (b *BasePlatformAdapter) MessageLenFnForChat(chatID string) (func(string) int, error)

Per chat length measure, the adapter wide one unless a relay overrides it

func (*BasePlatformAdapter) Name

func (b *BasePlatformAdapter) Name() string

Title cased platform value

func (*BasePlatformAdapter) NotifyFatalError

func (b *BasePlatformAdapter) NotifyFatalError(ctx context.Context) error

Runs the fatal error handler shielded from the caller's cancellation, a detached run logs its own failure

func (*BasePlatformAdapter) OnProcessingComplete

func (b *BasePlatformAdapter) OnProcessingComplete(ctx context.Context, event *MessageEvent, outcome ProcessingOutcome) error

Swaps the in progress reaction for the outcome one when the adapter opts in, cancelled stays unreacted

func (*BasePlatformAdapter) OnProcessingStart

func (b *BasePlatformAdapter) OnProcessingStart(ctx context.Context, event *MessageEvent) error

Hook run when background processing begins, nothing by default

func (*BasePlatformAdapter) OwnerProfile

func (b *BasePlatformAdapter) OwnerProfile() string

Owning multiplex profile, empty on the primary

func (*BasePlatformAdapter) PauseTypingForChat

func (b *BasePlatformAdapter) PauseTypingForChat(chatID string)

Pauses the typing refresh for a chat while an approval waits

func (*BasePlatformAdapter) PeekPendingMessage

func (b *BasePlatformAdapter) PeekPendingMessage(sessionKey string) (*MessageEvent, bool)

Event parked in a session's pending slot without taking it, and whether the slot holds a key

func (*BasePlatformAdapter) PendingMessagesSnapshot

func (b *BasePlatformAdapter) PendingMessagesSnapshot() map[string]*MessageEvent

Copy of the per session pending message slots

func (*BasePlatformAdapter) PendingTextBatch

func (b *BasePlatformAdapter) PendingTextBatch(key string) *MessageEvent

Pending text batch of a key

func (*BasePlatformAdapter) PendingTextBatchTaskCount

func (b *BasePlatformAdapter) PendingTextBatchTaskCount() int

Number of flush tasks still owning a key

func (*BasePlatformAdapter) PlatformEventHandler

func (b *BasePlatformAdapter) PlatformEventHandler() PlatformEventHandler

Installed platform event boundary, nil failing closed

func (*BasePlatformAdapter) PlatformLockIdentity

func (b *BasePlatformAdapter) PlatformLockIdentity() string

Identity of the held platform lock, empty when none is held

func (*BasePlatformAdapter) PlatformValue

func (b *BasePlatformAdapter) PlatformValue() string

Platform value the plugin platform actions route their verbs by

func (*BasePlatformAdapter) PlayTTS

func (b *BasePlatformAdapter) PlayTTS(ctx context.Context, chatID, audioPath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)

Plays auto TTS audio as a voice message, adapters with invisible playback override it

func (*BasePlatformAdapter) PopPendingMessage

func (b *BasePlatformAdapter) PopPendingMessage(sessionKey string) (*MessageEvent, bool)

Takes the event parked in a session's pending slot, false when the slot holds no key

func (*BasePlatformAdapter) PopPostDeliveryCallback

func (b *BasePlatformAdapter) PopPostDeliveryCallback(sessionKey string, generation *int) PostDeliveryCallback

Pops the deferred callback, requiring the generation to own the slot when one is given

func (*BasePlatformAdapter) PopTextBatch

func (b *BasePlatformAdapter) PopTextBatch(key string) *MessageEvent

Removes and returns the pending batch of a key

func (*BasePlatformAdapter) PrefersFreshFinalStreaming

func (b *BasePlatformAdapter) PrefersFreshFinalStreaming(content string, metadata map[string]any, chatID string) bool

Whether the stream consumer finalizes with a fresh message instead of editing the preview

func (*BasePlatformAdapter) PrepareTTSText

func (b *BasePlatformAdapter) PrepareTTSText(ctx context.Context, text string) string

Spoken script of chat markdown, a markup strip when the normalizer fails

func (*BasePlatformAdapter) ProcessMessageBackground

func (b *BasePlatformAdapter) ProcessMessageBackground(ctx context.Context, event *MessageEvent, sessionKey string) (retErr error)

Processes one inbound turn end to end, delivering the reply and handing any queued follow up to a drain task

func (*BasePlatformAdapter) ProfileName

func (b *BasePlatformAdapter) ProfileName() string

Multiplex profile recorded on a secondary adapter, empty on the primary

func (*BasePlatformAdapter) ReactionHandler

func (b *BasePlatformAdapter) ReactionHandler() ReactionHandler

Installed reaction handler

func (*BasePlatformAdapter) RegisterPostDeliveryCallback

func (b *BasePlatformAdapter) RegisterPostDeliveryCallback(sessionKey string, callback PostDeliveryCallback, generation *int)

Registers a callback after the main response, chaining same generation slots and dropping stale ones

func (*BasePlatformAdapter) ReleasePlatformLock

func (b *BasePlatformAdapter) ReleasePlatformLock()

Releases the scoped lock the adapter acquired

func (*BasePlatformAdapter) ReleaseTextBatchTask

func (b *BasePlatformAdapter) ReleaseTextBatchTask(key string, task *AdapterTask)

Drops the key's flush task slot when task still owns it

func (*BasePlatformAdapter) RenderMessageEvent

func (b *BasePlatformAdapter) RenderMessageEvent(event StreamEvent, sink StreamSink)

Renders a message chunk, intermediate stop or commentary onto the stream sink

func (*BasePlatformAdapter) RescheduleTextBatchFlush

func (b *BasePlatformAdapter) RescheduleTextBatchFlush(ctx context.Context, key string)

Cancels the unfinished flush task of key and starts a fresh delayed flush in its slot

func (*BasePlatformAdapter) ResumePartialSend

func (b *BasePlatformAdapter) ResumePartialSend(ctx context.Context, chatID string, result SendResult, replyTo string, metadata map[string]any) (*SendResult, error)

Delivers only the undelivered remainder of a split payload, nil when the adapter cannot resume

func (*BasePlatformAdapter) ResumeTypingForChat

func (b *BasePlatformAdapter) ResumeTypingForChat(chatID string)

Resumes the typing refresh for a chat once the approval resolves

func (*BasePlatformAdapter) RewirePluginHandlers

func (b *BasePlatformAdapter) RewirePluginHandlers(ctx context.Context)

Wires the handlers of plugins loaded after connect, nothing before connect wired once

func (*BasePlatformAdapter) RunLoopTurn

func (b *BasePlatformAdapter) RunLoopTurn(ctx context.Context, fn func(ctx context.Context) error) error

Runs fn as one uninterrupted stretch of adapter code, what a coroutine runs between two awaits

func (*BasePlatformAdapter) ScheduleEphemeralDelete

func (b *BasePlatformAdapter) ScheduleEphemeralDelete(ctx context.Context, chatID, messageID string, ttlSeconds int)

Deletes a sent message after its ttl in the background, failures logged at debug

func (*BasePlatformAdapter) Self

The concrete adapter bound at construction, the base itself when none was bound

func (*BasePlatformAdapter) SendAnimation

func (b *BasePlatformAdapter) SendAnimation(ctx context.Context, chatID, animationURL, caption, replyTo string, metadata map[string]any) (SendResult, error)

Animated image by URL, the image send where the platform has no native animation

func (*BasePlatformAdapter) SendClarify

func (b *BasePlatformAdapter) SendClarify(ctx context.Context, chatID, question string, choices []string, clarifyID, sessionKey string, metadata map[string]any) (SendResult, error)

Clarify prompt as a numbered list awaiting a typed reply, or the bare question when open ended

func (*BasePlatformAdapter) SendDocument

func (b *BasePlatformAdapter) SendDocument(ctx context.Context, chatID, filePath, caption, fileName, replyTo string, metadata, extra map[string]any) (SendResult, error)

Native document send, a friendly failure notice naming only the caller's file name by default

func (*BasePlatformAdapter) SendDraft

func (b *BasePlatformAdapter) SendDraft(ctx context.Context, chatID string, draftID int, content string, metadata map[string]any) (SendResult, error)

Streaming draft preview, an error for adapters that never override it

func (*BasePlatformAdapter) SendExecApproval

func (b *BasePlatformAdapter) SendExecApproval(ctx context.Context, chatID, command, sessionKey string, description *string, metadata map[string]any, allowPermanent, allowSession, smartDenied bool, requestID *string) (SendResult, error)

Interactive approval prompt rendered natively by the adapter, not supported without buttons

func (*BasePlatformAdapter) SendExecApprovalPrompt

func (b *BasePlatformAdapter) SendExecApprovalPrompt(ctx context.Context, prompt *ExecApprovalPrompt) (SendResult, error)

Native button rendering of an approval prompt, not supported on the base without buttons

func (*BasePlatformAdapter) SendFinalLedgered

func (b *BasePlatformAdapter) SendFinalLedgered(ctx context.Context, event *MessageEvent, sessionKey, textContent string, metadata map[string]any, replyTo *string, isEphemeral bool) (SendResult, PlatformAdapter, error)

Ledger bracket of a final text on the current transport, returning the result with the adapter that sent it

func (*BasePlatformAdapter) SendImage

func (b *BasePlatformAdapter) SendImage(ctx context.Context, chatID, imageURL, caption, replyTo string, metadata map[string]any) (SendResult, error)

Image by URL, the caption and URL as text where the platform has no native image send

func (*BasePlatformAdapter) SendImageFile

func (b *BasePlatformAdapter) SendImageFile(ctx context.Context, chatID, imagePath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)

Local image file, a friendly failure notice where the platform has no native file send

func (*BasePlatformAdapter) SendMultipleImages

func (b *BasePlatformAdapter) SendMultipleImages(ctx context.Context, chatID string, images []ImageRef, metadata map[string]any, humanDelay float64) (SendResult, error)

Sends each image through its native sender, success when at least one was delivered

func (*BasePlatformAdapter) SendPathDegraded

func (b *BasePlatformAdapter) SendPathDegraded() bool

Whether connect succeeded but delivery is not yet confirmed

func (*BasePlatformAdapter) SendPlainFallback

func (b *BasePlatformAdapter) SendPlainFallback(ctx context.Context, chatID, content, replyTo string, metadata map[string]any) (SendResult, error)

Last resort send after a permanent failure, the content as plain text under the fallback banner

func (*BasePlatformAdapter) SendPrivateNotice

func (b *BasePlatformAdapter) SendPrivateNotice(ctx context.Context, chatID string, userID *string, content, replyTo string, metadata map[string]any) (SendResult, error)

Notice for one user, a plain send unless the platform has a private channel

func (*BasePlatformAdapter) SendRetryIsFinal

func (b *BasePlatformAdapter) SendRetryIsFinal(result SendResult) bool

Whether a failed send must be returned as is, never retried nor sent as plain text, false by default

func (*BasePlatformAdapter) SendSlashConfirm

func (b *BasePlatformAdapter) SendSlashConfirm(ctx context.Context, chatID, title, message, sessionKey, confirmID string, metadata map[string]any) (SendResult, error)

Three option slash command confirmation, not supported so the gateway text fallback runs

func (*BasePlatformAdapter) SendTyping

func (b *BasePlatformAdapter) SendTyping(ctx context.Context, chatID string, metadata map[string]any) error

Typing indicator, nothing where the platform has none

func (*BasePlatformAdapter) SendVideo

func (b *BasePlatformAdapter) SendVideo(ctx context.Context, chatID, videoPath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)

Native inline video, a friendly failure notice by default

func (*BasePlatformAdapter) SendVoice

func (b *BasePlatformAdapter) SendVoice(ctx context.Context, chatID, audioPath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)

Native voice message, a friendly failure notice by default

func (*BasePlatformAdapter) SendWithRetry

func (b *BasePlatformAdapter) SendWithRetry(ctx context.Context, chatID, content, replyTo string, metadata map[string]any, maxRetries int, baseDelay float64) (SendResult, error)

Sends with exponential backoff on transient errors, plain text fallback on permanent ones, a notice after exhaustion

func (*BasePlatformAdapter) SessionStore

func (b *BasePlatformAdapter) SessionStore() any

Installed session store

func (*BasePlatformAdapter) SessionTaskDone

func (b *BasePlatformAdapter) SessionTaskDone(sessionKey string) <-chan struct{}

Done signal of the session task the adapter runs for a key, nil when none runs

func (*BasePlatformAdapter) SetAuthorizationCheck

func (b *BasePlatformAdapter) SetAuthorizationCheck(check AuthorizationCheck)

Registers the runner's sender authorization check

func (*BasePlatformAdapter) SetAutoTTSDefault

func (b *BasePlatformAdapter) SetAutoTTSDefault(on bool)

Sets whether replies are spoken by default when a chat holds no override

func (*BasePlatformAdapter) SetBoundMessageHandler

func (b *BasePlatformAdapter) SetBoundMessageHandler(owner any, handler MessageHandler)

Installs a handler bound to its owner so the shared runtime check can read the owner's session authority

func (*BasePlatformAdapter) SetBusySessionHandler

func (b *BasePlatformAdapter) SetBusySessionHandler(handler BusySessionHandler)

Installs the handler for messages arriving during active sessions

func (*BasePlatformAdapter) SetBusyTextMode

func (b *BasePlatformAdapter) SetBusyTextMode(mode string)

Installs the busy follow up mode alone, keeping the debounce window and hard cap

func (*BasePlatformAdapter) SetBusyTextPolicy

func (b *BasePlatformAdapter) SetBusyTextPolicy(mode string, debounceSeconds, hardCapSeconds float64)

Installs the busy follow up policy the runner configures, mode plus debounce window and hard cap

func (*BasePlatformAdapter) SetBusyTextTiming

func (b *BasePlatformAdapter) SetBusyTextTiming(debounceSeconds, hardCapSeconds float64)

Installs the busy follow up debounce window and hard cap, keeping the mode

func (*BasePlatformAdapter) SetFatalError

func (b *BasePlatformAdapter) SetFatalError(ctx context.Context, code, message string, retryable bool)

Stops the adapter, records the fatal error and publishes fatal status

func (*BasePlatformAdapter) SetFatalErrorHandler

func (b *BasePlatformAdapter) SetFatalErrorHandler(handler FatalErrorHandler)

Installs the runner callback for fatal errors

func (*BasePlatformAdapter) SetHumanDelayRangeMs

func (b *BasePlatformAdapter) SetHumanDelayRangeMs(r *[2]int)

Installs the human delay range in milliseconds, nil keeping the configured env policy

func (*BasePlatformAdapter) SetMessageHandler

func (b *BasePlatformAdapter) SetMessageHandler(handler MessageHandler)

Installs the incoming message handler

func (*BasePlatformAdapter) SetOwnerProfile

func (b *BasePlatformAdapter) SetOwnerProfile(profileName string)

Declares the owning multiplex profile, default and blank names reading as the primary

func (*BasePlatformAdapter) SetPendingMessage

func (b *BasePlatformAdapter) SetPendingMessage(sessionKey string, event *MessageEvent)

Parks an event in a session's pending slot for the adapter's post command drain

func (*BasePlatformAdapter) SetPendingTextBatch

func (b *BasePlatformAdapter) SetPendingTextBatch(key string, event *MessageEvent)

Stores event as the pending text batch of key

func (*BasePlatformAdapter) SetPlatformEventHandler

func (b *BasePlatformAdapter) SetPlatformEventHandler(handler PlatformEventHandler)

Installs the gateway owned normalized platform event boundary

func (*BasePlatformAdapter) SetPlatformLockTakeoverAllowed

func (b *BasePlatformAdapter) SetPlatformLockTakeoverAllowed(allowed bool)

Arms or disarms the one explicit replace takeover of the initial connect

func (*BasePlatformAdapter) SetProfileName

func (b *BasePlatformAdapter) SetProfileName(name string)

Records the multiplex profile a secondary adapter serves so prune paths namespace topic bindings

func (*BasePlatformAdapter) SetReactionHandler

func (b *BasePlatformAdapter) SetReactionHandler(handler ReactionHandler)

Installs the handler for platform native emoji reaction events

func (*BasePlatformAdapter) SetRunning

func (b *BasePlatformAdapter) SetRunning(on bool)

Assigns the running flag directly the way adapters assign their running attribute

func (*BasePlatformAdapter) SetSessionStore

func (b *BasePlatformAdapter) SetSessionStore(store any)

Installs the session store adapters consult for active thread sessions

func (*BasePlatformAdapter) SetSharedListenerProfile

func (b *BasePlatformAdapter) SetSharedListenerProfile(profile string)

Routes a secondary's port binding adapter through the default profile's shared listener

func (*BasePlatformAdapter) SetStatusText

func (b *BasePlatformAdapter) SetStatusText(chatID string, text string)

Stores or clears the live working state phrase the next typing refresh renders

func (*BasePlatformAdapter) SetTextBatchDelays

func (b *BasePlatformAdapter) SetTextBatchDelays(delay, split float64)

Overrides the text batch delay and split delay with adapter specific values

func (*BasePlatformAdapter) SetTopicRecoveryFn

func (b *BasePlatformAdapter) SetTopicRecoveryFn(fn TopicRecoveryFn)

Installs or clears the thread id recovery hook run before session keying

func (*BasePlatformAdapter) SharedIngress

func (b *BasePlatformAdapter) SharedIngress() *SharedIngress

Shared listener publication of the adapter, nil while it binds its own port or has not connected

func (*BasePlatformAdapter) SharedListenerProfile

func (b *BasePlatformAdapter) SharedListenerProfile() string

Profile served through the shared listener, empty when the adapter binds its own port

func (*BasePlatformAdapter) SourceSessionKey

func (b *BasePlatformAdapter) SourceSessionKey(ctx context.Context, source *SessionSource) (string, error)

Session key of a source after its identity is pinned

func (*BasePlatformAdapter) StartSessionProcessing

func (b *BasePlatformAdapter) StartSessionProcessing(ctx context.Context, event *MessageEvent, sessionKey string, interruptEvent *InterruptEvent) bool

Spawns the background processing task under a freshly installed session guard

func (*BasePlatformAdapter) StatusText

func (b *BasePlatformAdapter) StatusText(chatID string) (string, bool)

Live working state phrase of a chat

func (*BasePlatformAdapter) StopTyping

func (b *BasePlatformAdapter) StopTyping(ctx context.Context, chatID string, metadata map[string]any) error

Clears the typing indicator, nothing where the platform has none

func (*BasePlatformAdapter) StreamingOverflowLimit

func (b *BasePlatformAdapter) StreamingOverflowLimit() (int, bool)

Single message length the stream consumer may accumulate, false meaning the declared maximum

func (*BasePlatformAdapter) SupportsDraftStreaming

func (b *BasePlatformAdapter) SupportsDraftStreaming(chatType string, metadata map[string]any, chatID string) bool

Whether native streaming draft updates work for this chat

func (*BasePlatformAdapter) SupportsExecApprovalButtons

func (b *BasePlatformAdapter) SupportsExecApprovalButtons() bool

Whether the adapter overrides the prompt hook with native approval buttons

func (*BasePlatformAdapter) SupportsStreamingTTS

func (b *BasePlatformAdapter) SupportsStreamingTTS(chatID string, format AudioFormat) bool

Whether the adapter accepts streaming PCM for the chat, never by default

func (*BasePlatformAdapter) TextBatchDelayFor

func (b *BasePlatformAdapter) TextBatchDelayFor(pending *MessageEvent) float64

Quiet period before a pending batch dispatches, near split chunks waiting longer

func (*BasePlatformAdapter) TextBatchDelays

func (b *BasePlatformAdapter) TextBatchDelays() (float64, float64)

Configured text batch delay and split delay in seconds

func (*BasePlatformAdapter) TextBatchEvents

func (b *BasePlatformAdapter) TextBatchEvents() []*MessageEvent

Every buffered text batch event

func (*BasePlatformAdapter) TextBatchKey

func (b *BasePlatformAdapter) TextBatchKey(ctx context.Context, event *MessageEvent) (string, error)

Session scoped key for text batching

func (*BasePlatformAdapter) TextBatchTask

func (b *BasePlatformAdapter) TextBatchTask(key string) *AdapterTask

Flush task currently owning a text batch key, nil when none

func (*BasePlatformAdapter) TextBatchTasks

func (b *BasePlatformAdapter) TextBatchTasks() []*AdapterTask

Every text batch flush task still registered

func (*BasePlatformAdapter) ToolsetsForSource

func (b *BasePlatformAdapter) ToolsetsForSource(source *SessionSource) ([]string, bool)

Per source toolset override replacing the platform toolsets, false for the default

func (*BasePlatformAdapter) TrackBackgroundTask

func (b *BasePlatformAdapter) TrackBackgroundTask(task *AdapterTask)

Tracks a detached task for cancellation at shutdown until it finishes, for callers outside this package

func (*BasePlatformAdapter) UnwrapEphemeral

func (b *BasePlatformAdapter) UnwrapEphemeral(ctx context.Context, response any) (any, int)

Text and seconds to live of a handler reply, an ephemeral reply unwrapped under the adapter's ttl rules

func (*BasePlatformAdapter) WaitTextBatches

func (b *BasePlatformAdapter) WaitTextBatches(ctx context.Context) error

Waits until every pending flush task has finished or the context ends

func (*BasePlatformAdapter) WarningNotificationsEnabled

func (b *BasePlatformAdapter) WarningNotificationsEnabled(ctx context.Context, logicalPlatform Platform, chatID string, metadata map[string]any) bool

Warning presentation policy of the logical platform, the adapter platform when none is given

func (*BasePlatformAdapter) WarningText

func (b *BasePlatformAdapter) WarningText(ctx context.Context, visible string, hidden *string, logicalPlatform Platform, chatID string, metadata map[string]any) *string

Diagnostic variant when warnings show, else the requested remainder

func (*BasePlatformAdapter) WirePluginHandlers

func (b *BasePlatformAdapter) WirePluginHandlers(ctx context.Context, native any)

Runs every plugin native handler factory not yet wired on this native client, each isolated

func (*BasePlatformAdapter) WriteRuntimeStatusSafe

func (b *BasePlatformAdapter) WriteRuntimeStatusSafe(ctx context.Context, statusContext string, fields map[string]any)

Writes the runtime status of the adapter, failures logged and never raised

func (*BasePlatformAdapter) WriteStreamingTTS

func (b *BasePlatformAdapter) WriteStreamingTTS(ctx context.Context, handle *StreamingTTSHandle, chunk []byte) error

Writes one PCM chunk to the outbound audio track, nothing by default

type BotLoopGuard

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

Per conversation sliding window of admitted bot messages with a cooldown once the budget trips

func NewBotLoopGuard

func NewBotLoopGuard(settings func(ctx context.Context) BotLoopGuardSettings, clock func() float64) *BotLoopGuard

Guard reading its settings per call under the caller's scope, the live config and monotonic time when nil

func (*BotLoopGuard) Admit

func (g *BotLoopGuard) Admit(ctx context.Context, conversation any) (bool, string)

Counts one admitted bot message, its verdict and the disabled, ok, tripped or cooldown state

func (*BotLoopGuard) Blocked

func (g *BotLoopGuard) Blocked(ctx context.Context, conversation any) bool

Whether the conversation is cooling down, a pure read

func (*BotLoopGuard) TrackedConversations

func (g *BotLoopGuard) TrackedConversations() int

Number of conversations holding a window

type BotLoopGuardSettings

type BotLoopGuardSettings struct {
	Enabled         bool
	MaxEvents       int
	WindowSeconds   float64
	CooldownSeconds float64
}

Budget of bot authored inbound messages per conversation and the cooldown once it trips

func DefaultBotLoopGuardSettings

func DefaultBotLoopGuardSettings() BotLoopGuardSettings

Bot loop guard budget the registry gives by default

func LoadBotLoopGuardSettings

func LoadBotLoopGuardSettings(ctx context.Context) BotLoopGuardSettings

Bot loop guard budget of the profile in ctx

type BoundTurn

type BoundTurn struct {
	TaskID, Platform, Message string
	// contains filtered or unexported fields
}

Turn a bound command handler builds for one session, held for the surface to submit

func (*BoundTurn) SubmitUserTurn

func (t *BoundTurn) SubmitUserTurn(ctx context.Context, message string) error

Holds the one turn the handler built, refusing a second

func (*BoundTurn) TurnSession

func (t *BoundTurn) TurnSession() (string, string)

Task id and platform of the session the turn is built for

type BoundaryPeer

type BoundaryPeer interface {
	BoundaryHeader(name string) string
	BoundaryClient() (string, bool)
}

Handshake view the WebSocket boundary checks read, its headers and peer address

type BuiltinAdapterSpec

type BuiltinAdapterSpec struct {
	Module      string
	AdapterName string
	Requirement string
	Warning     string
}

Module, adapter class, requirements probe and the warning logged when the probe fails

type BundledEnvRows

type BundledEnvRows struct {
	Overrides         []EnvStep
	EnableCredentials []string
	Authz             map[string]any
}

Env declarations a bundled platform's gateway_env module makes under one prefix

type BusySessionHandler

type BusySessionHandler func(ctx context.Context, event *MessageEvent, sessionKey string) (bool, error)

BusySessionHandler takes a message arriving while its session is busy and reports whether it handled it

type CLIOutputFns

type CLIOutputFns struct {
	Prompt       func(question, def string, password bool) string
	PromptYesNo  func(ctx context.Context, question string, def bool) bool
	PrintHeader  func(text string)
	PrintInfo    func(text string)
	PrintSuccess func(text string)
	PrintWarning func(text string)
	PrintError   func(text string)
}

The functions platform wizards resolve at call time, a table tests replace like the patched module

type CSVSpec

type CSVSpec struct{ Key, Raw string }

Key and raw text pair of a csv extra

type CachedMedia

type CachedMedia struct {
	Path        string
	MediaType   string
	Kind        string
	DisplayName string
}

One cached attachment with its host path, recorded MIME, kind and transcript name

func CacheMediaBytes

func CacheMediaBytes(ctx context.Context, data []byte, filename, mimeType, defaultKind string) (*CachedMedia, error)

Classifies attachment bytes by extension, MIME and default kind and caches them, nil only for an image failing validation

func CacheMediaBytesAsync

func CacheMediaBytesAsync(ctx context.Context, data []byte, filename, mimeType, defaultKind string) (*CachedMedia, error)

Classifies and caches attachment bytes without blocking the caller

func (*CachedMedia) ContextNote

func (m *CachedMedia) ContextNote(ctx context.Context) string

Transcript line pointing the agent at the file through the sandbox visible path of the active scope

type CallbackLoop

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

Single goroutine callback loop the gateway runner runs its work on, the asyncio event loop of the runner

func NewCallbackLoop

func NewCallbackLoop() *CallbackLoop

func (*CallbackLoop) CallExceptionHandler

func (l *CallbackLoop) CallExceptionHandler(c LoopExceptionContext)

Routes a failure to the installed handler, the default one when none is installed

func (*CallbackLoop) CallLater

func (l *CallbackLoop) CallLater(delay time.Duration, fn func()) (LoopTimer, error)

Runs fn on the loop after delay, ErrLoopClosed once the loop is closed

func (*CallbackLoop) CallSoonThreadsafe

func (l *CallbackLoop) CallSoonThreadsafe(fn func()) error

Queues fn to run on the loop goroutine from any goroutine, ErrLoopClosed once the loop is closed

func (*CallbackLoop) Close

func (l *CallbackLoop) Close()

Closes the loop so later scheduling fails and Run returns, pending callbacks dropped

func (*CallbackLoop) DefaultExceptionHandler

func (l *CallbackLoop) DefaultExceptionHandler(c LoopExceptionContext)

Logs the failure at error level the way asyncio's default handler reports it

func (*CallbackLoop) ExceptionHandler

func (l *CallbackLoop) ExceptionHandler() LoopExceptionHandler

Handler installed on the loop, nil while the default one reports failures

func (*CallbackLoop) IsClosed

func (l *CallbackLoop) IsClosed() bool

Whether the loop was closed so scheduling onto it fails

func (*CallbackLoop) IsRunning

func (l *CallbackLoop) IsRunning() bool

Whether Run is executing the loop on some goroutine, false before it starts and after it returns

func (*CallbackLoop) Run

func (l *CallbackLoop) Run(ctx context.Context) error

Runs queued callbacks one at a time on the calling goroutine until ctx ends or the loop closes

func (*CallbackLoop) Schedule

func (l *CallbackLoop) Schedule(fn func()) bool

Starts fn from the loop goroutine as its own task beside the loop callbacks, false once the loop is closed

func (*CallbackLoop) SetExceptionHandler

func (l *CallbackLoop) SetExceptionHandler(handler LoopExceptionHandler)

Installs handler for every later failure on the loop, nil restoring the default

type CalledProcessError

type CalledProcessError struct {
	Cmd            []string
	ReturnCode     int
	Stdout, Stderr string
}

Raised by a checked systemctl run that exits non zero

func (*CalledProcessError) Error

func (e *CalledProcessError) Error() string

type CanonicalHostedRoomService

type CanonicalHostedRoomService struct {
	*HostedRoomService
	Authority *SessionAuthority
	// contains filtered or unexported fields
}

Authority bound hosted room service whose member turns run through the canonical session FIFO

func EnsureHostedService

func EnsureHostedService(ctx context.Context, runner any) (*CanonicalHostedRoomService, error)

Prepares every served transport before readiness releases a coordinator and returns the active service

func NewCanonicalHostedRoomService

func NewCanonicalHostedRoomService(ctx context.Context, authority *SessionAuthority, loop context.Context) (*CanonicalHostedRoomService, error)

Hosted room service over the authority's own room store, producers dispatching onto the owner loop

func (*CanonicalHostedRoomService) Approve

func (c *CanonicalHostedRoomService) Approve(ctx context.Context, sessionID, requestID, choice string) (map[string]any, error)

Resolves an approval through the local producer that owns the session, refused when none does

func (*CanonicalHostedRoomService) Attest

func (c *CanonicalHostedRoomService) Attest(ctx context.Context, selector map[string]any, operation string, params map[string]any) (map[string]any, error)

Source owner attestation of a hosted operation against current membership and durable task state

func (*CanonicalHostedRoomService) AuthorizeRoom

func (c *CanonicalHostedRoomService) AuthorizeRoom(ctx context.Context, actorSubject, roomID any, create bool, conn state.SQLiteConn) (bool, error)

Checks, or with create claims, room ownership, inside the caller's transaction when a conn is given

func (*CanonicalHostedRoomService) BeginReadyImport

func (c *CanonicalHostedRoomService) BeginReadyImport() bool

Marks the ready import begun, false when it began before

func (*CanonicalHostedRoomService) Bindings

Room bindings of the base service whose rooms this authority owns

func (*CanonicalHostedRoomService) CheckAdmission

func (c *CanonicalHostedRoomService) CheckAdmission(ctx context.Context, ref SessionRef, row *jsonutil.Object) error

Reconstructs the private producer of a queued hosted admission from durable task state before its claim

func (*CanonicalHostedRoomService) DiscardRoomTask

func (c *CanonicalHostedRoomService) DiscardRoomTask(roomID string, memberID, taskID, executionGeneration any) (map[string]any, error)

Cancels a deferred turn or a peer member's uncertain one, else settles an indeterminate local attempt receipt first

func (*CanonicalHostedRoomService) LocalProfiles

func (c *CanonicalHostedRoomService) LocalProfiles() ([]string, error)

Profile names a new group may seat, in roster order

func (*CanonicalHostedRoomService) MarkTransportInstalled

func (c *CanonicalHostedRoomService) MarkTransportInstalled()

Records the private transport routes of this service as installed

func (*CanonicalHostedRoomService) ProfileHomes

func (c *CanonicalHostedRoomService) ProfileHomes() (map[string]string, []string, error)

Seatable local profile homes by name for this authority's groups

func (*CanonicalHostedRoomService) PromoteReplicaRoom

func (c *CanonicalHostedRoomService) PromoteReplicaRoom(actor Principal, roomID string, reason any) (map[string]any, error)

Continues a replicated room here, claims it for the actor and applies what local users had queued for the old home

func (*CanonicalHostedRoomService) ResolveMemberTransport

func (c *CanonicalHostedRoomService) ResolveMemberTransport(binding HostedRoomBinding, task map[string]any) (InternalSessionRPC, error)

Member turn producer, a peer route when remote, an owner relay for another home, else the local FIFO

func (*CanonicalHostedRoomService) RetryRoomTask

func (c *CanonicalHostedRoomService) RetryRoomTask(roomID string, memberID, taskID, executionGeneration any) (map[string]any, error)

Retries a deferred local attempt whose session is idle, a peer member attempt or stalled preparation through the shared service

func (*CanonicalHostedRoomService) RoomProfiles

func (c *CanonicalHostedRoomService) RoomProfiles(room map[string]any) ([]string, error)

Local profiles plus every local member a saved room already seats, sorted

func (*CanonicalHostedRoomService) ShareRoom

func (c *CanonicalHostedRoomService) ShareRoom(roomID, target string) (map[string]any, error)

Shares a room this gateway hosts with a registered peer, idempotent per peer

func (*CanonicalHostedRoomService) Start

func (c *CanonicalHostedRoomService) Start() error

Starts the room worker and the sync of shared rooms with peers

func (*CanonicalHostedRoomService) Status

func (c *CanonicalHostedRoomService) Status(roomID *string) (map[string]any, error)

Room status whose pending actions name exact local attempts for discard and retry, and peer member attempts for retry

func (*CanonicalHostedRoomService) TransportInstalled

func (c *CanonicalHostedRoomService) TransportInstalled() bool

Whether the private transport routes of this service are installed

func (*CanonicalHostedRoomService) TurnLock

func (c *CanonicalHostedRoomService) TurnLock(string) (func(), error)

Member turns serialize on the canonical FIFO, so no cross process lock is held

func (*CanonicalHostedRoomService) UnshareRoom

func (c *CanonicalHostedRoomService) UnshareRoom(roomID, target string) (map[string]any, error)

Stops sharing a room with a peer, the peer told to drop its replica on the next sync

type CapabilityDescriptor

type CapabilityDescriptor struct {
	ContractVersion              int
	Platform                     string
	Label                        string
	MaxMessageLength             int
	SupportsDraftStreaming       bool
	SupportsEdit                 bool
	SupportsThreads              bool
	MarkdownDialect              string
	LenUnit                      string
	Emoji                        string
	PlatformHint                 string
	PIISafe                      bool
	SupportsContext              bool
	SupportsInchannelContinuable bool
	SupportsBlockFormatting      bool
	SupportedOps                 []string
}

CapabilityDescriptor is the immutable capability profile negotiated at the relay handshake

func CapabilityDescriptorFromJSON

func CapabilityDescriptorFromJSON(data string) (CapabilityDescriptor, error)

Descriptor from handshake JSON, unknown keys dropped, garbage lengths and ops normalized, missing required keys an error

func NewCapabilityDescriptor

func NewCapabilityDescriptor(contractVersion int, platform, label string, maxMessageLength int, supportsDraftStreaming, supportsEdit, supportsThreads bool, markdownDialect, lenUnit string) CapabilityDescriptor

Descriptor with the dataclass defaults for the optional fields

func (CapabilityDescriptor) SupportsOp

func (d CapabilityDescriptor) SupportsOp(op string) bool

Whether the connector advertises the op, the legacy set standing in when none is advertised

func (CapabilityDescriptor) ToJSON

func (d CapabilityDescriptor) ToJSON() (string, error)

Sorted key JSON of every field for the handshake frame

type CatalogOptions

type CatalogOptions struct {
	InstallationID    any
	ProtocolVersions  []any
	LinkModes         []string
	PersistentProcess bool
	Text              *bool
	Attachments       bool
	Endpoint          any
	TargetProfile     any
	ExecutionPolicy   any
}

Arguments of one catalog build, nil fields taking the Python defaults

type ChannelListingAdapter

type ChannelListingAdapter interface {
	ListChannels(ctx context.Context) (any, error)
}

Adapter enumerating its own reachable channels, nil channels deferring to the platform builders

type ChannelOverride

type ChannelOverride struct {
	Model        any
	Provider     any
	SystemPrompt any
	AllowSilence any
}

Per channel reply policy, model, provider or system prompt override

func ChannelOverrideFromDict

func ChannelOverrideFromDict(data map[string]any) *ChannelOverride

Override of a mapping, every field nil for an empty one

func (*ChannelOverride) ToDict

func (o *ChannelOverride) ToDict() map[string]any

Mapping of the fields that are set

type ChoicePickerSender

type ChoicePickerSender interface {
	SendChoicePicker(ctx context.Context, chatID, title string, choices []map[string]any, sessionKey string,
		onChoiceSelected func(ctx context.Context, chatID, value string) (string, error), metadata map[string]any) (SendResult, error)
}

Adapter that renders a flat one tap choice picker, the send_choice_picker of telegram, discord and matrix

type ClaimedObligation

type ClaimedObligation struct {
	ObligationID    string
	SessionKey      string
	Platform        string
	ChatID          string
	ThreadID        *string
	Content         string
	NeedsMarker     bool
	Marker          string
	Profile         string
	RuntimeRecovery bool
	LastError       string
	Attempts        int
	Adopted         bool
	NotBefore       float64
}

Row claimed or adopted for redelivery, Marker empty when the runner's restart marker applies

func SweepFailedForRuntime

func SweepFailedForRuntime(ctx context.Context, platform string, now *float64, profile *string) ([]ClaimedObligation, error)

Claims this process's failed rows of one adapter that are past their retry deadline, every claim marked

func SweepRecoverable

func SweepRecoverable(ctx context.Context, now *float64, deliverablePlatforms map[string]bool, deliverableTargets map[LedgerTarget]bool) ([]ClaimedObligation, error)

Claims undelivered rows of dead owners for redelivery, abandoning exhausted ones and adopting flood rows still waiting

type CommandResult

type CommandResult struct {
	Stdout     string
	Stderr     string
	ReturnCode int
}

Captured subprocess run with text output decoded with replacement characters

func RunSystemctl

func RunSystemctl(ctx context.Context, args []string, system bool, timeout time.Duration) (CommandResult, error)

Runs systemctl in a scope, SystemctlUnavailableError when the binary is missing

type CommandSink

type CommandSink struct {
	Notices []string
	Prompt  *string
	Display *string
}

What a messaging command handler would have sent, captured for a local slash exec

func ActiveSink

func ActiveSink(ctx context.Context) *CommandSink

Sink capturing command output on the context, nil when no local exec is capturing

func CaptureCommandSink

func CaptureCommandSink(ctx context.Context) (context.Context, *CommandSink)

Context whose command acks and next turn land in a fresh sink instead of the transport

type Commentary

type Commentary struct {
	Text string
}

Commentary is interim assistant text shown between tool calls

type ConfigFns

type ConfigFns struct {
	GetEnvValue    func(ctx context.Context, key string) (string, error)
	SaveEnvValue   func(ctx context.Context, key, value string) error
	RemoveEnvValue func(ctx context.Context, key string) (bool, error)
}

The env file functions platform wizards resolve at call time

type ConnectGatewayOptions

type ConnectGatewayOptions struct {
	Endpoint *GatewayEndpoint
	MaxSize  int64
}

Options of one gateway attach, the zero value ensuring this home's owner

type ConnectorRefusal

type ConnectorRefusal struct {
	*state.RuntimeStoreError
	// contains filtered or unexported fields
}

Refusal on the legacy connector handlers' wire shape, a store refusal carrying their code and message

func (*ConnectorRefusal) Unwrap

func (r *ConnectorRefusal) Unwrap() error

func (*ConnectorRefusal) WireCode

func (r *ConnectorRefusal) WireCode() int

func (*ConnectorRefusal) WireMessage

func (r *ConnectorRefusal) WireMessage() string

type ContextExpansion

type ContextExpansion struct {
	Message  string
	Warnings []string
	Expanded bool
	Blocked  bool
}

Expanded text of one message and the verdict of its @ reference injection

type ContextRefsRunner

type ContextRefsRunner interface {
	AuthorityRunner
	InboundModelContextLength(ctx context.Context, source *SessionSource, sessionKey string) (int, error)
	ExpandInboundContextReferences(ctx context.Context, source *SessionSource, sessionKey, text string) (*string, error)
}

Runner whose inbound turns expand @ references in the session workspace with the turn model context

type ControlPrivateHandler

type ControlPrivateHandler func(params map[string]any, peerSubject string) (any, error)

Private verb handler answering only an authenticated same user peer

type ControlVerbHandler

type ControlVerbHandler func(params map[string]any) (any, error)

Verb handler answering a request with its params, an empty map when the request carries none

type CreateRoomInput

type CreateRoomInput struct {
	RoomID, Name, Members, AuthorityGatewayID any
	Now                                       *float64
	Admit                                     func(conn state.SQLiteConn) error
}

Room creation request, admit running first inside the write transaction

type CronOwnerExecution

type CronOwnerExecution struct {
	DB          *state.DB
	DBPath      string
	SessionID   string
	JobID       string
	ExecutionID string
}

CronOwnerExecution is the cron admission a context runs under, the owner's exact store and the occurrence ids

func CurrentCronExecution

func CurrentCronExecution(ctx context.Context) (CronOwnerExecution, bool)

Cron owner execution bound to ctx, false outside a canonical cron run

type CronOwnerHooks

type CronOwnerHooks struct {
	GetJob           func(ctx context.Context, jobID string) (*jsonutil.Object, error)
	JobModel         func(ctx context.Context, job *jsonutil.Object, jobID, jobName string) (*string, error)
	GetExecution     func(ctx context.Context, executionID string) (map[string]any, error)
	EnterExecution   func(ctx context.Context, job *jsonutil.Object, executionID string, record map[string]any) context.Context
	RunJob           func(ctx context.Context, job *jsonutil.Object, executionID string, extraPrompt *string, cancel *syncutil.Event) (CronRunResult, error)
	OwnerProgress    func(executionID string) any
	PopOwnerProgress func(executionID string)
}

Cron scheduler functions the owner reaches, installed by pkg/cron which imports this package

type CronRPCConnection

type CronRPCConnection interface {
	CronAuthority() *SessionAuthority
	CronActor() *Principal
}

Authenticated connection a cron RPC arrives on

type CronRunResult

type CronRunResult struct {
	Success       bool
	Output        string
	FinalResponse string
	Error         *string
}

Success flag, run document, final response and error text of one cron run

type DMAllowedAdapter

type DMAllowedAdapter interface {
	IsDMAllowed(ctx context.Context, senderID string) (bool, error)
}

Adapter rechecking a DM sender against its live allowlist under the profile scope of the context

type DMTopicEnsurer

type DMTopicEnsurer interface {
	EnsureDMTopic(ctx context.Context, chatID, name string, forceCreate bool) (string, error)
}

DMTopicEnsurer creates or recreates a named Telegram private DM topic and returns its thread id

type DeadTargetRegistry

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

DeadTargetRegistry is the persistent per profile set of delivery targets confirmed unreachable

func NewDeadTargetRegistry

func NewDeadTargetRegistry(ctx context.Context, path string) *DeadTargetRegistry

Registry loaded from the path or the profile gateway dead_targets.json, starting empty on a bad file

func (*DeadTargetRegistry) Clear

func (r *DeadTargetRegistry) Clear(platform, chatID string) bool

Removes a target's dead flag after a successful send and reports whether it was set

func (*DeadTargetRegistry) IsDead

func (r *DeadTargetRegistry) IsDead(platform, chatID string) bool

True when the target was confirmed dead

func (*DeadTargetRegistry) MarkDead

func (r *DeadTargetRegistry) MarkDead(platform, chatID, reason string) bool

Records a confirmed dead target and reports whether it was newly added

type DelegationDeliveryStore

type DelegationDeliveryStore interface {
	EnsureSessionDB(ctx context.Context) (*state.SessionDB, error)
}

Stateless adapter whose session store takes delegation delivery rows

type DeliveryAdapter

type DeliveryAdapter interface {
	Send(ctx context.Context, chatID, content, replyTo string, metadata map[string]any) (SendResult, error)
}

DeliveryAdapter is the native adapter send surface a delivery transport calls

type DeliveryAdapterRunner

type DeliveryAdapterRunner interface {
	DeliveryAdapterFor(ctx context.Context, source *SessionSource) (PlatformAdapter, error)
}

Runner seam naming the live adapter of a source after a reconnect swapped the registry entry

type DeliveryObligation

type DeliveryObligation struct {
	ObligationID   string
	SessionKey     string
	Platform       string
	ChatID         string
	ThreadID       *string
	Content        string
	AdapterProfile *string
}

type DeliveryOutcome

type DeliveryOutcome = map[string]any

DeliveryOutcome is one target result of a router delivery

type DeliveryRouter

type DeliveryRouter struct {
	Config      *GatewayConfig
	Adapters    any
	OutputDir   string
	DeadTargets *DeadTargetRegistry
}

DeliveryRouter resolves delivery targets and dispatches messages to platform adapters

func NewDeliveryRouter

func NewDeliveryRouter(config *GatewayConfig, adapters any) *DeliveryRouter

Router over the config and live adapters with the process profile output dir and dead target registry

func NewDeliveryRouterIn

func NewDeliveryRouterIn(ctx context.Context, config *GatewayConfig, adapters any, deadTargets *DeadTargetRegistry) *DeliveryRouter

Router whose output dir and default dead target registry belong to the profile of ctx

func (*DeliveryRouter) Deliver

func (r *DeliveryRouter) Deliver(ctx context.Context, content string, targets []DeliveryTarget, jobID, jobName string, metadata [][2]any) map[string]DeliveryOutcome

Delivers content to every target and returns per target results keyed by target string

func (*DeliveryRouter) DeliverToPlatform

func (r *DeliveryRouter) DeliverToPlatform(ctx context.Context, target DeliveryTarget, content string, metadata map[string]any, transport *DeliveryTransport) (any, error)

Delivers content to a messaging platform through a resolved or caller authorized transport

type DeliveryTarget

type DeliveryTarget struct {
	Platform        Platform
	ChatID          string
	ThreadID        *string
	IsOrigin        bool
	IsExplicit      bool
	UnknownPlatform *string
}

DeliveryTarget is one delivery destination of origin, local, a home channel or an explicit chat

func (DeliveryTarget) String

func (t DeliveryTarget) String() string

Target in its parseable string form

type DeliveryTransport

type DeliveryTransport struct {
	Adapter  any
	Config   *PlatformConfig
	Platform Platform
}

DeliveryTransport is the resolved live transport for one logical delivery platform

func ResolveDeliveryTransport

func ResolveDeliveryTransport(ctx context.Context, platform Platform, config *GatewayConfig, adapters any) *DeliveryTransport

Logical platform resolved to its live transport, a native adapter winning over a relay that fronts it

func (*DeliveryTransport) IsRelay

func (t *DeliveryTransport) IsRelay() bool

True when the transport is the relay

func (*DeliveryTransport) Send

func (t *DeliveryTransport) Send(ctx context.Context, logical Platform, chatID, content string, metadata map[string]any) (SendResult, error)

Sends through the transport keeping the logical platform

type DiscordChannelFlagsReader

type DiscordChannelFlagsReader interface {
	DiscordChannelFlags() (value any, ok bool)
}

Channel whose flags value can be read, ok false when the channel carries no flags

type DiscordChannelNameReader

type DiscordChannelNameReader interface {
	DiscordChannelName() (name any, ok bool)
}

Channel whose name can be read, ok false when the channel carries no name

type DiscordDirectoryAdapter

type DiscordDirectoryAdapter interface {
	DiscordDirectoryClient() DiscordDirectoryClient
}

Discord adapter exposing its gateway client, nil before login

type DiscordDirectoryChannel

type DiscordDirectoryChannel interface {
	DiscordChannelID() uint64
	DiscordChannelNameReader
}

Discord guild channel with its snowflake id and display name

type DiscordDirectoryClient

type DiscordDirectoryClient interface {
	Guilds() []DiscordDirectoryGuild
}

Discord gateway client listing the guilds the bot belongs to

type DiscordDirectoryGuild

type DiscordDirectoryGuild interface {
	GuildName() string
	TextChannels() []DiscordDirectoryChannel
	ForumChannels() []DiscordDirectoryChannel
}

Discord guild with its name, text channels and forum channels

type DiscoveryError

type DiscoveryError struct {
	Reason, Cause, Fix, Detail string
}

DiscoveryError is a bounded local control refusal, Reason the stable code and Detail what the user reads

func (*DiscoveryError) BoundedDetail

func (e *DiscoveryError) BoundedDetail(limit int) string

Detail within limit characters, an unfitting repair command dropped with a notice and a long cause cut visibly

func (*DiscoveryError) Error

func (e *DiscoveryError) Error() string

type DiscussionDecision

type DiscussionDecision struct {
	Status            string
	Reason            string
	DiscussionEventID *string
	SourceEventSeq    *int64
	ThreadID          *string
	Task              *DiscussionTaskPlan
	// Budgets the user granted this discussion beyond its first
	Continues int64
}

Current result of replaying one room's Discussion policy

func PlanNextTask

func PlanNextTask(roomValue any, events []any, localProfiles []string, initialWatermarks map[[2]string]int64, freezeInputContext bool, limits DiscussionLimits) (DiscussionDecision, error)

Replays the complete room log and returns at most one next member task

type DiscussionLimits

type DiscussionLimits struct {
	MaxRounds   int64
	MaxMessages int64
}

Finite per send scheduling ceilings, separate from replay validation

func DefaultDiscussionLimits

func DefaultDiscussionLimits() DiscussionLimits

Default scheduling ceilings

func NewDiscussionLimits

func NewDiscussionLimits(maxRounds, maxMessages any) (DiscussionLimits, error)

Validated scheduling ceilings

type DiscussionMember

type DiscussionMember struct {
	MemberID    string
	Profile     string
	Handle      string
	DisplayName string
	Target      map[string]any
}

One immutable local or peer member of the hosted room

func ResolveMentions

func ResolveMentions(texts []string, members []DiscussionMember, defaultAll bool) []DiscussionMember

Members the texts mention by handle, everyone for @all or for no mention when defaultAll

func ValidateRoster

func ValidateRoster(value any, localProfiles []string) ([]DiscussionMember, error)

Validated frozen roster of two to six members on this gateway

func (DiscussionMember) Equal

func (m DiscussionMember) Equal(other DiscussionMember) bool

Whether two members are the same frozen roster entry

type DiscussionPolicyError

type DiscussionPolicyError struct{ Msg string }

Invalid policy input or unreconstructable state, a ValueError

func (*DiscussionPolicyError) Error

func (e *DiscussionPolicyError) Error() string

type DiscussionReconstructionError

type DiscussionReconstructionError struct{ *DiscussionPolicyError }

Persisted task that durable state cannot reproduce

func (*DiscussionReconstructionError) Unwrap

type DiscussionRoom

type DiscussionRoom struct {
	RoomID         string
	Name           string
	Members        []DiscussionMember
	GatewayID      string
	AuthorityEpoch int64
}

Validated policy projection of one active hosted room

func ValidateDiscussionRoom

func ValidateDiscussionRoom(value any, localProfiles []string) (DiscussionRoom, error)

Strict same gateway policy shape of a hosted room row

type DiscussionTaskPlan

type DiscussionTaskPlan struct {
	Identity          TaskIdentity
	Payload           map[string]any
	DiscussionEventID string
	Member            DiscussionMember
	MemberIndex       int64
	RoundIndex        int64
	SeenThroughSeq    int64
}

One deterministic member turn compatible with the driver schema

func ReconstructTaskPlan

func ReconstructTaskPlan(roomValue any, events []any, task map[string]any, localProfiles []string) (DiscussionTaskPlan, error)

Reconstructs and verifies one persisted driver task after a restart

type DiscussionValidationError

type DiscussionValidationError struct{ *DiscussionPolicyError }

Malformed room, roster, payload or typed event

func (*DiscussionValidationError) Unwrap

func (e *DiscussionValidationError) Unwrap() error

type DisplayEvent

type DisplayEvent interface {
	IsInternal() bool
	EventMetadata() map[string]any
	HeartbeatSessionID() any
	EventMessageID() any
}

DisplayEvent is the inbound gateway event view the display kind helpers read

func DisplayEventOf

func DisplayEventOf(e *MessageEvent) DisplayEvent

Display kind view the response filters read off a message event, nil for a nil event

type DraftAbandoner

type DraftAbandoner interface {
	AbandonOpenDraft(ctx context.Context, chatID, text string, metadata map[string]any) (SendResult, error)
}

Adapter that seals an orphaned draft stream when its turn dies

type DrainRunner

type DrainRunner interface {
	SessionRuntimeDescriptor() map[string]any
	Draining() bool
	Running() bool
}

DrainRunner is the runner state the restart wait checks read and the descriptor they stamp

type DriverClock

type DriverClock func() any

Clock of the room driver, its value converted the way float converts it

type DriverLease

type DriverLease struct {
	RoomID            string
	GatewayID         string
	AuthorityEpoch    int64
	ProcessGeneration string
	LeaseGeneration   int64
	ExpiresAt         float64
	Reclaimed         bool
}

Fenced lease held by one gateway process incarnation

func DriverAcquireLease

func DriverAcquireLease(ctx context.Context, dbPath string, roomIDValue, gatewayIDValue, authorityEpoch, processGenerationValue, ttlSeconds any, clock DriverClock) (DriverLease, error)

Acquires an empty or expired room lease under a monotonic generation

func DriverRenewLease

func DriverRenewLease(ctx context.Context, dbPath string, lease DriverLease, ttlSeconds any, clock DriverClock) (DriverLease, error)

Renews the exact active lease generation or fails closed

type DriverStateError

type DriverStateError struct{ Msg string }

Invalid or conflicting driver state operation, a ValueError

func (*DriverStateError) Error

func (e *DriverStateError) Error() string

type DriverValidationError

type DriverValidationError struct{ Msg string }

A driver identifier, clock, TTL or payload that is invalid, a ValueError

func (*DriverValidationError) Error

func (e *DriverValidationError) Error() string

type DurableActiveTurnClearer

type DurableActiveTurnClearer interface {
	ClearDurableActiveTurn(ctx context.Context, event *MessageEvent) error
}

Runner seam clearing the durable crash marker of a turn whose reply is ledgered or owed nothing

type EmptyStreamFallbackResender

type EmptyStreamFallbackResender interface {
	ResendFinalOnEmptyStreamFallback() bool
}

Adapter that commits a fresh final send when the stream fallback has nothing unseen

type EnvAssignment

type EnvAssignment struct{ Name, Value string }

One env assignment of a multi value save, kept in call order like Python keyword arguments

type EnvCred

type EnvCred struct {
	Platform         Platform
	Creds            [][]string
	Token            string
	Fixed            []EnvSpec
	Optional         []EnvSpec
	OptionalStripped []EnvSpec
	WarnMissingEnv   string
	WarnMissingMsg   string
	Then             func(ctx context.Context, cfg *GatewayConfig, pc *PlatformConfig) error
	Home             string
	HomeStrip        bool
}

Credential gated platform enable, Creds groups all truthy with a group's names any of

func (*EnvCred) Apply

func (c *EnvCred) Apply(ctx context.Context, cfg *GatewayConfig) error

type EnvSeedRow

type EnvSeedRow struct {
	Env, Key string
	Conv     func(raw string) (any, error)
}

One env var seeded into an extra key, Conv nil keeping the stripped string and a ValueError skipping it

type EnvSpec

type EnvSpec struct {
	Key     string
	Env     string
	AnyOf   []string
	Default string
	Fn      func(string) any
	Int     bool
}

One env backed extra value, AnyOf naming alternatives read as the first truthy one

type EnvStep

type EnvStep interface {
	Apply(ctx context.Context, cfg *GatewayConfig) error
}

One env override step a platform declares, run in order after the config loads

type EnvStepFunc

type EnvStepFunc func(ctx context.Context, cfg *GatewayConfig) error

Plain function step

func (EnvStepFunc) Apply

func (f EnvStepFunc) Apply(ctx context.Context, cfg *GatewayConfig) error

type EphemeralReply

type EphemeralReply struct {
	TTLSeconds *int
	// contains filtered or unexported fields
}

System notice reply that auto deletes after the TTL on platforms that delete messages, nil TTL uses the display default

func NewEphemeralReply

func NewEphemeralReply(text string, ttlSeconds *int) *EphemeralReply

Ephemeral reply over the text with the optional TTL in seconds

func (*EphemeralReply) String

func (r *EphemeralReply) String() string

Reply text so the reply reads as plain text everywhere a handler result is treated as text

func (*EphemeralReply) Text

func (r *EphemeralReply) Text() string

Underlying reply text

type EventAttachmentConflictError

type EventAttachmentConflictError struct{ *EventCursorConflictError }

A publication that lost its file commitments, retried with a fresh plan

func (*EventAttachmentConflictError) Unwrap

func (e *EventAttachmentConflictError) Unwrap() error

type EventConflictError

type EventConflictError struct{ *HostedRoomError }

An event id reused with different immutable content

func (*EventConflictError) Unwrap

func (e *EventConflictError) Unwrap() error

type EventCursorConflictError

type EventCursorConflictError struct{ *HostedRoomError }

New room events that invalidate an uncommitted publication plan

func (*EventCursorConflictError) Unwrap

func (e *EventCursorConflictError) Unwrap() error

type EventLoop

type EventLoop interface {
	CallSoonThreadsafe(fn func()) error
	CallLater(delay time.Duration, fn func()) (LoopTimer, error)
	IsClosed() bool
	IsRunning() bool
}

Callback scheduling surface of the gateway runner loop that the liveness backstops drive

type EventPlan

type EventPlan struct {
	EventID            string
	Kind               string
	Actor              map[string]any
	Payload            map[string]any
	AuthorityGatewayID string
	AuthorityEpoch     int64
}

One idempotent room event append

func (EventPlan) AppendInput

func (p EventPlan) AppendInput(roomID string) AppendEventInput

Append input of the planned event in room

type EventQueue

type EventQueue struct {
	Overflow      []heldEvent
	OverflowBytes int
	// contains filtered or unexported fields
}

Bounded event queue plus an ordered overflow behind it refilled on every get

func NewEventQueue

func NewEventQueue(maxsize int) *EventQueue

func (*EventQueue) Empty

func (q *EventQueue) Empty() bool

func (*EventQueue) Full

func (q *EventQueue) Full() bool

func (*EventQueue) Get

func (q *EventQueue) Get(ctx context.Context) (any, error)

Oldest item, waiting until one arrives or the context ends

func (*EventQueue) GetNowait

func (q *EventQueue) GetNowait() (any, bool)

Oldest item with one overflow item moved into the queue, false when the queue is empty

func (*EventQueue) Hold

func (q *EventQueue) Hold(item any, size int)

Queues an item behind everything already read without ever dropping it

func (*EventQueue) Maxsize

func (q *EventQueue) Maxsize() int

func (*EventQueue) OverflowLen

func (q *EventQueue) OverflowLen() int

func (*EventQueue) PutFirst

func (q *EventQueue) PutFirst(item any)

Puts an item back at the head of the queue ahead of everything waiting, never refused by the bound

func (*EventQueue) PutNowait

func (q *EventQueue) PutNowait(item any) bool

Adds an item to the queue, false when the queue is full

func (*EventQueue) QSize

func (q *EventQueue) QSize() int

func (*EventQueue) TakeMatching

func (q *EventQueue) TakeMatching(match func(item any) bool) []any

Removes and returns the queued items match accepts, the rest staying in order

type ExecApprovalAction

type ExecApprovalAction struct {
	Label  string
	Choice string
	Style  string
}

One rendered approval button row with the label, the approval choice and the button style

type ExecApprovalPrompt

type ExecApprovalPrompt struct {
	ChatID      string
	SessionKey  string
	Text        string
	Actions     []ExecApprovalAction
	Command     string
	Description string
	SmartDenied bool
	Metadata    map[string]any
	RequestID   *string
}

One exec approval prompt ready for a platform to render natively

func (*ExecApprovalPrompt) Choices

func (p *ExecApprovalPrompt) Choices() []string

Approval choices of the action rows in order

type ExecApprovalPromptSender

type ExecApprovalPromptSender interface {
	SendExecApprovalPrompt(ctx context.Context, prompt *ExecApprovalPrompt) (SendResult, error)
}

Adapter that renders native approval buttons by overriding the prompt hook

type ExistingService

type ExistingService struct {
	Backend   string
	StartArgv []string
	Running   bool
}

ExistingService is an installed supervisor definition and the argv that asks it to start

func DiscoverExistingGatewayService

func DiscoverExistingGatewayService(ctx context.Context, h string, deadline float64) (*ExistingService, error)

Installed service owning home on this host, a start error for an unsupported or failing manager

type FailedObligationRedeliverer

type FailedObligationRedeliverer interface {
	RedeliverFailedObligationsForPlatform(ctx context.Context, platform Platform, profile *string) int
}

Runner seam sweeping the failed obligations of a platform once a replacement adapter is live

type FatalErrorHandler

type FatalErrorHandler func(ctx context.Context, adapter PlatformAdapter) error

FatalErrorHandler is the runner callback run once an adapter hits a fatal error

type FinalEditFloodFallback

type FinalEditFloodFallback interface {
	FallbackOnFinalEditFlood() bool
}

Adapter whose turn final edit flood enters the fallback send at once

type FloodRedeliveryScheduler

type FloodRedeliveryScheduler interface {
	ScheduleFloodRedelivery(ctx context.Context, platform Platform, profile *string)
}

Runner seam arming the timed redelivery after a refused final reply

type FooterInputs

type FooterInputs struct {
	Model          string
	ContextTokens  int
	ContextLength  int
	Cwd            string
	TurnSeconds    *float64
	RequestedModel string
	ServedModel    string
}

Inputs of one footer render, a zero context length or nil turn seconds standing for unmeasured

type ForeignGatewayPid

type ForeignGatewayPid struct {
	PID  int
	Home string
}

ForeignGatewayPid is a gateway pid outside the update scope with its home, empty when unreadable

func PartitionGatewayPidsByScope

func PartitionGatewayPidsByScope(ctx context.Context, pids []int, scope map[string]bool) ([]int, []ForeignGatewayPid)

PartitionGatewayPidsByScope splits pids into owned ones and foreign ones paired with their readable home

type FrameHooks

type FrameHooks struct {
	Inbound   func(raw string, frame *jsonutil.Object)
	Malformed func(raw string)
}

Callbacks of a reader that reads on past frames it cannot decode, the terminal UI link

type GatewayChild

type GatewayChild = gatewayChild

Process children of a gateway pid snapshotted before it is signalled

func SnapshotGatewayChildren

func SnapshotGatewayChildren(pid int) []GatewayChild

Children of pid captured before a takeover signals it

type GatewayClient

type GatewayClient struct {
	Events *EventQueue
	// contains filtered or unexported fields
}

One attached owner connection multiplexing RPC answers and the session event stream

func ConnectGateway

func ConnectGateway(ctx context.Context) (*GatewayClient, error)

Attaches to this home's owner, starting it when needed

func ConnectGatewayWith

func ConnectGatewayWith(ctx context.Context, opts ConnectGatewayOptions) (*GatewayClient, error)

Attaches to the given endpoint, the explicit TUI gateway URL or this home's ensured owner

func NewGatewayClient

func NewGatewayClient(socket GatewaySocket) *GatewayClient

func (*GatewayClient) Close

func (c *GatewayClient) Close() error

Closes the socket and waits for the reader to finish failing every pending answer

func (*GatewayClient) EventQueue

func (c *GatewayClient) EventQueue() *EventQueue

Event frames read off the socket, the client.events queue of the thin client

func (*GatewayClient) PendingCount

func (c *GatewayClient) PendingCount() int

Requests still waiting for an answer

func (*GatewayClient) RPC

func (c *GatewayClient) RPC(ctx context.Context, method string, params map[string]any) (map[string]any, error)

One request answered as a plain map, waiting the default budget

func (*GatewayClient) RPCTimeout

func (c *GatewayClient) RPCTimeout(ctx context.Context, method string, params map[string]any, timeout time.Duration) (any, error)

One request and its raw answer, timeout zero the default budget and negative no deadline

func (*GatewayClient) Read

func (c *GatewayClient) Read()

Reads frames until the socket ends, answering RPCs and queueing events, then fails every waiter

func (*GatewayClient) ReadError

func (c *GatewayClient) ReadError() error

Error the socket read failed with once the reader finished, nil while it reads

func (*GatewayClient) ReaderDone

func (c *GatewayClient) ReaderDone() bool

Whether the reader finished, every pending answer already failed and no further frame arriving

func (*GatewayClient) SendFrame

func (c *GatewayClient) SendFrame(text string) error

Writes one raw frame on the socket, the websocket.send of a server request reply

func (*GatewayClient) SetFrameHooks

func (c *GatewayClient) SetFrameHooks(h FrameHooks)

Installs the frame callbacks, called before Start so the reader sees them from its first frame

func (*GatewayClient) Start

func (c *GatewayClient) Start() *GatewayClient

Starts the reader goroutine, the async context entry

type GatewayClientError

type GatewayClientError struct {
	Msg string
	// Refusal of the resume request itself, a policy or launch key mismatch
	ResumeRefused bool
	// Exit status of a refused command line, zero meaning 1
	ExitStatus int
}

func (*GatewayClientError) Error

func (e *GatewayClientError) Error() string

type GatewayConfig

type GatewayConfig struct {
	Platforms map[Platform]*PlatformConfig

	QuickCommands                map[string]any
	SessionsDir                  string
	WriteSessionsJSON            bool
	AlwaysLogLocal               bool
	FilterSilenceNarration       bool
	STTEnabled                   bool
	STTEchoTranscripts           bool
	GroupSessionsPerUser         bool
	ThreadSessionsPerUser        bool
	MaxConcurrentSessions        int
	MultiplexProfiles            *bool
	RoomLinkURL                  *string
	SystemdWatchdogSeconds       int
	LoopWatchdog                 bool
	LoopWatchdogProbeIntervalS   float64
	LoopWatchdogProbeTimeoutS    float64
	LoopWatchdogMaxStrikes       int
	OnAllAdaptersDown            string
	UnauthorizedDMBehavior       string
	UnauthorizedDMDeclineMessage string
	Streaming                    StreamingConfig
	SessionStoreMaxAgeDays       int
	ProfileRoutes                []*ProfileRoute
	// contains filtered or unexported fields
}

Main gateway configuration, platform connections, session policies and delivery settings

func DefaultGatewayConfig

func DefaultGatewayConfig(ctx context.Context) *GatewayConfig

Gateway config with the dataclass defaults for the home in ctx

func GatewayConfigFromDict

func GatewayConfigFromDict(ctx context.Context, raw any) (*GatewayConfig, error)

Gateway config of a mapping, top level keys winning over the nested gateway form

func LoadGatewayConfig

func LoadGatewayConfig(ctx context.Context) (*GatewayConfig, error)

Gateway config from env over config.yaml over defaults

func LoadGatewayConfigFile

func LoadGatewayConfigFile(ctx context.Context, path string) (*GatewayConfig, error)

Gateway config of an explicit local YAML file, refused when the config backend has no file tooling

func (*GatewayConfig) GetConnectedPlatforms

func (c *GatewayConfig) GetConnectedPlatforms(ctx context.Context) []Platform

Enabled and configured platforms sorted by value so the prompt block stays byte stable

func (*GatewayConfig) GetHomeChannel

func (c *GatewayConfig) GetHomeChannel(platform Platform) *HomeChannel

Home channel of a configured platform, nil otherwise

func (*GatewayConfig) GetNoticeDelivery

func (c *GatewayConfig) GetNoticeDelivery(platform Platform) string

Effective notice delivery mode, public or private

func (*GatewayConfig) GetUnauthorizedDMBehavior

func (c *GatewayConfig) GetUnauthorizedDMBehavior(platform Platform) string

Effective unauthorized DM behavior, email defaulting to ignore unless its own block opts in

func (*GatewayConfig) MaxConcurrentSessionsAttr

func (c *GatewayConfig) MaxConcurrentSessionsAttr() any

Configured active session cap as the registry resolver reads it, nil when unset

func (*GatewayConfig) PlatformKeys

func (c *GatewayConfig) PlatformKeys() []Platform

Platforms in the insertion order a Python dict keeps, platforms stored without SetPlatform following sorted

func (*GatewayConfig) PlatformSetDefault

func (c *GatewayConfig) PlatformSetDefault(p Platform) *PlatformConfig

Config of a platform, created with the defaults and appended to the order when absent

func (*GatewayConfig) PostInit

func (c *GatewayConfig) PostInit()

Bounds the systemd watchdog interval as the dataclass post init does

func (*GatewayConfig) RuntimeProfileHomes

func (c *GatewayConfig) RuntimeProfileHomes() ([]profiles.ServedProfile, bool)

Served profile homes boot reserved, false while discovery is not frozen

func (*GatewayConfig) SetPlatform

func (c *GatewayConfig) SetPlatform(p Platform, pc *PlatformConfig)

Stores a platform block, a platform new to the mapping moved to the end of the order as a dict insert does

func (*GatewayConfig) SetRuntimeProfileHomes

func (c *GatewayConfig) SetRuntimeProfileHomes(homes []profiles.ServedProfile)

Freezes the served profile homes boot reserved, the _runtime_profile_homes the config carries

func (*GatewayConfig) ToDict

func (c *GatewayConfig) ToDict() map[string]any

Mapping form of the whole config

type GatewayControlServer

type GatewayControlServer struct {
	TicketStore *TicketStore
	// contains filtered or unexported fields
}

Gateway owned control listener answering identify, status and the verbs the gateway registers

func NewGatewayControlServer

func NewGatewayControlServer(home string, verbHandlers map[string]ControlVerbHandler) (*GatewayControlServer, error)

Server for home, the process home when empty, answering the default verbs plus the given ones

func (*GatewayControlServer) AddPrivateHandlers

func (s *GatewayControlServer) AddPrivateHandlers(handlers map[string]ControlPrivateHandler)

Adds private verbs only an authenticated same user peer reaches

func (*GatewayControlServer) BindPath

func (s *GatewayControlServer) BindPath() string

Path the listener bound, empty before a POSIX start

func (*GatewayControlServer) CleanupFiles

func (s *GatewayControlServer) CleanupFiles()

Removes the socket and pointer files this server still owns, leaving a replacement alone

func (*GatewayControlServer) HandleRequestLine

func (s *GatewayControlServer) HandleRequestLine(raw []byte, peerSubject string) []byte

One JSON request line to one JSON response line, never failing

func (*GatewayControlServer) Home

func (s *GatewayControlServer) Home() string

Resolved home the listener serves

func (*GatewayControlServer) Start

func (s *GatewayControlServer) Start() bool

Binds and starts serving, false after logging why it could not

func (*GatewayControlServer) Stop

func (s *GatewayControlServer) Stop()

Stops serving, revokes outstanding tickets and removes the socket and pointer files

type GatewayEndpoint

type GatewayEndpoint struct {
	ProfileID       string
	InstanceID      string
	AuthorityEpoch  int64
	RuntimeProtocol int
	APIOrigin       string
	Supervisor      string
	ControlHome     string
	CodeSHA         string
	// Go build ID and wire contract version the owner runs, empty and zero for an owner older than both
	BuildID string
}

GatewayEndpoint is the validated identity of a live gateway owner

type GatewayLiveness

type GatewayLiveness struct {
	Running    bool
	PID        any
	Source     string
	HealthBody *jsonutil.Object
	ProbeError bool
	Runtime    *jsonutil.Object
}

Resolved gateway liveness for one surface, Source naming the ladder rung that answered

func ResolveGatewayLiveness

func ResolveGatewayLiveness(o LivenessOptions) GatewayLiveness

One answer to whether the gateway is up, a failing rung degrading to the next with ProbeError set

type GatewayLoopRunner

type GatewayLoopRunner interface {
	Running() bool
	GatewayLoop() EventLoop
	OnGatewayLoop(ctx context.Context) bool
}

Running gateway loop state, the runner _running flag and its _gateway_loop

type GatewayNotice

type GatewayNotice struct {
	Kind  string
	Text  string
	Extra map[string]any
}

GatewayNotice is a gateway owned notice such as restart or online with its default rendering

type GatewayRPCError

type GatewayRPCError struct {
	Msg  string
	Code *int64
	Data map[string]any
	Raw  any
}

Received owner refusal with its bounded reason, integer code and scalar only data

func RPCError

func RPCError(errMember any) *GatewayRPCError

Refusal for one received error member keeping only bounded reason codes

func (*GatewayRPCError) As

func (e *GatewayRPCError) As(target any) bool

Lets a refusal match a GatewayClientError target like the Python subclass

func (*GatewayRPCError) Error

func (e *GatewayRPCError) Error() string

type GatewayRoomCatalog

type GatewayRoomCatalog struct {
	InstallationID    string
	ProtocolVersions  []int64
	LinkModes         []string
	PersistentProcess bool
	Text              bool
	Attachments       bool
	ExecutionPolicy   *RoomExecutionPolicy
	CatalogDigest     string
	EndpointURL       *string
	EndpointReason    *string
	TransportSecurity *string
}

Authenticated gateway capabilities inherited by its Bots

func GatewayRoomCatalogFromMapping

func GatewayRoomCatalogFromMapping(value any) (*GatewayRoomCatalog, error)

Catalog validated from its peer mapping with its digest checked

func (*GatewayRoomCatalog) AsMapping

func (c *GatewayRoomCatalog) AsMapping() *jsonutil.Object

Canonical catalog mapping, the endpoint present only when advertised

func (*GatewayRoomCatalog) EndpointMapping

func (c *GatewayRoomCatalog) EndpointMapping() *jsonutil.Object

Normalized self advertised endpoint capability

type GatewaySetupWizardFns

type GatewaySetupWizardFns struct {
	PrintSetupHeader   func(title string)
	ConfirmReconfigure func(ctx context.Context, label string, envVars ...string) (bool, error)
	OfferHomeChannel   func(ctx context.Context, homeVar, userID, what string) error
	SaveEnvValues      func(ctx context.Context, values ...EnvAssignment) error
	PromptCSV          func(promptText, def string) string
}

The helpers platform plugin wizards import

type GatewaySocket

type GatewaySocket interface {
	Recv() (raw string, err error)
	Send(data string) error
	Open() bool
	Subprotocol() string
	Close() error
}

Socket a client reads frames from and writes requests to

func DialGatewaySocket

func DialGatewaySocket(ctx context.Context, target string, protocols []string, maxSize int64) (GatewaySocket, error)

Socket on a gateway WebSocket target offering the protocols, never through a proxy

func DialOwnerSocket

func DialOwnerSocket(ctx context.Context, profileHome string, endpoint *GatewayEndpoint, scope string, maxSize int64) (GatewaySocket, error)

Socket on the ready endpoint dialed with this home's ticket of the scope, never through a proxy

type GatewayStreamConsumer

type GatewayStreamConsumer struct {

	// Whether this consumer is fed the final reply's stream deltas
	StreamDeltasEnabled bool
	// contains filtered or unexported fields
}

Async consumer that progressively edits a platform message with streamed tokens

func NewGatewayStreamConsumer

func NewGatewayStreamConsumer(adapter PlatformAdapter, chatID string, opts StreamConsumerOptions) *GatewayStreamConsumer

Consumer for one chat with every per run transport state fresh

func (*GatewayStreamConsumer) AcceptsToolProgress

func (s *GatewayStreamConsumer) AcceptsToolProgress() bool

True only while native streaming is active

func (*GatewayStreamConsumer) Adapter

Adapter the stream consumer sends and edits through

func (*GatewayStreamConsumer) AlreadySent

func (s *GatewayStreamConsumer) AlreadySent() bool

Whether anything durable was sent to the chat

func (*GatewayStreamConsumer) CloseForApprovalPrompt

func (s *GatewayStreamConsumer) CloseForApprovalPrompt(boundaryText, reason string, reopen bool) *StreamBoundary

Queues an approval or clarify boundary, an already settled boundary without native streaming

func (*GatewayStreamConsumer) DeliveredFinalMatches

func (s *GatewayStreamConsumer) DeliveredFinalMatches(finalText string) *bool

Tri state reconcile of the recorded turn final payload against the final text, nil when the flags are trusted

func (*GatewayStreamConsumer) FinalContentDelivered

func (s *GatewayStreamConsumer) FinalContentDelivered() bool

Whether the final content landed even when the cosmetic finalize edit failed

func (*GatewayStreamConsumer) FinalResponseSent

func (s *GatewayStreamConsumer) FinalResponseSent() bool

Whether the turn final answer was delivered by the stream

func (*GatewayStreamConsumer) Finish

func (s *GatewayStreamConsumer) Finish(finalText *string)

Signals stream completion, the authoritative final text adopted as the finalize payload when given

func (*GatewayStreamConsumer) FlushPendingSync

func (s *GatewayStreamConsumer) FlushPendingSync(timeout float64) bool

Blocks until everything queued so far is delivered, false on timeout

func (*GatewayStreamConsumer) HasDeliveredText

func (s *GatewayStreamConsumer) HasDeliveredText(text string) bool

Whether text was already delivered as visible chat content

func (*GatewayStreamConsumer) HasDurablyDeliveredText

func (s *GatewayStreamConsumer) HasDurablyDeliveredText(text string) bool

Delivered text match restricted to deliveries that outlive the turn

func (*GatewayStreamConsumer) LastSentText

func (s *GatewayStreamConsumer) LastSentText() any

Text the consumer last put on the wire, read by the reply clock

func (*GatewayStreamConsumer) MessageID

func (s *GatewayStreamConsumer) MessageID() string

Id of the live preview message, empty when none

func (*GatewayStreamConsumer) OnCommentary

func (s *GatewayStreamConsumer) OnCommentary(text string)

Queues a completed interim assistant commentary message

func (*GatewayStreamConsumer) OnDelta

func (s *GatewayStreamConsumer) OnDelta(text any)

Agent worker callback, a text delta queued and nil marking a tool boundary

func (*GatewayStreamConsumer) OnSegmentBreak

func (s *GatewayStreamConsumer) OnSegmentBreak()

Finalizes the current stream segment and starts a fresh message

func (*GatewayStreamConsumer) OnToolProgress

func (s *GatewayStreamConsumer) OnToolProgress(line string)

Overlays a tool progress line in the native bubble until the next delta, safe from any goroutine

func (*GatewayStreamConsumer) RequestReopenSeed

func (s *GatewayStreamConsumer) RequestReopenSeed()

Requests an eager native re seed after a clarify answer, a no op unless one is pending

func (*GatewayStreamConsumer) Run

Drains the queue and edits the platform message until the turn finishes, the stream is stale or ctx ends

func (*GatewayStreamConsumer) TurnSplitDelivery

func (s *GatewayStreamConsumer) TurnSplitDelivery() bool

Whether the turn final was delivered split across several messages

type GatewayUnavailableError

type GatewayUnavailableError struct {
	Msg, State, ReasonCode string
}

No ready owner to dial, State the ensure verdict and nothing submitted

func (*GatewayUnavailableError) As

func (e *GatewayUnavailableError) As(target any) bool

Lets an unavailable owner match a GatewayClientError target like the Python subclass

func (*GatewayUnavailableError) Error

func (e *GatewayUnavailableError) Error() string

type GlibcMallocHandle

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

GlibcMallocHandle is the mallopt entry point of a glibc process

func GlibcMalloc

func GlibcMalloc() *GlibcMallocHandle

glibc libc handle of this process when it exports gnu_get_libc_version and mallopt, nil otherwise

func (*GlibcMallocHandle) Mallopt

func (h *GlibcMallocHandle) Mallopt(param, value int32) int32

Calls mallopt with a C int parameter and value, returning its C int result

type HTTPApp

type HTTPApp struct {
	ClientMaxSize int64
	Middlewares   []WebMiddleware
	State         map[string]any
	// contains filtered or unexported fields
}

Ordered aiohttp style router with a body cap that freezes once served

func NewHTTPApp

func NewHTTPApp(clientMaxSize int64) *HTTPApp

Application with the given client body cap, the aiohttp default of 1 MiB when zero

func (*HTTPApp) AddGet

func (a *HTTPApp) AddGet(path string, handler WebHandler) error

Registers a GET handler and its HEAD twin

func (*HTTPApp) AddPost

func (a *HTTPApp) AddPost(path string, handler WebHandler) error

Registers a POST handler

func (*HTTPApp) AddRoute

func (a *HTTPApp) AddRoute(method, path string, handler WebHandler) error

Registers a handler for a method and path

func (*HTTPApp) Freeze

func (a *HTTPApp) Freeze()

Freezes the router so no resource can be added and empty plain paths serve the root

func (*HTTPApp) Frozen

func (a *HTTPApp) Frozen() bool

Whether the router is frozen

func (*HTTPApp) Handle

func (a *HTTPApp) Handle(ctx context.Context, request *WebRequest) (*WebResponse, error)

Routes and runs the request like Application._handle, the router's HTTP exception raised as an error

func (*HTTPApp) Resolve

func (a *HTTPApp) Resolve(request *WebRequest) (WebHandler, map[string]string, *WebHTTPError)

Handler and match info routing the request, else the 404 or 405 HTTP exception of the router

type HTTPAppRunner

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

Started TCP sites of one served application, the aiohttp AppRunner

func BindListener

func BindListener(ctx context.Context, adapter PlatformAdapter, app *HTTPApp, host *string, port int, ingressPath string, opts ListenOptions) (*HTTPAppRunner, error)

Starts the app on host and port, or in shared listener mode publishes it for prefix forwarding and returns nil

func StartHTTPApp

func StartHTTPApp(ctx context.Context, app *HTTPApp, host *string, port int, opts ListenOptions) (*HTTPAppRunner, error)

Starts the application on every address of host and port and returns its runner

func StartTCPSite

func StartTCPSite(ctx context.Context, app *HTTPApp, host *string, port int, logTag string, accessLog AccessLog) (*HTTPAppRunner, error)

Starts the app on host and port, exclusive on macOS with one reuse retry past a dead TIME_WAIT socket

func (*HTTPAppRunner) Addrs

func (rn *HTTPAppRunner) Addrs() []net.Addr

Bound addresses of the started sites

func (*HTTPAppRunner) Cleanup

func (rn *HTTPAppRunner) Cleanup(ctx context.Context) error

Stops the sites, waits up to the aiohttp 60 second shutdown timeout for handlers and then cancels them

func (*HTTPAppRunner) Port

func (rn *HTTPAppRunner) Port() int

Port of the first started site, zero when none is bound

func (*HTTPAppRunner) ServeHTTP

func (rn *HTTPAppRunner) ServeHTTP(w http.ResponseWriter, r *http.Request)

Serves one wire request through the application and writes the access log line

type HTTPXLimits

type HTTPXLimits struct {
	MaxConnections          *int
	MaxKeepaliveConnections *int
	KeepaliveExpiry         *float64
}

Keepalive pool bounds of an HTTP client, nil fields meaning unbounded as in httpx Limits

func DefaultHTTPXLimits

func DefaultHTTPXLimits() HTTPXLimits

The httpx default pool of 100 connections, 20 kept alive for five seconds

func PlatformHTTPXLimits

func PlatformHTTPXLimits(ctx context.Context) HTTPXLimits

Tighter keepalive limits for persistent chat app clients of the profile ctx serves

type HandleCacheGetOptions

type HandleCacheGetOptions struct {
	RaiseOnError bool
	OnRecovered  func()
	NonCacheable func(error) bool
}

Keyword options of one get call

type HeldInboundAdopter

type HeldInboundAdopter interface {
	AdoptHeldInbound(ctx context.Context, source any)
}

Adapter that takes over inbound another instance is holding

type HeldNotAdmittedError

type HeldNotAdmittedError struct{ *state.RuntimeStoreError }

Settleable runtime_coordination_required refusal that admitted nothing yet

func (*HeldNotAdmittedError) Admitted

func (e *HeldNotAdmittedError) Admitted() bool

False, the admitted attribute the sender reads before it asks settle

func (*HeldNotAdmittedError) Unwrap

func (e *HeldNotAdmittedError) Unwrap() error

type HomeChannel

type HomeChannel struct {
	Platform Platform
	ChatID   string
	Name     any
	ThreadID *string
	UserID   *string
	ScopeID  *string
}

Default destination of a platform, thread routing to the topic where it was set

func HomeChannelFromDict

func HomeChannelFromDict(ctx context.Context, data map[string]any) (*HomeChannel, error)

Home channel of a mapping, KeyError for a missing platform or chat id, nil when the chat id is null and no home channel is set

func NewHomeChannel

func NewHomeChannel(platform Platform, chatID string, name any) *HomeChannel

Home channel with a Discord channel link reduced to its channel id

func (*HomeChannel) PostInit

func (h *HomeChannel) PostInit()

Normalizes a pasted Discord channel link to the bare channel id

func (*HomeChannel) ToDict

func (h *HomeChannel) ToDict() map[string]any

Mapping form with the optional ids only when set

type HomeStep

type HomeStep struct {
	Platform Platform
	EnvBase  string
	Strip    bool
}

Home channel step whose platform and env base stay readable to the profile channel scan

func (HomeStep) Apply

func (s HomeStep) Apply(ctx context.Context, cfg *GatewayConfig) error

type HostAttachDecision

type HostAttachDecision struct {
	Outcome   string
	Message   string
	Owner     *HostGateway
	Transient bool
}

Attach verdict with the owner it concerns, transient when a supervisor must retry it

func DecideHostAttach

func DecideHostAttach(ctx context.Context, ourHome string, replace bool) (HostAttachDecision, error)

Attach, rescan then attach, replace or refuse, a configured standalone profile allowed to coexist

func StandaloneAttachDecision

func StandaloneAttachDecision(ctx context.Context, ourHome string, owner *HostGateway) (*HostAttachDecision, error)

Coexistence for a standalone profile only after every live gateway confirms it does not serve it

type HostGateway

type HostGateway struct {
	PID         int
	Home        string
	Profiles    []string
	ServedKnown bool
	Standalone  bool
}

The one live host gateway, where it was launched from and what it serves

func HostGatewayNow

func HostGatewayNow() *HostGateway

Live host gateway serving every profile through the memoized probe, nil when none answers

func HostGatewayProbe

func HostGatewayProbe(wait time.Duration) *HostGateway

The one live host gateway or nil, waiting up to wait for its channel to answer

func HostMultiplexerServingOwner

func HostMultiplexerServingOwner(ctx context.Context, profileName *string) *HostGateway

Host gateway serving the profile, nil for the default profile or when none serves it

func RequestServeProfile

func RequestServeProfile(profile string, timeout time.Duration, owner *HostGateway) *HostGateway

Asks the host gateway to rescan profiles, returning it once it serves the profile or answers standalone

func ServedByAnotherHostGateway

func ServedByAnotherHostGateway(ctx context.Context, profileName *string) *HostGateway

Host gateway serving the profile when the profile itself runs no gateway

func (*HostGateway) Describe

func (g *HostGateway) Describe() string

Pid, launching profile and served set of the owner in one line

func (*HostGateway) ProfileLabel

func (g *HostGateway) ProfileLabel() string

Profile of the home that launched the owner

func (*HostGateway) Serves

func (g *HostGateway) Serves(profile string) bool

Whether the owner positively serves the profile, never while its served set is unknown

type HostGatewayTopology

type HostGatewayTopology struct {
	PID      int
	Profiles []string
	Source   string
	Home     string
}

The single gateway process on this host with the profile roster it multiplexes

func CurrentHostGatewayTopology

func CurrentHostGatewayTopology() (*HostGatewayTopology, error)

The one live host gateway and its served profiles, nil when no gateway owns the role

func HostGatewayServing

func HostGatewayServing(ctx context.Context, profileName string) (*HostGatewayTopology, error)

Host gateway when it serves the profile, an empty name meaning the active profile, nil otherwise

func (*HostGatewayTopology) Describe

func (t *HostGatewayTopology) Describe() string

Shared phrasing naming the host gateway pid and the profiles it serves

func (*HostGatewayTopology) Serves

func (t *HostGatewayTopology) Serves(profileName string) (bool, error)

Whether this host process serves the profile, default included

type HostLockOutcome

type HostLockOutcome string

Outcome of a host lock claim, an unopenable lock never reading as contention

const (
	HostLockAcquired     HostLockOutcome = "acquired"
	HostLockHeldByOther  HostLockOutcome = "held-by-other"
	HostLockCouldNotOpen HostLockOutcome = "could-not-open"
)

func ClaimHostLock

func ClaimHostLock(ctx context.Context, role string) (HostLockOutcome, error)

Takes the host wide lock for role idempotently per lock path, the open error accompanying could not open

type HostPublishOptions

type HostPublishOptions struct {
	Profiles []string
	Home     string
}

Served profiles and launch home a host record publish carries

type HostRecord

type HostRecord struct {
	Role            string
	PID             int
	CreateTime      *float64
	ProtocolVersion int
	Profiles        []string
	UpdatedAt       string
	Home            string
	StartTime       *int64
	BootEpoch       string
}

A published host role owner whose profiles are the served set, not the launch profile

func HostRecordFromJSON

func HostRecordFromJSON(payload any) *HostRecord

Record from a decoded payload, nil unless it is a dict with a positive pid and a known role

func PublishHostRecord

func PublishHostRecord(ctx context.Context, role string, o HostPublishOptions) *HostRecord

Publishes this process as the role host owner, nil when the write failed

func ReadHostRecord

func ReadHostRecord(role string, includeStale bool) *HostRecord

Published record for role, nil when absent, foreign, corrupt or stale unless stale ones are wanted

func (*HostRecord) ToJSON

func (r *HostRecord) ToJSON() *jsonutil.Object

Record fields in their published key order, the gateway role publishing no bound address or token

type HostedAdmissionChecker

type HostedAdmissionChecker interface {
	CheckAdmission(ctx context.Context, ref SessionRef, row *jsonutil.Object) error
}

Hosted room service that reauthorizes a queued hosted admission at its claim

type HostedAttemptError

type HostedAttemptError struct {
	Err                 error
	NotAdmitted         bool
	RefusedBeforeSubmit bool
}

Failure of a member turn carrying the admission proof the room driver books it by

func (*HostedAttemptError) Error

func (e *HostedAttemptError) Error() string

func (*HostedAttemptError) Unwrap

func (e *HostedAttemptError) Unwrap() error

type HostedAttester

type HostedAttester func(ctx context.Context, selector map[string]any, operation string, params map[string]any) (map[string]any, error)

Source owner attestation of one hosted operation, naming the durable room owner and the target home

type HostedAuthorizer

type HostedAuthorizer func(ctx context.Context, operation string, task *TaskIdentity, generation *int64) (bool, error)

Check of one hosted operation against current room membership and durable task state

type HostedDispatchTimeoutError

type HostedDispatchTimeoutError struct{}

Expiry of a hosted dispatch, ambiguous so it never cancels the admission or claims non admission

func (*HostedDispatchTimeoutError) Error

type HostedKeyError

type HostedKeyError struct{ Key string }

Missing mapping key of a hosted room record, a KeyError

func (*HostedKeyError) Error

func (e *HostedKeyError) Error() string

func (*HostedKeyError) ErrorKind

func (e *HostedKeyError) ErrorKind() string

Kind label of the error

type HostedMemberDispatch

type HostedMemberDispatch struct {
	ProtocolVersion       int64
	RoomID                string
	HomeInstallID         string
	AuthorityGatewayID    string
	AuthorityEpoch        int64
	MemberID              string
	TargetInstallID       string
	TargetProfile         string
	TaskID                string
	ExecutionGeneration   int64
	SourceEventSeq        int64
	CancellationScopeID   string
	Prompt                string
	PromptDigest          string
	CapabilityDigest      string
	ExecutionPolicyDigest string
	TraceID               string
	Attachments           []map[string]any
}

Recipient validated identity of one remote room member attempt

func BuildMemberDispatch

func BuildMemberDispatch(binding HostedRoomBinding, route PeerMemberRoute, roomID, taskID, targetProfile string, executionGeneration, sourceEventSeq int64, prompt, traceID string, files []map[string]any) (*HostedMemberDispatch, error)

Fully fenced member dispatch shared by submit and recovery, naming the files the peer holds for the turn

func HostedMemberDispatchFromMapping

func HostedMemberDispatchFromMapping(value any) (*HostedMemberDispatch, error)

Dispatch validated from its wire mapping, its prompt checked against the prompt digest

func (*HostedMemberDispatch) AsMapping

func (d *HostedMemberDispatch) AsMapping() *jsonutil.Object

Canonical wire mapping of the dispatch in field order, the one fingerprinting reads

type HostedMemberRefusal

type HostedMemberRefusal struct {
	Reason string
	Field  string
	Detail string
}

Why a new member may not take a profile name, the refusal reason, field and detail

type HostedRoomAttachmentStore

type HostedRoomAttachmentStore struct {
	DBPath            string
	Root              string
	BlobRoot          string
	Clock             func() float64
	RoomQuotaBytes    int64
	GatewayQuotaBytes int64
	RoomQuotaCount    int64
	GatewayQuotaCount int64
	// contains filtered or unexported fields
}

SQLite owned metadata and private content deduplicated blob bytes

func NewHostedRoomAttachmentStore

func NewHostedRoomAttachmentStore(ctx context.Context, dbPath string, o AttachmentStoreOptions) (*HostedRoomAttachmentStore, error)

Opens the store, initializing, reconciling and pruning once per database file

func (*HostedRoomAttachmentStore) AbortMessageCommit

func (s *HostedRoomAttachmentStore) AbortMessageCommit(roomIDValue, eventIDValue any, attachmentIDs []string) (int64, error)

Returns a failed pre event commitment to its bounded upload state

func (*HostedRoomAttachmentStore) CommitMessageWithReceipt

func (s *HostedRoomAttachmentStore) CommitMessageWithReceipt(c AttachmentCommit) ([]map[string]any, []string, error)

Commits a manifest and reports only the rows this call transitioned

func (*HostedRoomAttachmentStore) Describe

func (s *HostedRoomAttachmentStore) Describe(roomID, attachmentID, recipientMemberID, eventID any) (map[string]any, error)

Metadata of a committed attachment the recipient may read for the event, without bytes

func (*HostedRoomAttachmentStore) FindUpload

func (s *HostedRoomAttachmentStore) FindUpload(roomIDValue, uploadIDValue any) (map[string]any, error)

Verified metadata of an idempotent upload retry, nil when none is live

func (*HostedRoomAttachmentStore) Prune

func (s *HostedRoomAttachmentStore) Prune(now *float64) (int, error)

Removes expired attachments and unreferenced blobs, the count of removed rows

func (*HostedRoomAttachmentStore) Put

func (s *HostedRoomAttachmentStore) Put(roomIDValue, uploadIDValue, kindValue, nameValue, mimeValue any, data []byte) (map[string]any, error)

Stores one upload's bytes deduplicated by content, an identical retry returning the original

func (*HostedRoomAttachmentStore) Read

func (s *HostedRoomAttachmentStore) Read(roomID, attachmentID, recipientMemberID, eventID any, viewer bool) (AttachmentData, error)

Verified bytes of a committed attachment the recipient or viewer may read

func (*HostedRoomAttachmentStore) ReadRange

func (s *HostedRoomAttachmentStore) ReadRange(roomID, attachmentID, recipientMemberID, eventID any, offset, length any) (AttachmentData, error)

One slice of a committed attachment under the same authorization as a whole read

func (*HostedRoomAttachmentStore) ReadViewer

func (s *HostedRoomAttachmentStore) ReadViewer(roomIDValue, attachmentIDValue, eventIDValue, recipientValue, gatewayValue, epochValue any) (AttachmentData, error)

Viewer read of a live hosted room, its authority fenced before and after the byte read

func (*HostedRoomAttachmentStore) ReconcileRoomEvents

func (s *HostedRoomAttachmentStore) ReconcileRoomEvents() (int64, error)

Recovers only the commitments a durable event payload names

type HostedRoomAuthorityRPC

type HostedRoomAuthorityRPC struct {
	Authority *SessionAuthority

	RoomID         string
	MemberID       string
	Profile        string
	Principal      Principal
	Authorizer     HostedAuthorizer
	AuthorizeWrite HostedWriteAuthorizer
	Timeout        time.Duration

	CreationID           string
	Ref                  SessionRef
	HostedAttachmentData *[]TransferredAttachment
	// contains filtered or unexported fields
}

Private hosted room producer of one room member profile binding over the canonical local session FIFO

func NewHostedRoomAuthorityRPC

func NewHostedRoomAuthorityRPC(authority *SessionAuthority, loop context.Context, roomID, memberID, profile string, principal Principal,
	authorize HostedAuthorizer, authorizeWrite HostedWriteAuthorizer) (*HostedRoomAuthorityRPC, error)

Producer for the binding whose canonical session identity derives from its room, member and profile

func (*HostedRoomAuthorityRPC) AcceptsAttachments

func (r *HostedRoomAuthorityRPC) AcceptsAttachments() bool

Every submit resolves event bound bytes for its member

func (*HostedRoomAuthorityRPC) Approve

func (r *HostedRoomAuthorityRPC) Approve(ctx context.Context, sessionID, requestID, choice string) (map[string]any, error)

func (*HostedRoomAuthorityRPC) Create

func (r *HostedRoomAuthorityRPC) Create(ctx context.Context, profile, title, source string) (map[string]any, error)

func (*HostedRoomAuthorityRPC) Discard

func (r *HostedRoomAuthorityRPC) Discard(ctx context.Context, profile, sessionID, source, expectedTaskID string, executionGeneration int64) (map[string]any, error)

Settles the expected task's unknown attempt of the hosted generation as cancelled

func (*HostedRoomAuthorityRPC) History

func (r *HostedRoomAuthorityRPC) History(ctx context.Context, profile, sessionID, source string) ([]map[string]any, error)

func (*HostedRoomAuthorityRPC) Info

func (r *HostedRoomAuthorityRPC) Info(ctx context.Context, profile, sessionID, source string) (map[string]any, error)

func (*HostedRoomAuthorityRPC) Interrupt

func (r *HostedRoomAuthorityRPC) Interrupt(ctx context.Context, profile, sessionID, source, expectedTaskID string) (map[string]any, error)

func (*HostedRoomAuthorityRPC) ResolveExact

func (r *HostedRoomAuthorityRPC) ResolveExact(ctx context.Context, profile, title, source string) (map[string]any, error)

func (*HostedRoomAuthorityRPC) Results

func (r *HostedRoomAuthorityRPC) Results(ctx context.Context, profile, sessionID, source string, admissionIDs []any) ([]map[string]any, error)

Terminal receipts of the session, narrowed to the given admission ids when any are named

func (*HostedRoomAuthorityRPC) Resume

func (r *HostedRoomAuthorityRPC) Resume(ctx context.Context, profile, sessionID, source string) (map[string]any, error)

func (*HostedRoomAuthorityRPC) Submit

func (r *HostedRoomAuthorityRPC) Submit(ctx context.Context, req HostedSubmit) (map[string]any, error)

Submits a turn of this producer's own member, a task for another member refused as the wrong producer

type HostedRoomBinding

type HostedRoomBinding struct {
	RoomID         string
	GatewayID      string
	AuthorityEpoch int64
}

Current server issued authority coordinate of one hosted room

type HostedRoomError

type HostedRoomError struct{ Msg string }

Invalid or conflicting hosted room operation, a ValueError

func (*HostedRoomError) Error

func (e *HostedRoomError) Error() string

type HostedRoomGrantError

type HostedRoomGrantError struct{ *HostedRoomPeerError }

Room scoped grant that is invalid or expired, a HostedRoomPeerError

func (*HostedRoomGrantError) Unwrap

func (e *HostedRoomGrantError) Unwrap() error

type HostedRoomOwnerRPC

type HostedRoomOwnerRPC struct {
	HostedRoomAuthorityRPC
	Home string
	// contains filtered or unexported fields
}

Driver compatible producer that forwards every operation to the member's owner process, carrying data only

func NewHostedRoomOwnerRPC

func NewHostedRoomOwnerRPC(ownerHome, sourceHome, roomID, memberID, profile string) *HostedRoomOwnerRPC

Producer forwarding to the owner at the home for the source room member and profile

type HostedRoomPeerClient

type HostedRoomPeerClient interface {
	Prepare(ctx context.Context, req PeerPrepare) (map[string]any, error)
	Dispatch(ctx context.Context, dispatch *jsonutil.Object, grant string) (map[string]any, error)
	History(ctx context.Context, roomID, profile, sessionID, grant string) ([]map[string]any, error)
	Status(ctx context.Context, roomID, profile, sessionID, grant string) (map[string]any, error)
	Stop(ctx context.Context, dispatch *jsonutil.Object, grant string) (map[string]any, error)
}

Authenticated client of a target gateway's narrow room member API

type HostedRoomPeerError

type HostedRoomPeerError struct{ Msg string }

Malformed or unauthorized peer room input

func (*HostedRoomPeerError) Error

func (e *HostedRoomPeerError) Error() string

type HostedRoomPolicyCheckpoint

type HostedRoomPolicyCheckpoint struct {
	DBPath          string
	MaxActiveEvents int64
	// contains filtered or unexported fields
}

Incremental room policy index that never compacts visible history

func NewHostedRoomPolicyCheckpoint

func NewHostedRoomPolicyCheckpoint(ctx context.Context, dbPath string, maxActiveEvents any) (*HostedRoomPolicyCheckpoint, error)

Checkpoint over dbPath whose replay capacity never drops below a capacity stored earlier

func (*HostedRoomPolicyCheckpoint) CompactCompleted

func (c *HostedRoomPolicyCheckpoint) CompactCompleted(ctx context.Context, roomID string) error

Drops completed projections an interrupted sync left behind

func (*HostedRoomPolicyCheckpoint) EventsForTask

func (c *HostedRoomPolicyCheckpoint) EventsForTask(ctx context.Context, roomID string, sourceEventSeq int64, inputContext any, taskID string) ([]map[string]any, error)

One bounded discussion projection for terminal reconstruction of a task

func (*HostedRoomPolicyCheckpoint) PublicationExists

func (c *HostedRoomPolicyCheckpoint) PublicationExists(ctx context.Context, roomID, taskID, status string, executionGeneration int64) (bool, error)

Whether one exact driver outcome is already in the room log

func (*HostedRoomPolicyCheckpoint) Snapshot

func (c *HostedRoomPolicyCheckpoint) Snapshot(ctx context.Context, roomID string, latestSeq int64) (PolicySnapshot, error)

Oldest active discussion of the room and its watermark set after a sync

func (*HostedRoomPolicyCheckpoint) Sync

func (c *HostedRoomPolicyCheckpoint) Sync(ctx context.Context, roomID string, latestSeq int64) (int64, error)

Materializes each unseen room event exactly once behind the durable cursor

type HostedRoomRPC

type HostedRoomRPC interface {
	Approve(ctx context.Context, sessionID, requestID, choice string) (map[string]any, error)
}

Session operations the service resolves approvals through

type HostedRoomRuntime

type HostedRoomRuntime struct {
	DBPath string
	RPC    InternalSessionRPC

	LeaseTTLSeconds            float64
	PollIntervalSeconds        float64
	ActivePollIntervalSeconds  float64
	TurnTimeoutSeconds         float64
	IndeterminateDeferSeconds  float64
	MaxConcurrentRooms         int
	UnavailableRetryMinSeconds float64
	UnavailableRetryMaxSeconds float64
	ProcessGeneration          string
	// contains filtered or unexported fields
}

Runs queued hosted room tasks independently of client connections

func NewHostedRoomRuntime

func NewHostedRoomRuntime(ctx context.Context, o HostedRoomRuntimeOptions) (*HostedRoomRuntime, error)

Validated room runtime over the options, a ValueError for a bound out of range

func (*HostedRoomRuntime) Cancel

func (r *HostedRoomRuntime) Cancel(identity TaskIdentity, cancelID string) (map[string]any, error)

Persists a stop intent, then commits cancellation after acknowledgement, rerouting lost races

func (*HostedRoomRuntime) RetryIndeterminate

func (r *HostedRoomRuntime) RetryIndeterminate(identity TaskIdentity, executionGeneration *int64) (map[string]any, error)

Retries one uncertain attempt under the current room lease, pinned to the selected generation

func (*HostedRoomRuntime) RunCycle

func (r *HostedRoomRuntime) RunCycle() error

Runs one scheduling pass, inline outside the supervisor and on bounded room workers inside it

func (*HostedRoomRuntime) Start

func (r *HostedRoomRuntime) Start()

Starts the bounded room worker supervisor once

func (*HostedRoomRuntime) Status

func (r *HostedRoomRuntime) Status() map[string]any

Transport neutral snapshot of runtime health

func (*HostedRoomRuntime) Stop

func (r *HostedRoomRuntime) Stop(timeout float64) bool

Requests a bounded clean stop without interrupting accepted turns, true when every worker ended

func (*HostedRoomRuntime) Wakeup

func (r *HostedRoomRuntime) Wakeup()

Wakes the worker after task admission or a room state change

type HostedRoomRuntimeOptions

type HostedRoomRuntimeOptions struct {
	DBPath                     string
	Rooms                      func() ([]HostedRoomBinding, error)
	TurnLock                   func(profile string) (release func(), err error)
	RPC                        InternalSessionRPC
	TransportResolver          MemberTransportResolver
	PrepareRoom                func(binding HostedRoomBinding) error
	PublishTerminal            func(binding HostedRoomBinding, task map[string]any) error
	PendingAction              func(roomID, memberID string, action map[string]any) error
	Clock                      func() float64
	LeaseTTLSeconds            float64
	PollIntervalSeconds        float64
	ActivePollIntervalSeconds  float64
	TurnTimeoutSeconds         float64
	IndeterminateDeferSeconds  float64
	MaxConcurrentRooms         int
	UnavailableRetryMinSeconds float64
	UnavailableRetryMaxSeconds float64
	ProcessGeneration          string
}

Construction arguments of a room runtime, the Python keyword defaults from the options constructor

func DefaultHostedRoomRuntimeOptions

func DefaultHostedRoomRuntimeOptions() HostedRoomRuntimeOptions

Runtime options carrying the keyword defaults of the room runtime

type HostedRoomService

type HostedRoomService struct {
	DBPath           string
	DiscussionLimits DiscussionLimits

	PolicyCheckpoint *HostedRoomPolicyCheckpoint
	RPC              HostedRoomRPC
	// contains filtered or unexported fields
}

Owns the hosted Discussion policy and its transport free worker

func NewHostedRoomService

func NewHostedRoomService(ctx context.Context, o HostedRoomServiceOptions) (*HostedRoomService, error)

Hosted room service over the server's session handlers

func (*HostedRoomService) ApproveRoomTask

func (s *HostedRoomService) ApproveRoomTask(roomID, memberID, taskID string, executionGeneration int64, choice string, requestID *string) (map[string]any, error)

Resolves one exact local or peer approval and wakes room observation

func (*HostedRoomService) Bindings

func (s *HostedRoomService) Bindings() ([]HostedRoomBinding, error)

Rooms this gateway holds authority over

func (*HostedRoomService) ContinueRoom

func (s *HostedRoomService) ContinueRoom(roomID, discussionEventID string) (map[string]any, error)

Grants a discussion paused at its cap one more budget of rounds and messages, answering the event that records it

func (*HostedRoomService) CreateRoom

func (s *HostedRoomService) CreateRoom(roomID, name string, members any, admit func(conn state.SQLiteConn) error) (map[string]any, error)

Creates a room over a validated roster under this gateway's authority

func (*HostedRoomService) LocalProfiles

func (s *HostedRoomService) LocalProfiles() ([]string, error)

Default profile plus every named profile with an identity and no tombstone

func (*HostedRoomService) OwnedAuthority

func (s *HostedRoomService) OwnedAuthority(roomID string) (string, int64, error)

Gateway id and epoch of a room this service's gateway holds authority for

func (*HostedRoomService) PrepareRoom

func (s *HostedRoomService) PrepareRoom(binding HostedRoomBinding) error

Publishes terminal tasks, then admits the next Discussion turn or records the room's settled status

func (*HostedRoomService) PublishTerminal

func (s *HostedRoomService) PublishTerminal(binding HostedRoomBinding, _ map[string]any) error

Publishes a terminal task by preparing its room again, then wakes the worker

func (*HostedRoomService) RegisterPeerRoute

func (s *HostedRoomService) RegisterPeerRoute(roomID, memberID string, route PeerMemberRoute, client HostedRoomPeerClient, targetURL *string, catalog *GatewayRoomCatalog) error

Registers one verified route, persisting its scoped grant when a catalog and URL are given

func (*HostedRoomService) ResolveMemberTransport

func (s *HostedRoomService) ResolveMemberTransport(binding HostedRoomBinding, task map[string]any) (InternalSessionRPC, error)

Transport of a member turn, the in process RPC for local members and a tracked peer route otherwise

func (*HostedRoomService) RetryRoomTask

func (s *HostedRoomService) RetryRoomTask(roomID, taskID string, memberID *string, executionGeneration *int64) (map[string]any, error)

Retries one uncertain or deferred task, or a stalled room's preparation, after explicit user action

func (*HostedRoomService) RevokeRoomRoutes

func (s *HostedRoomService) RevokeRoomRoutes(roomID string) (int, error)

Revokes and forgets every scoped peer route of one room, an unreachable target leaving it for retry

func (*HostedRoomService) RoomProfiles

func (s *HostedRoomService) RoomProfiles(map[string]any) ([]string, error)

Profiles a saved room's roster is checked against

func (*HostedRoomService) RoomRecord

func (s *HostedRoomService) RoomRecord(roomID string) (map[string]any, error)

Live room record of the service store

func (*HostedRoomService) Root

func (s *HostedRoomService) Root() string

Directory holding the room store

func (*HostedRoomService) Runtime

func (s *HostedRoomService) Runtime() *HostedRoomRuntime

Room worker of the service

func (*HostedRoomService) RuntimeStatus

func (s *HostedRoomService) RuntimeStatus() map[string]any

Status snapshot of the room worker

func (*HostedRoomService) Send

func (s *HostedRoomService) Send(roomID, eventID string, payload any) (map[string]any, error)

Stores one message of the local user, then prepares the room

func (*HostedRoomService) SendAs

func (s *HostedRoomService) SendAs(roomID, eventID string, payload any, actor map[string]any) (map[string]any, error)

Stores one user message under the actor, then prepares the room, a later preparation failure left to the driver

func (*HostedRoomService) Start

func (s *HostedRoomService) Start() error

func (*HostedRoomService) Status

func (s *HostedRoomService) Status(roomID *string) (map[string]any, error)

Runtime health with peer routes, or one room's working, blocked and pending action view

func (*HostedRoomService) Stop

func (s *HostedRoomService) Stop(timeout float64) bool

func (*HostedRoomService) StopRoom

func (s *HostedRoomService) StopRoom(roomID, cancelID string, requireAcknowledged bool) (int, error)

Fences the room's earlier turns and cancels every stoppable task, the count of tasks it touched

func (*HostedRoomService) StorePath

func (s *HostedRoomService) StorePath() string

Room state database the service drives

func (*HostedRoomService) TurnLock

func (s *HostedRoomService) TurnLock(profile string) (func(), error)

Cross process turn lock of the profile under the room root

func (*HostedRoomService) Wakeup

func (s *HostedRoomService) Wakeup()

type HostedRoomServiceOptions

type HostedRoomServiceOptions struct {
	DBPath      string
	MakeRPC     func(dbPath string) (HostedRoomRPC, error)
	PeerRoutes  map[[2]string]PeerMemberRoute
	PeerClients map[any]HostedRoomPeerClient
}

Construction arguments of a hosted room service

type HostedSubmit

type HostedSubmit struct {
	Profile             string
	SessionID           string
	Prompt              string
	Source              string
	Task                TaskIdentity
	ExecutionGeneration int64
	OnTerminal          func(receipt map[string]any) error
	MemberID            *string
	Attachments         []any
}

One fenced turn handed to a member transport, its terminal result reported through the callback

type HostedWriteAuthorizer

type HostedWriteAuthorizer func(ctx context.Context, conn state.SQLiteConn, task TaskIdentity, generation int64) error

Check of a submit inside the FIFO writer's transaction, raising to refuse

type IdentityUnresolved

type IdentityUnresolved struct{ Reason string }

Under multiplexing the event's runtime profile could not be established, the caller drops the event

func (*IdentityUnresolved) Error

func (e *IdentityUnresolved) Error() string

type ImageRef

type ImageRef struct {
	URL string
	Alt string
}

One image URL found in a response with its alt text

func ExtractImages

func ExtractImages(content string) ([]ImageRef, string)

Markdown images whose URL looks like an image and every HTML img URL, with only those tags removed from the text

type InternalSessionRPC

type InternalSessionRPC interface {
	AcceptsAttachments() bool
	ResolveExact(ctx context.Context, profile, title, source string) (map[string]any, error)
	Create(ctx context.Context, profile, title, source string) (map[string]any, error)
	Resume(ctx context.Context, profile, sessionID, source string) (map[string]any, error)
	Submit(ctx context.Context, req HostedSubmit) (map[string]any, error)
	History(ctx context.Context, profile, sessionID, source string) ([]map[string]any, error)
	Info(ctx context.Context, profile, sessionID, source string) (map[string]any, error)
	Interrupt(ctx context.Context, profile, sessionID, source, expectedTaskID string) (map[string]any, error)
}

Normalized session operations the room driver drives in process or over a peer route

type InternalSessionTurnRunner

type InternalSessionTurnRunner interface {
	RunInternalSessionTurn(ctx context.Context, sessionID, text, profile, notificationCategory string) error
}

Stateless adapter that runs a served profile's session turn in process

type InterruptEvent

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

Settable flag goroutines wait on, the asyncio Event of a session's interrupt signal

func NewInterruptEvent

func NewInterruptEvent() *InterruptEvent

Unset event

func (*InterruptEvent) Clear

func (e *InterruptEvent) Clear()

Resets the flag so later waiters block again

func (*InterruptEvent) Done

func (e *InterruptEvent) Done() <-chan struct{}

Channel closed once the flag is set

func (*InterruptEvent) IsSet

func (e *InterruptEvent) IsSet() bool

Whether the flag is set

func (*InterruptEvent) RunGeneration

func (e *InterruptEvent) RunGeneration() any

Run generation the agent cache bound to this turn's interrupt event, nil when none was bound

func (*InterruptEvent) Set

func (e *InterruptEvent) Set()

Sets the flag and wakes every waiter

func (*InterruptEvent) SetRunGeneration

func (e *InterruptEvent) SetRunGeneration(generation int)

Binds the run generation of the turn this interrupt event belongs to

type InterruptWatch

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

Ctrl-C observer of a polling wizard step, the signal turned into ErrKeyboardInterrupt at the next sleep or check

func WatchInterrupt

func WatchInterrupt() *InterruptWatch

Starts observing Ctrl-C until Stop

func (*InterruptWatch) Check

func (w *InterruptWatch) Check() error

ErrKeyboardInterrupt when Ctrl-C arrived since the last check

func (*InterruptWatch) Sleep

func (w *InterruptWatch) Sleep(seconds float64) error

Sleeps the seconds, cut short by ErrKeyboardInterrupt when Ctrl-C arrives first

func (*InterruptWatch) Stop

func (w *InterruptWatch) Stop()

Stops observing Ctrl-C

type InvalidStatusError

type InvalidStatusError = websocketutil.HandshakeError

InvalidStatusError is the websockets InvalidStatus of a handshake the server answered with a non 101 HTTP status

type InvalidStoredWorkRecord

type InvalidStoredWorkRecord struct{ *WorkRecordError }

Retained evidence bytes that cannot be reused

func (*InvalidStoredWorkRecord) Unwrap

func (e *InvalidStoredWorkRecord) Unwrap() error

type InvalidTaskTransitionError

type InvalidTaskTransitionError struct{ *DriverStateError }

Requested task transition that is not allowed

func (*InvalidTaskTransitionError) Unwrap

func (e *InvalidTaskTransitionError) Unwrap() error

type LaunchdExitTimeoutQuery

type LaunchdExitTimeoutQuery struct {
	Label    string
	Environ  map[string]string
	UID      *int
	Run      func(argv []string, timeout time.Duration) (stdout string, returncode int, err error)
	Platform string
}

Inputs of ReadLaunchdExitTimeoutS, zero values select the live process defaults

type LeaseHeldError

type LeaseHeldError struct{ *DriverStateError }

Room lease another unexpired driver generation owns

func (*LeaseHeldError) Unwrap

func (e *LeaseHeldError) Unwrap() error

type LeaseReleaser

type LeaseReleaser interface{ Release() error }

Lease or marker whose release the single ordered worker runs

type LedgerTarget

type LedgerTarget struct {
	Platform    string
	Profile     string
	NullProfile bool
}

Platform and adapter identity a multiplexed boot can send on, NullProfile for a legacy row without one

type LegacyLauncherArtifact

type LegacyLauncherArtifact struct {
	Kind   string
	Label  string
	Target string
}

Pre suffix launcher of this home, a file or a task, with its label

func LegacyLauncherArtifacts

func LegacyLauncherArtifacts(ctx context.Context) ([]LegacyLauncherArtifact, error)

Every pre suffix launcher of this home still present, empty when this home owns the bare name

type ListenOptions

type ListenOptions struct {
	ReuseAddress *bool
	AccessLog    AccessLog
}

Bind options of a listener, the asyncio reuse address default when nil

type ListenerState

type ListenerState struct {
	BoundHost string
}

Bound host of the session listener the boundary checks read

type LiveSession

type LiveSession struct {
	Source      *SessionSource
	Route       string
	EventStream *SessionEvents

	Rescan      bool
	Settling    map[string]*jsonutil.Object
	RetireTimer *time.Timer
	Subscribers map[string]Principal
	Detaching   int
	ClosedStamp *closedStamp
	ReviewRun   reviewRun
	ReviewLock  sync.Mutex

	PauseNotified bool
	ReaskPick     bool
	// Principal and level of a reasoning command that arrived while a turn ran
	PendingReasoning *pendingReasoning
	// Model a one turn switch replaced, put back at the boundary after that turn
	OnceRestore      *onceRestore
	CompressionCount int

	// Control card publish tickets and the revision last painted, guarded by ControlMu
	ControlMu           sync.Mutex
	ControlSeq          int
	ControlPublishedSeq int
	ControlRevision     string
	// contains filtered or unexported fields
}

One gateway owned live session with its route, event stream and drain state

func LocalLive

func LocalLive(runner any, source *SessionSource) *LiveSession

Live local session the source addresses, nil for every other route

func LocalLiveForRoute

func LocalLiveForRoute(runner any, sessionKey string) *LiveSession

Local live session whose route is the session key, nil when none is

func NewLiveSession

func NewLiveSession(source *SessionSource, route string) *LiveSession

Live session on a route with a fresh event stream

func (*LiveSession) SnapshotControls

func (l *LiveSession) SnapshotControls(sessionID string, generation int64) []map[string]any

Pending control prompts of the session for the generation, the controls snapshot viewers replay

type LiveSessionView

type LiveSessionView struct {
	SessionID  string
	Live       *LiveSession
	Subscribed bool
}

Live session of an authority with whether a viewer was subscribed when the snapshot was taken

type LiveTurnRunner

type LiveTurnRunner interface {
	IsSessionRunning(route string) bool
	HasPendingSlashConfirm(route string) bool
	UpdatePromptPending(route string) bool
	HMPendingReplyIntercepts(ctx context.Context, event *MessageEvent, source *SessionSource, sessionKey string) (*string, error)
	RoutePlaintextApprovalWhileBusy(ctx context.Context, event *MessageEvent, sessionKey string) bool
	HMBusyPreempt(ctx context.Context, event *MessageEvent, source *SessionSource, sessionKey string) (bool, error)
}

Runner seams a producer delivery answers or redirects the chat's running turn through, run_inbound _hm_pending_reply_intercepts and _hm_busy_preempt and run_busy_steer _route_plaintext_approval_while_busy

type LivenessOptions

type LivenessOptions struct {
	ProfileDir      string
	Runtime         *jsonutil.Object
	RuntimeGiven    bool
	HealthProbe     func() (bool, *jsonutil.Object, error)
	NoCache         bool
	PidProbe        func(pidPath string) (int, bool, error)
	RuntimeReader   func(path string) (*jsonutil.Object, error)
	RuntimePidProbe func(runtime *jsonutil.Object, expectedHome string) (int, bool, error)
}

Ladder options, ProfileDir scoping every read and the probes replacing the default rungs

type LocalBot

type LocalBot struct {
	Name      string
	Home      string
	Authority *SessionAuthority
	Problem   *string
	Retiring  bool
}

One local bot this process serves under its profile name, home and owning authority

func LocalBots

func LocalBots(runner any) []LocalBot

Local bots this gateway serves, one per built authority, flagged when clients cannot address one by name

type LocalSessionAdapter

type LocalSessionAdapter struct {
	*BasePlatformAdapter
	Authority *SessionAuthority
	Policies  map[string]*LocalSessionPolicy
	// contains filtered or unexported fields
}

Local platform adapter whose delivery stays in the canonical event stream of its authority

func NewLocalSessionAdapter

func NewLocalSessionAdapter(a *SessionAuthority) *LocalSessionAdapter

Adapter holding the admission sources and frozen policies of one authority's local sessions

func (*LocalSessionAdapter) Connect

func (l *LocalSessionAdapter) Connect(ctx context.Context, isReconnect bool) (bool, error)

Always connected, the local transport has no remote endpoint

func (*LocalSessionAdapter) Disconnect

func (l *LocalSessionAdapter) Disconnect(ctx context.Context) error

Forgets every registered admission source

func (*LocalSessionAdapter) EditMessage

func (l *LocalSessionAdapter) EditMessage(ctx context.Context, chatID, messageID, content string, finalize bool) (SendResult, error)

Acknowledges an edit under the same message id

func (*LocalSessionAdapter) GetChatInfo

func (l *LocalSessionAdapter) GetChatInfo(ctx context.Context, chatID string) (map[string]any, error)

Chat info of a local chat, always a direct message

func (*LocalSessionAdapter) RecordDeliveryObligation

func (l *LocalSessionAdapter) RecordDeliveryObligation(ctx context.Context, event *MessageEvent, sessionKey, textContent string, deliveryAdapter PlatformAdapter, isEphemeral bool) *string

Ledgers nothing, viewers replay the durable transcript and no platform acknowledgement can be lost

func (*LocalSessionAdapter) Send

func (l *LocalSessionAdapter) Send(ctx context.Context, chatID, content, replyTo string, metadata map[string]any) (SendResult, error)

Acknowledges a send with a fresh message id, the turn runner already published the deltas and settlement

func (*LocalSessionAdapter) SendClarify

func (l *LocalSessionAdapter) SendClarify(ctx context.Context, chatID, question string, choices []string, clarifyID, sessionKey string, metadata map[string]any) (SendResult, error)

Asks a clarifying question with the base prompt, declining at once when nobody can answer it

func (*LocalSessionAdapter) SendExecApproval

func (l *LocalSessionAdapter) SendExecApproval(ctx context.Context, chatID, command, sessionKey string, description *string, metadata map[string]any, allowPermanent, allowSession, smartDenied bool, requestID *string) (SendResult, error)

Acknowledges an approval prompt so the pending controls rendering path is selected without a text fallback

func (*LocalSessionAdapter) SendTyping

func (l *LocalSessionAdapter) SendTyping(ctx context.Context, chatID string, metadata map[string]any) error

Sends no typing indicator

type LocalSessionPolicy

type LocalSessionPolicy struct {
	Source             string
	Platform           string
	Cwd                string
	Model              *string
	Toolsets           []string
	ConfigJSON         string
	RequestJSON        string
	TerminalJSON       string
	CredentialRef      *string
	ConfigSecretRef    *string
	EditorMCPJSON      *string
	KanbanJSON         *string
	SafeMode           bool
	IgnoreUserConfig   bool
	SkillsPrompt       *string
	CodingPosture      bool
	ClientEnvJSON      *string
	ClientEnvRemote    bool
	ClientEnvRulesJSON *string
	EditApprovalPolicy string
}

Frozen launch policy of one local session as its committed private JSON fields

func BindLaunchKey

func BindLaunchKey(ctx context.Context, a *SessionAuthority, sid string, policy *LocalSessionPolicy, apiKey *string, configSecrets *RecoveredSecrets) (*LocalSessionPolicy, error)

BindLaunchKey binds a launch key and frozen config secrets in the authority lifetime only

func BuildPolicy

func BuildPolicy(ctx context.Context, params, cfg map[string]any, privateSecrets *RecoveredSecrets) (*LocalSessionPolicy, error)

BuildPolicy freezes launch params over the profile config, the config secrets it strips gathered into privateSecrets

func BypassLaunchPolicy

func BypassLaunchPolicy(ctx context.Context, params map[string]any) (*LocalSessionPolicy, error)

Frozen policy of a bypass launch from its session.create parameters, code defaults and never the profile

func LocalPolicy

func LocalPolicy(ctx context.Context, runner AuthorityRunner, source *SessionSource) (*LocalSessionPolicy, error)

Frozen policy of a local session, nil for a messaging chat

func LocalPolicyForSource

func LocalPolicyForSource(ctx context.Context, runner AuthorityRunner, source *SessionSource) (*LocalSessionPolicy, error)

Frozen policy of a local source its adapter admits, nil for other routes

func RestorePolicy

func RestorePolicy(raw any) (*LocalSessionPolicy, error)

Stored private policy of a bootstrap frame, the storage_unavailable refusal of an incomplete one

func SessionPolicyForSource

func SessionPolicyForSource(ctx context.Context, runner AuthorityRunner, source *SessionSource) (*LocalSessionPolicy, error)

Frozen launch policy of a local source its adapter admits, nil for other routes

func (*LocalSessionPolicy) AsDict

func (p *LocalSessionPolicy) AsDict() map[string]any

Stored field dict of the policy as a receipt holds it

func (*LocalSessionPolicy) BaseURL

func (p *LocalSessionPolicy) BaseURL() any

Frozen model base URL

func (*LocalSessionPolicy) CheckpointsEnabled

func (p *LocalSessionPolicy) CheckpointsEnabled() bool

Frozen checkpoints enabled flag

func (*LocalSessionPolicy) ClientEnv

func (p *LocalSessionPolicy) ClientEnv() map[string]any

Shell launched client environment bound for this session, nil when the client sent none

func (*LocalSessionPolicy) ClientEnvScope

func (p *LocalSessionPolicy) ClientEnvScope(ctx context.Context) (context.Context, error)

Context binding the session's client environment under the rules it was normalised by

func (*LocalSessionPolicy) CurrentModel

func (p *LocalSessionPolicy) CurrentModel(ctx context.Context, a *SessionAuthority) (*string, error)

Model the session's next turn runs, the profile's current default when following

func (*LocalSessionPolicy) CurrentReasoningConfig

func (p *LocalSessionPolicy) CurrentReasoningConfig(ctx context.Context, runner any, sessionKey string) (map[string]any, error)

Next turn reasoning, a typed session override, the profile current effort when following, else the frozen one

func (*LocalSessionPolicy) CurrentServiceTier

func (p *LocalSessionPolicy) CurrentServiceTier(ctx context.Context, runner any, sessionKey string) (*string, error)

Next turn tier, a typed session /fast, else the policy tier frozen or followed from the profile

func (*LocalSessionPolicy) CurrentToolsets

func (p *LocalSessionPolicy) CurrentToolsets(ctx context.Context, cfg map[string]any) ([]string, error)

Next turn's toolsets from its resolved config, the profile's current pick when following

func (*LocalSessionPolicy) EffectiveFor

func (p *LocalSessionPolicy) EffectiveFor(ctx context.Context, authority *SessionAuthority, secrets bool) (map[string]any, *string, error)

Next turn's config and model of the policy as the given authority reads them, secrets recovered when asked

func (*LocalSessionPolicy) FollowsProfile

func (p *LocalSessionPolicy) FollowsProfile() bool

Whether the session re-reads its owning profile config each turn

func (*LocalSessionPolicy) IgnoreRules

func (p *LocalSessionPolicy) IgnoreRules() bool

Whether project rule files are skipped, always under safe mode

func (*LocalSessionPolicy) MaxTurns

func (p *LocalSessionPolicy) MaxTurns() int

Frozen iteration cap from agent max_turns

func (*LocalSessionPolicy) PassSessionID

func (p *LocalSessionPolicy) PassSessionID() bool

Whether the session id rides the agent system prompt

func (*LocalSessionPolicy) PolicyCwd

func (p *LocalSessionPolicy) PolicyCwd() string

Host cwd the policy turn runs in

func (*LocalSessionPolicy) PolicyPlatform

func (p *LocalSessionPolicy) PolicyPlatform() string

Platform label the policy turn runs on

func (*LocalSessionPolicy) Provider

func (p *LocalSessionPolicy) Provider() any

Frozen model provider

func (*LocalSessionPolicy) ReasoningConfig

func (p *LocalSessionPolicy) ReasoningConfig() map[string]any

Frozen reasoning config for the frozen model

func (*LocalSessionPolicy) RunBudgetSeconds

func (p *LocalSessionPolicy) RunBudgetSeconds(ctx context.Context) (*float64, error)

Frozen run budget seconds of the policy, nil for no budget

func (*LocalSessionPolicy) Verbose

func (p *LocalSessionPolicy) Verbose() bool

Whether the session agent runs with quiet mode off so status lines reach the viewer

func (*LocalSessionPolicy) Yolo

func (p *LocalSessionPolicy) Yolo() bool

Whether this session bypasses dangerous command approvals like a chat scoped yolo

type LongMessageSplitter

type LongMessageSplitter interface {
	SplitsLongMessages() bool
}

LongMessageSplitter reports whether an adapter chunks long messages natively

type LongToolHint

type LongToolHint struct {
	ToolName string
	Duration float64
}

LongToolHint flags a long running tool for the verbose capability hint

type LoopExceptionContext

type LoopExceptionContext struct {
	Message   string
	Exception error
	// Name of the task or callback that failed, empty when unknown
	Task string
	// Python repr of the failed callback and of its handle, empty when the failure names none
	Callback, Handle string
}

What a loop exception handler receives, the asyncio handler context of a failed callback or task

type LoopExceptionHandler

type LoopExceptionHandler func(loop *CallbackLoop, c LoopExceptionContext)

Handler a loop routes every callback failure to, the asyncio loop exception handler

type LoopFloorTimerHandle

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

Self rescheduling no op loop timer that keeps one timer pending so selector waits stay bounded

func ArmLoopFloorTimer

func ArmLoopFloorTimer(loop EventLoop, interval any) (*LoopFloorTimerHandle, error)

Arms the floor timer, a non positive or uncoercible interval taking the 5 second default

func (*LoopFloorTimerHandle) Cancel

func (h *LoopFloorTimerHandle) Cancel()

Stops rescheduling and cancels the pending timer

type LoopHeartbeatOptions

type LoopHeartbeatOptions struct {
	IntervalS      any
	StartTime      *float64
	Home           string
	ShouldContinue func() bool
}

Keyword options of the heartbeat task, a nil IntervalS taking the 30 second default

type LoopLivenessOptions

type LoopLivenessOptions struct {
	StaleAfterS  *float64
	Home         string
	TickTimeoutS float64
	TickStrikes  *int
	TickGapS     *float64
}

Knobs of the loop liveness probe, zero values select the Python defaults

type LoopLivenessWatchdogHandle

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

Stop, join and liveness of a running loop liveness watchdog

func StartLoopLivenessWatchdog

func StartLoopLivenessWatchdog(ctx context.Context, loop EventLoop, probeInterval, probeTimeout float64, maxStrikes, exitCode int) *LoopLivenessWatchdogHandle

Out of loop watchdog that dumps stacks and hard exits after maxStrikes consecutive missed loop probes

func (*LoopLivenessWatchdogHandle) IsAlive

func (h *LoopLivenessWatchdogHandle) IsAlive() bool

func (*LoopLivenessWatchdogHandle) Join

func (h *LoopLivenessWatchdogHandle) Join(timeoutS *float64)

Waits for the watchdog to end, at most timeoutS seconds when it is set

func (*LoopLivenessWatchdogHandle) Stop

func (h *LoopLivenessWatchdogHandle) Stop()

type LoopTimer

type LoopTimer interface {
	Cancel()
}

Pending loop timer that can be cancelled before its callback runs

type MSGraphWebhookAdapter

type MSGraphWebhookAdapter struct {
	*BasePlatformAdapter
	// contains filtered or unexported fields
}

MSGraphWebhookAdapter receives Microsoft Graph change notifications and surfaces them internally

func NewMSGraphWebhookAdapter

func NewMSGraphWebhookAdapter(config *PlatformConfig) (*MSGraphWebhookAdapter, error)

Adapter for a Graph webhook platform config, the ValueError of a malformed port or limit

func (*MSGraphWebhookAdapter) AdapterAttr

func (a *MSGraphWebhookAdapter) AdapterAttr(name string) any

Python attribute of the adapter by name, the client state secret as its token

func (*MSGraphWebhookAdapter) ClearSeenReceipts

func (a *MSGraphWebhookAdapter) ClearSeenReceipts()

Forgets every remembered notification receipt

func (*MSGraphWebhookAdapter) Connect

func (a *MSGraphWebhookAdapter) Connect(ctx context.Context, isReconnect bool) (bool, error)

Starts the webhook listener, false without a client state or with a public bind lacking an allowlist

func (*MSGraphWebhookAdapter) Disconnect

func (a *MSGraphWebhookAdapter) Disconnect(ctx context.Context) error

Stops the listener and marks the adapter disconnected

func (*MSGraphWebhookAdapter) GetChatInfo

func (a *MSGraphWebhookAdapter) GetChatInfo(ctx context.Context, chatID string) (map[string]any, error)

Chat info of a webhook subscription chat

func (*MSGraphWebhookAdapter) ListenHost

func (a *MSGraphWebhookAdapter) ListenHost() *string

Bound host, nil for the dual stack default

func (*MSGraphWebhookAdapter) ListenPort

func (a *MSGraphWebhookAdapter) ListenPort() int

Configured listen port

func (*MSGraphWebhookAdapter) Runner

func (a *MSGraphWebhookAdapter) Runner() *HTTPAppRunner

Running listener, nil before connect or in shared listener mode

func (*MSGraphWebhookAdapter) Send

func (a *MSGraphWebhookAdapter) Send(ctx context.Context, chatID, content, replyTo string, metadata map[string]any) (SendResult, error)

Logs the response the internal turn produced, Graph has no reply channel

func (*MSGraphWebhookAdapter) SetAllowedSourceNetworks

func (a *MSGraphWebhookAdapter) SetAllowedSourceNetworks(networks []netip.Prefix)

Replaces the source allowlist

func (*MSGraphWebhookAdapter) SetNotificationScheduler

func (a *MSGraphWebhookAdapter) SetNotificationScheduler(scheduler NotificationScheduler)

Installs the plugin owned notification pipeline, nil returning ingress to gateway inference

func (*MSGraphWebhookAdapter) WebhookPath

func (a *MSGraphWebhookAdapter) WebhookPath() string

Webhook callback route path

type MailboxUnusable

type MailboxUnusable struct{ Msg string }

Mailbox directory this token cannot list, create or lock inside, a permission error

func (*MailboxUnusable) Error

func (e *MailboxUnusable) Error() string

func (*MailboxUnusable) Unwrap

func (e *MailboxUnusable) Unwrap() error

type ManagedExecutionUnknown

type ManagedExecutionUnknown struct{ Message string }

Committed unknown verdict that stops the FIFO without forging a failed settlement

func (*ManagedExecutionUnknown) Error

func (e *ManagedExecutionUnknown) Error() string

type MediaDeliveryScopeRunner

type MediaDeliveryScopeRunner interface {
	MediaDeliveryScopeForSource(ctx context.Context, source *SessionSource) (context.Context, func(), error)
}

Runner seam resolving the routed home and terminal policy scope of post handler delivery

type MediaRef

type MediaRef struct {
	Path    string
	IsVoice bool
}

Media path of a response and whether it goes out as a voice message

func ExtractMedia

func ExtractMedia(ctx context.Context, content string) ([]MediaRef, string, error)

Media tags of the content and the content with them and the delivery markers removed

func FilterMediaDeliveryPaths

func FilterMediaDeliveryPaths(ctx context.Context, media []MediaRef) ([]MediaRef, error)

Safe MEDIA paths of a response with their voice flags, unsafe ones logged and dropped

type MemberTransportResolver

type MemberTransportResolver func(binding HostedRoomBinding, task map[string]any) (InternalSessionRPC, error)

Transport of one member turn of a bound room

type MentionPatternOptions

type MentionPatternOptions struct {
	LogPrefix     string
	PlatformLabel *string
	DisplayLabel  string
	Defaults      []string
	Logger        *slog.Logger
}

How a mention pattern list is read, config style naming the platform and wakeword style giving defaults

type MessageChunk

type MessageChunk struct {
	Text string
}

MessageChunk is one text delta of the assistant reply

type MessageDeduplicator

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

TTL bounded cache of seen message ids that also caps its size under load

func NewMessageDeduplicator

func NewMessageDeduplicator(maxSize int, ttlSeconds float64) *MessageDeduplicator

Empty cache keeping at most maxSize ids for ttlSeconds each

func (*MessageDeduplicator) Absorb

func (d *MessageDeduplicator) Absorb(other *MessageDeduplicator)

Adopts the other cache's still live ids at their original seen times

func (*MessageDeduplicator) Clear

func (d *MessageDeduplicator) Clear()

Forgets every id

func (*MessageDeduplicator) Contains

func (d *MessageDeduplicator) Contains(msgID string) bool

Whether the id is live in the cache without inserting it, an expired id being dropped

func (*MessageDeduplicator) Discard

func (d *MessageDeduplicator) Discard(msgID string)

Releases a claimed id after a cancelled or failed handoff

func (*MessageDeduplicator) IsDuplicate

func (d *MessageDeduplicator) IsDuplicate(msgID string) bool

True when the id was already seen inside the window, otherwise records it and trims the cache

type MessageDeleter

type MessageDeleter interface {
	DeleteMessage(ctx context.Context, chatID, messageID string) (bool, error)
}

Adapter that can delete a sent message, the base reporting false

type MessageEvent

type MessageEvent struct {
	Text                string
	MessageType         MessageType
	UserID              *string
	UserName            *string
	Source              *SessionSource
	RawMessage          any
	MessageID           *string
	LedgerMessageID     *string
	ReplyAnchorOverride *string
	PlatformUpdateID    *int64
	MediaURLs           []string
	MediaTypes          []string
	MediaTextInlined    []*bool
	ReplyToMessageID    *string
	ReplyToText         *string
	ReplyToAuthorID     *string
	ReplyToAuthorName   *string
	ReplyToIsOwnMessage bool
	PromptResponse      map[string]any
	AutoSkill           any
	ChannelPrompt       *string
	ChannelContext      *string
	Internal            bool
	Metadata            map[string]any
	Timestamp           time.Time
	AllowGatewayControl bool
	ReplyExpected       *bool
	InheritChannelPin   bool
	EditRevision        *string
	MediaFilenames      []string
	// Replay of an inbound message the startup restore queued, never queued again
	StartupRestoreReplay bool
	// Batch opened by a tagged bot whose continuation chunks wait the split delay
	BotTagDebounce bool

	OnCommit func()
	// contains filtered or unexported fields
}

func NewMessageEvent

func NewMessageEvent(text string) *MessageEvent

Event with the dataclass defaults for every field the caller leaves unset

func ReplaceMessageEventText

func ReplaceMessageEventText(event *MessageEvent, text string) *MessageEvent

Copy of the event with only its dataclass fields and new text, sharing the same source as dataclasses replace does

func RestoreNative

func RestoreNative(ctx context.Context, payload *jsonutil.Object, runner AuthorityRunner) (*MessageEvent, error)

Event rebuilt from a native envelope payload with its seal checked against the live connector

func (*MessageEvent) AbsorbReplyExpected

func (e *MessageEvent) AbsorbReplyExpected(other *MessageEvent)

Takes the other event's reply expectation unless this one is addressed or the other is not under the caller's lock

func (*MessageEvent) AdmittedBeforeDrain

func (e *MessageEvent) AdmittedBeforeDrain() bool

Whether the event is a wake its producer admitted before the drain began

func (*MessageEvent) BotLoopAdmitted

func (e *MessageEvent) BotLoopAdmitted() bool

Whether a busy follow up already spent its bot loop budget on the busy path

func (*MessageEvent) ClaimedOwner

func (e *MessageEvent) ClaimedOwner() (sessionID string, generation int64, ok bool)

Claim the executing turn was admitted under, nil for an internal, API or local turn

func (*MessageEvent) ClearGatewayActiveTurnMarker

func (e *MessageEvent) ClearGatewayActiveTurnMarker()

Drops both durable active turn marker attributes from the event

func (*MessageEvent) ConsumerReply

func (e *MessageEvent) ConsumerReply() *string

Consumer reply a post admission plugin or the chat's in flight work handed back for the caller's own reply leg

func (*MessageEvent) ExtendMedia

func (e *MessageEvent) ExtendMedia(other *MessageEvent)

Appends the other event's attachments keeping each original name aligned with its attachment

func (*MessageEvent) FIFOOnly

func (e *MessageEvent) FIFOOnly() (bool, int)

Whether the event is a command produced turn that only the authority FIFO may run, and its stop epoch

func (*MessageEvent) GatewayAccepted

func (e *MessageEvent) GatewayAccepted() bool

Whether the event was accepted into a turn or a pending slot by the last admission

func (*MessageEvent) GatewayActiveTurnSessionKey

func (e *MessageEvent) GatewayActiveTurnSessionKey() *string

Routing key the durable active turn marker was written under, nil when the event holds no marker

func (*MessageEvent) GatewayActiveTurnToken

func (e *MessageEvent) GatewayActiveTurnToken() any

Durable active turn token the runner stamped on admission, nil when none

func (*MessageEvent) GatewayMarkerReleased

func (e *MessageEvent) GatewayMarkerReleased() *InterruptEvent

Event an adopter waits on until this turn released its crash marker, nil when none

func (*MessageEvent) GatewayTurnRefusal

func (e *MessageEvent) GatewayTurnRefusal() *string

Refusal a local turn answers with after its context references were refused, nil when none

func (*MessageEvent) GetCommand

func (e *MessageEvent) GetCommand() (string, bool)

Lowercase command name without the bot suffix, false when not a command or the name holds a slash

func (*MessageEvent) GetCommandArgs

func (e *MessageEvent) GetCommandArgs() string

Arguments after the command with em and en dashes turned back into ASCII flags

func (*MessageEvent) GuardReplyFields

func (e *MessageEvent) GuardReplyFields(guard sync.Locker)

Binds the lock of the running turn that owns the reply fields, the first binding kept for the event's life

func (*MessageEvent) HeartbeatExecutionStarted

func (e *MessageEvent) HeartbeatExecutionStarted() bool

Whether the heartbeat attempt entered the agent runner

func (*MessageEvent) HeartbeatResolvedSessionID

func (e *MessageEvent) HeartbeatResolvedSessionID() *string

Session id the heartbeat owner resolved to before the agent runner starts, nil before resolution

func (*MessageEvent) HeartbeatSessionID

func (e *MessageEvent) HeartbeatSessionID() *string

Heartbeat session a scheduled wake carries, nil for every other inbound

func (*MessageEvent) IsCommand

func (e *MessageEvent) IsCommand() bool

Reports a slash command the event is allowed to run as gateway control

func (*MessageEvent) LastChunkLen

func (e *MessageEvent) LastChunkLen() int

Code point length of the last chunk merged into the batch

func (*MessageEvent) PendingSTT

func (e *MessageEvent) PendingSTT() (text string, transcripts []string, ok bool)

Transcribed text and transcripts cached on the event by the inbound transcription pass, ok false when absent

func (*MessageEvent) PendingSTTClips

func (e *MessageEvent) PendingSTTClips() map[string]STTClip

Per clip transcription results of the event, created on first use so merges keep earlier clips

func (*MessageEvent) PendingSTTEchoed

func (e *MessageEvent) PendingSTTEchoed() int

Count of pending transcripts already echoed to the chat

func (*MessageEvent) ReplyFields

func (e *MessageEvent) ReplyFields() (anchorOverride, ledgerID *string, replyExpected *bool)

Reply anchor override, ledger id and reply expectation copied under the bound turn lock when one is bound

func (*MessageEvent) SetBotLoopAdmitted

func (e *MessageEvent) SetBotLoopAdmitted(v bool)

Records that the busy path charged the bot loop budget for the event

func (*MessageEvent) SetFIFOOnly

func (e *MessageEvent) SetFIFOOnly(stopEpoch int)

Marks the event as a FIFO only turn admitted under the stop epoch

func (*MessageEvent) SetGatewayAccepted

func (e *MessageEvent) SetGatewayAccepted(v bool)

Marks the event accepted by the gateway the way enqueuing it into the FIFO does

func (*MessageEvent) SetGatewayActiveTurnMarker

func (e *MessageEvent) SetGatewayActiveTurnMarker(sessionKey string, token any)

Stamps the durable active turn marker key and token the runner owns for this event

func (*MessageEvent) SetGatewayActiveTurnToken

func (e *MessageEvent) SetGatewayActiveTurnToken(token any)

Stamps the durable active turn token the delivery lifecycle clears

func (*MessageEvent) SetGatewayMarkerReleased

func (e *MessageEvent) SetGatewayMarkerReleased(ev *InterruptEvent)

Installs the event set once this turn released its crash marker

func (*MessageEvent) SetGatewayTurnRefusal

func (e *MessageEvent) SetGatewayTurnRefusal(refusal string)

Records the refusal a refused local turn replies with

func (*MessageEvent) SetHeartbeatExecutionStarted

func (e *MessageEvent) SetHeartbeatExecutionStarted(started bool)

Records whether the heartbeat attempt entered the agent runner

func (*MessageEvent) SetHeartbeatResolvedSessionID

func (e *MessageEvent) SetHeartbeatResolvedSessionID(id *string)

Records the session id the heartbeat owner resolved to

func (*MessageEvent) SetHeartbeatSessionID

func (e *MessageEvent) SetHeartbeatSessionID(id *string)

Marks the event as a scheduled heartbeat wake of the session

func (*MessageEvent) SetLastChunkLen

func (e *MessageEvent) SetLastChunkLen(n int)

Records the code point length of the last chunk merged into the batch

func (*MessageEvent) SetLedgerMessageID

func (e *MessageEvent) SetLedgerMessageID(id *string)

Stores the ledger id that keys the final send, under the bound turn lock when one is bound

func (*MessageEvent) SetNotificationReplyMuted

func (e *MessageEvent) SetNotificationReplyMuted(muted bool)

Records whether a queued chain's terminal notification reply is muted

func (*MessageEvent) SetPendingSTT

func (e *MessageEvent) SetPendingSTT(text string, transcripts []string)

Caches the transcribed text and transcripts the routed turn reads instead of transcribing again

func (*MessageEvent) SetPendingSTTEchoed

func (e *MessageEvent) SetPendingSTTEchoed(n int)

Records how many pending transcripts were echoed

func (*MessageEvent) SetStreamedFinalResponse

func (e *MessageEvent) SetStreamedFinalResponse(text string)

Records the text streaming already delivered for the loop and goal hooks that read the turn result

func (*MessageEvent) StreamedFinalResponse

func (e *MessageEvent) StreamedFinalResponse() *string

Text streaming already delivered for this turn, nil when the reply was not streamed

func (*MessageEvent) TurnMarkerHandoff

func (e *MessageEvent) TurnMarkerHandoff() bool

Whether this delivery lifecycle may release the durable crash marker of the turn

func (*MessageEvent) WakeInternal

func (e *MessageEvent) WakeInternal() bool

func (*MessageEvent) WakeMetadata

func (e *MessageEvent) WakeMetadata() map[string]any

func (*MessageEvent) WakeReplyMuted

func (e *MessageEvent) WakeReplyMuted() (bool, bool)

func (*MessageEvent) WakeSourcePlatform

func (e *MessageEvent) WakeSourcePlatform() string

func (*MessageEvent) WebhookDuplicate

func (e *MessageEvent) WebhookDuplicate() bool

Whether admission resolved the delivery to an already committed provider receipt

type MessageHandler

type MessageHandler func(ctx context.Context, event *MessageEvent) (any, error)

Handler result is nil when already delivered, a string reply or an EphemeralReply

type MessageStop

type MessageStop struct {
	Final bool
}

MessageStop ends a text segment, an intermediate stop starts a fresh segment below tool chrome

type MessageType

type MessageType string
const (
	MessageTypeText     MessageType = "text"
	MessageTypeLocation MessageType = "location"
	MessageTypePhoto    MessageType = "photo"
	MessageTypeVideo    MessageType = "video"
	MessageTypeAudio    MessageType = "audio"
	MessageTypeVoice    MessageType = "voice"
	MessageTypeDocument MessageType = "document"
	MessageTypeSticker  MessageType = "sticker"
	MessageTypeCommand  MessageType = "command"
)

type MirrorOptions

type MirrorOptions struct {
	SourceLabel string
	ThreadID    *string
	UserID      *string
	Role        string
	SessionID   string
}

MirrorOptions are the optional thread, sender, role and exact session of a mirror

type ModelPickerSender

type ModelPickerSender interface {
	SendModelPicker(ctx context.Context, chatID string, providers []map[string]any, currentModel, currentProvider, sessionKey string,
		onModelSelected func(ctx context.Context, chatID, modelID, providerSlug string) (string, error), metadata map[string]any) (SendResult, error)
}

Adapter that renders the interactive provider then model drill down picker of the model command

type ModelSwitchContext

type ModelSwitchContext struct {
	SessionKey       string
	Source           *SessionSource
	ConfigPath       string
	PersistGlobal    bool
	OneTurn          bool
	ReasoningEffort  string
	RestoreSnapshot  map[string]any
	CurrentModel     string
	CurrentProvider  string
	RouteProvider    any
	CurrentBaseURL   string
	CurrentAPIKey    string
	UserProviders    any
	CustomProviders  any
	ExcludedProvider []any
}

Current route and persistence policy of a model switch, shared with the runner's model commands

func (*ModelSwitchContext) ApplyOverride

func (c *ModelSwitchContext) ApplyOverride(override map[string]any)

Session model override superseding the configured route

func (*ModelSwitchContext) ReadConfig

func (c *ModelSwitchContext) ReadConfig(ctx context.Context)

Fills the current route from the config file, the defaults kept when it cannot be read

type MovedService

type MovedService struct {
	Name   string
	System bool
}

One service moved off a retired name, its current name and whether it is system scope

func MigrateRetiredGatewayServicesForInstall

func MigrateRetiredGatewayServicesForInstall(ctx context.Context, w io.Writer) ([]MovedService, error)

Moves the retired services of every profile of this install, the default home first

type MultipartPart

type MultipartPart struct {
	Name        string
	Filename    string
	ContentType string
	Data        []byte
}

One form field of an httpx multipart body, a file part when Filename is set

type MultiplexDecision

type MultiplexDecision struct {
	Enabled bool
	Source  string
	Reason  string
}

Boot verdict on multiplexing with where it came from and the guard's reason

func StandaloneLauncherDecision

func StandaloneLauncherDecision(ctx context.Context, cfg *GatewayConfig) (*MultiplexDecision, error)

Standalone guard verdict of an opted out launcher, turning multiplexing off on cfg, nil otherwise

type NativeBinding

type NativeBinding struct {
	SessionID string
	Source    *SessionSource
	Adapter   PlatformAdapter
}

Server observed route of one native session to recover, its available source and adapter

type NativeControlServer

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

Bounded native pipe workers serving control requests independent of any event loop

func NewNativeControlServer

func NewNativeControlServer(home string, handler func(raw []byte, peerSubject string) []byte) *NativeControlServer

Server over home's control pipe answering each request line through handler

func (*NativeControlServer) Alive

func (s *NativeControlServer) Alive(index int) bool

Alive reports whether the worker at index has started and not yet stopped

func (*NativeControlServer) Close

func (s *NativeControlServer) Close() error

Stops every worker, failing when one has not stopped five seconds after its turn

func (*NativeControlServer) Err

func (s *NativeControlServer) Err() error

Error the most recent worker stopped on, nil while every worker serves

func (*NativeControlServer) Start

func (s *NativeControlServer) Start() error

First instance claims the pipe name before the others start, failing when it cannot within five seconds

type NativeStreamAdapter

type NativeStreamAdapter interface {
	SupportsNativeStreaming(chatType string, metadata map[string]any) bool
	SendStreamFrame(ctx context.Context, text string, finalize bool, chatID, replyTo, turnID string) (bool, error)
}

Adapter that streams every frame natively, the WeCom stream message transport

type NativeToken

type NativeToken struct {
	Set   bool
	Token any
}

Snapshot of the native token a send will use, Set false when the caller passed none

type NotificationScheduler

type NotificationScheduler func(ctx context.Context, notification *jsonutil.Object, event *MessageEvent) error

Plugin owned handler of one Graph notification and its internal event, replacing gateway inference

type ObservedEndpoint

type ObservedEndpoint struct {
	State      string
	ReasonCode string
	Endpoint   *GatewayEndpoint
	Detail     string
}

ObservedEndpoint is a discovery or ensure verdict, empty strings standing for None

func DiscoverGatewayEndpoint

func DiscoverGatewayEndpoint(ctx context.Context, home string, timeout time.Duration) ObservedEndpoint

Live control identity of a profile home, preserving uncertainty instead of spawning

func DiscoverGatewayEndpointChecked

func DiscoverGatewayEndpointChecked(ctx context.Context, profileHome string, timeout time.Duration) (ObservedEndpoint, error)

Endpoint verdict for the profile home, the error a bad home raises

func EnsureGatewayRuntime

func EnsureGatewayRuntime(ctx context.Context, profileHome string, timeout float64, idleExit bool) (ObservedEndpoint, error)

Starts or awaits the owner of profile home once, a pending owner staying pending at the deadline

type OwnAccessPolicyMixin

type OwnAccessPolicyMixin struct {
	// AllowAllEnvPrefix is the platform prefix of the allow all users env name
	AllowAllEnvPrefix string
	// ExtraAllowAllEnvNames are further opt in names a host adds after the global and platform ones
	ExtraAllowAllEnvNames []string
	DMPolicy              string
	GroupPolicy           string
	AllowFrom             map[string]bool
	GroupAllowFrom        map[string]bool
	// EntryMatches is the platform allowlist match, plain membership when nil
	EntryMatches func(ctx context.Context, entries map[string]bool, target string) (bool, error)
	// LiveDMAllowFrom is the allowlist enforced right now, the construction allowlist when nil
	LiveDMAllowFrom func(ctx context.Context) (map[string]bool, error)
	// contains filtered or unexported fields
}

Config driven DM and group intake policy of an adapter that gates access itself

func NewOwnAccessPolicyMixin

func NewOwnAccessPolicyMixin(host, prefix string) (*OwnAccessPolicyMixin, error)

Policy of a host, refused like a class with no platform prefix is at creation

func (*OwnAccessPolicyMixin) AdapterAttr

func (p *OwnAccessPolicyMixin) AdapterAttr(name string) any

Host policy attributes the runner reads by name, nil for a name the mixin does not hold

func (*OwnAccessPolicyMixin) AllowAllEnvNames

func (p *OwnAccessPolicyMixin) AllowAllEnvNames() []string

The global and platform allow all users names, each read from the setting it moved to or else the env

func (*OwnAccessPolicyMixin) AllowFromSnapshot

func (p *OwnAccessPolicyMixin) AllowFromSnapshot() map[string]bool

Copy of the construction DM allowlist taken under its lock

func (*OwnAccessPolicyMixin) EnforcesOwnAccessPolicy

func (p *OwnAccessPolicyMixin) EnforcesOwnAccessPolicy() bool

The adapter enforces its own access policy

func (*OwnAccessPolicyMixin) IsDMAllowed

func (p *OwnAccessPolicyMixin) IsDMAllowed(ctx context.Context, senderID string) (bool, error)

Strict DM authorization, pairing never implying access

func (*OwnAccessPolicyMixin) IsDMIntakeAllowed

func (p *OwnAccessPolicyMixin) IsDMIntakeAllowed(ctx context.Context, senderID string) (bool, error)

Whether a DM may reach gateway intake, pairing admitting any principal and a blank one never

func (*OwnAccessPolicyMixin) IsGroupAllowed

func (p *OwnAccessPolicyMixin) IsGroupAllowed(ctx context.Context, chatID, senderID string) (bool, error)

Whether group traffic reaches intake, disabled, pairing and unknown policies never forwarding it

func (*OwnAccessPolicyMixin) OpenDMOptedIn

func (p *OwnAccessPolicyMixin) OpenDMOptedIn(ctx context.Context) (bool, error)

Whether a profile scoped allow all users opt in is set, failing closed

func (*OwnAccessPolicyMixin) PurgeAllowlistSnapshots

func (p *OwnAccessPolicyMixin) PurgeAllowlistSnapshots(keep func(entry string) bool)

Drops revoked principals from the DM allowlist in place, leaving it whole when a match panics

type OwnershipConflict

type OwnershipConflict struct {
	Msg       string
	Cancelled bool
	Cause     error
}

A profile home whose gateway.lock another holder owns

func (*OwnershipConflict) Error

func (e *OwnershipConflict) Error() string

func (*OwnershipConflict) Unwrap

func (e *OwnershipConflict) Unwrap() error

type PairingApproval

type PairingApproval struct {
	UserID, UserName string
	Row              *jsonutil.Object
}

Approved identity of a settled pairing request

type PairingStore

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

Pairing codes and approved users of one pairing directory, shared by the adapters of a gateway

func NewPairingStore

func NewPairingStore(ctx context.Context, profile string) (*PairingStore, error)

Store of the bound home, or of a named profile resolved the way `icebath -p <name> pairing` resolves it

func (*PairingStore) ApproveCode

func (s *PairingStore) ApproveCode(ctx context.Context, platform, code string) (*PairingApproval, error)

Approves a pairing code, nil when the code is invalid or expired or the platform is locked out

func (*PairingStore) ApproveRequest

func (s *PairingStore) ApproveRequest(ctx context.Context, platform, requestID string) (*PairingApproval, error)

Approves a pending request by its request id, outside the brute force lockout, nil when no row has it

func (*PairingStore) ClearPending

func (s *PairingStore) ClearPending(ctx context.Context, platform string) (int, error)

Clears the pending requests of one platform or of all, returning how many were removed

func (*PairingStore) GenerateCode

func (s *PairingStore) GenerateCode(ctx context.Context, platform, userID, userName string) (string, bool, error)

New pairing code for a user, false when rate limited, locked out or the platform is at its pending cap

func (*PairingStore) HasRecentDecline

func (s *PairingStore) HasRecentDecline(ctx context.Context, platform, userID string) (bool, error)

Whether a sender under any alias was sent a decline within the decline spacing

func (*PairingStore) IsApproved

func (s *PairingStore) IsApproved(ctx context.Context, platform, userID string) (bool, error)

Whether a user is approved on a platform under any of its aliases

func (*PairingStore) IsLockedOut

func (s *PairingStore) IsLockedOut(platform string) (bool, error)

Whether code approvals on the platform are refused after too many failed attempts

func (*PairingStore) IsRateLimited

func (s *PairingStore) IsRateLimited(ctx context.Context, platform, userID string) (bool, error)

Whether the user is inside the pairing request cooldown of the platform

func (*PairingStore) ListApproved

func (s *PairingStore) ListApproved(platform string) ([]*jsonutil.Object, error)

Approved users as rows of platform, user_id and the stored fields, of one platform or of all

func (*PairingStore) ListPending

func (s *PairingStore) ListPending(ctx context.Context, platform string) ([]PendingPairing, error)

Pending requests of one platform or of all, legacy entries reporting an empty request id

func (*PairingStore) Profile

func (s *PairingStore) Profile() (string, bool)

Profile name the store is scoped to, false for the store of the bound home

func (*PairingStore) RecordDecline

func (s *PairingStore) RecordDecline(ctx context.Context, platform, userID string) error

Stamps a sender under every alias as declined now and prunes the expired stamps

func (*PairingStore) RecordRateLimit

func (s *PairingStore) RecordRateLimit(ctx context.Context, platform, userID string) error

Starts the pairing request cooldown of the user on the platform

func (*PairingStore) Revoke

func (s *PairingStore) Revoke(ctx context.Context, platform, userID string) (bool, error)

Removes a user from the approved list, true when the user was found

type ParkedProfileRefusal

type ParkedProfileRefusal struct {
	*state.RuntimeStoreError
	Profile string
}

Producer admission refused because the delivery routes to the parked profile, retryable for as long as the park lasts

func NewParkedProfileRefusal

func NewParkedProfileRefusal(profile string) *ParkedProfileRefusal

func (*ParkedProfileRefusal) Unwrap

func (e *ParkedProfileRefusal) Unwrap() error

type ParkedRouteRefused

type ParkedRouteRefused struct{}

Unacknowledged delivery routed to a parked profile, nothing admitted and answered retryably

func (*ParkedRouteRefused) Error

func (*ParkedRouteRefused) Error() string

type PartialDeliveryError

type PartialDeliveryError struct {
	Msg    string
	Result any
}

PartialDeliveryError is a split send that failed after earlier chunks were delivered

func (*PartialDeliveryError) Error

func (e *PartialDeliveryError) Error() string

type PassthroughForward

type PassthroughForward struct {
	Platform string
	BotID    string
	Method   string
	Path     string
	Headers  [][2]string
	Body     []byte
	Profile  *string
}

PassthroughForward is a connector forwarded passthrough request with its decoded body and ordered headers

type PeekedSessionState

type PeekedSessionState = peekedSessionState

Session state a runner peeks without creating, as session info reads it

type PeerFileRefusal

type PeerFileRefusal struct {
	Status int
	Code   string
	Msg    string
}

File a room member's gateway will not take, its HTTP status, machine code and the words naming the rule

func (*PeerFileRefusal) Error

func (e *PeerFileRefusal) Error() string

type PeerFileRefusedError

type PeerFileRefusedError struct {
	Name   string
	Size   int64
	Detail string
}

Peer refusal of one file, the peer's own words naming its limit or type rule

func (*PeerFileRefusedError) Error

func (e *PeerFileRefusedError) Error() string

type PeerFileTransferError

type PeerFileTransferError struct {
	Name       string
	Held, Size int64
	Cause      error
}

File transfer to a peer cut off, the bytes the peer already holds kept for the retry

func (*PeerFileTransferError) Error

func (e *PeerFileTransferError) Error() string

func (*PeerFileTransferError) Unwrap

func (e *PeerFileTransferError) Unwrap() error

type PeerHostedRoomTransport

type PeerHostedRoomTransport struct {
	Binding             HostedRoomBinding
	Route               PeerMemberRoute
	Client              HostedRoomPeerClient
	SourceEventSeq      int64
	TaskID              *string
	ExecutionGeneration *int64
	StorePath           string
	AdoptCatalog        func(grant string, catalog *GatewayRoomCatalog) error
	// contains filtered or unexported fields
}

Translates runtime session operations into recipient validated peer RPC

func NewPeerHostedRoomTransport

func NewPeerHostedRoomTransport(binding HostedRoomBinding, route PeerMemberRoute, client HostedRoomPeerClient, sourceEventSeq int64, taskID *string, executionGeneration *int64) (*PeerHostedRoomTransport, error)

Peer transport of one member route, its client bound to the room scope

func (*PeerHostedRoomTransport) AcceptsAttachments

func (t *PeerHostedRoomTransport) AcceptsAttachments() bool

Whether the peer's catalog takes room files and the home store is there to send them from

func (*PeerHostedRoomTransport) Create

func (t *PeerHostedRoomTransport) Create(ctx context.Context, profile, title, source string) (map[string]any, error)

func (*PeerHostedRoomTransport) History

func (t *PeerHostedRoomTransport) History(ctx context.Context, profile, sessionID, source string) ([]map[string]any, error)

func (*PeerHostedRoomTransport) Info

func (t *PeerHostedRoomTransport) Info(ctx context.Context, profile, sessionID, source string) (map[string]any, error)

func (*PeerHostedRoomTransport) Interrupt

func (t *PeerHostedRoomTransport) Interrupt(ctx context.Context, profile, sessionID, source, expectedTaskID string) (map[string]any, error)

Stops the dispatched attempt, or the recovered one from its durable receipt

func (*PeerHostedRoomTransport) ResolveExact

func (t *PeerHostedRoomTransport) ResolveExact(ctx context.Context, profile, title, source string) (map[string]any, error)

func (*PeerHostedRoomTransport) Resume

func (t *PeerHostedRoomTransport) Resume(ctx context.Context, profile, sessionID, source string) (map[string]any, error)

func (*PeerHostedRoomTransport) Submit

func (t *PeerHostedRoomTransport) Submit(ctx context.Context, req HostedSubmit) (map[string]any, error)

Dispatches the fenced member turn after its files reached the peer, reporting an immediately terminal result

type PeerMemberRoute

type PeerMemberRoute struct {
	HomeInstallID         string
	MemberID              string
	TargetInstallID       string
	TargetProfile         string
	CapabilityDigest      string
	CancellationScopeID   string
	TraceID               string
	Grant                 string
	ExecutionPolicyDigest string
	Attachments           bool
}

Secret free target coordinates plus a separately stored room grant

type PeerPrepare

type PeerPrepare struct {
	RoomID            string
	Profile           string
	Source            string
	Grant             string
	Create            bool
	ExpectedSessionID *string
}

Coordinates of one scoped prepare call on a target gateway's room member API

type PeerRoomScope

type PeerRoomScope struct {
	RoomID             string
	HomeInstallID      string
	AuthorityGatewayID string
	AuthorityEpoch     int64
	MemberID           string
	TargetInstallID    string
	TargetProfile      string
}

Room scope bound into a peer client before any call

type PeerRunsHTTPClient

type PeerRunsHTTPClient struct {
	BaseURL           string
	APIKey            string
	TransportSecurity string
	TimeoutSeconds    float64
	ReceiptDBPath     string
	PollMinSeconds    float64
	PollMaxSeconds    float64
	// contains filtered or unexported fields
}

Drives a peer's dedicated group session through its scoped async Runs APIs

func NewDefaultPeerRunsHTTPClient

func NewDefaultPeerRunsHTTPClient(ctx context.Context, baseURL, apiKey, receiptDBPath string) (*PeerRunsHTTPClient, error)

Peer client with the keyword defaults of the Python constructor

func NewPeerRunsHTTPClient

func NewPeerRunsHTTPClient(ctx context.Context, baseURL, apiKey string, timeoutSeconds float64, receiptDBPath string, pollMinSeconds, pollMaxSeconds float64, clock func() float64) (*PeerRunsHTTPClient, error)

Peer client over a validated RoomLink URL, its polling bounds checked

func (*PeerRunsHTTPClient) ApproveReceipt

func (c *PeerRunsHTTPClient) ApproveReceipt(taskID string, executionGeneration int64, requestID, choice, grant string) (map[string]any, error)

Resolves approval of the exact durable remote run, nil when no receipt exists

func (*PeerRunsHTTPClient) BindObservation

func (c *PeerRunsHTTPClient) BindObservation(taskID string, executionGeneration int64) error

Pins history and status reads to one exact logical task attempt

func (*PeerRunsHTTPClient) BindReceiptStore

func (c *PeerRunsHTTPClient) BindReceiptStore(dbPath string) error

Attaches the gateway wide durable receipt store once

func (*PeerRunsHTTPClient) BindRoomScope

func (c *PeerRunsHTTPClient) BindRoomScope(scope PeerRoomScope) error

Fences every in memory and durable receipt to one room authority

func (*PeerRunsHTTPClient) Dispatch

func (c *PeerRunsHTTPClient) Dispatch(_ context.Context, dispatch *jsonutil.Object, grant string) (map[string]any, error)

func (*PeerRunsHTTPClient) History

func (c *PeerRunsHTTPClient) History(_ context.Context, roomID, profile, sessionID, grant string) ([]map[string]any, error)

Terminal history row of the observed run, empty while it is active

func (*PeerRunsHTTPClient) IssueInvitation

func (c *PeerRunsHTTPClient) IssueInvitation(roomID, homeInstallID, authorityGatewayID string, authorityEpoch int64, memberID, grantID string, ttlSeconds float64, statusTTLSeconds *float64) (map[string]any, error)

Asks the target gateway to mint a scoped room member grant

func (*PeerRunsHTTPClient) Prepare

func (c *PeerRunsHTTPClient) Prepare(_ context.Context, req PeerPrepare) (map[string]any, error)

Deterministic logical room session of the profile, checked against the expected id

func (*PeerRunsHTTPClient) Probe

func (c *PeerRunsHTTPClient) Probe(grant string) (map[string]any, error)

Verifies gateway reachability and the live scoped capability catalog

func (*PeerRunsHTTPClient) RecoverDispatch

func (c *PeerRunsHTTPClient) RecoverDispatch(dispatch any, grant string) (map[string]any, error)

Recovers one exact admission by receipt or idempotent POST replay

func (*PeerRunsHTTPClient) RefreshGrant

func (c *PeerRunsHTTPClient) RefreshGrant(grant string, ttlSeconds float64, capabilityDigest, executionPolicyDigest *string) (map[string]any, error)

Renews dispatch access only while its frozen authority is unchanged

func (*PeerRunsHTTPClient) RevokeGrant

func (c *PeerRunsHTTPClient) RevokeGrant(grant string) (map[string]any, error)

Revokes this grant's exact room, home, target and profile scope

func (*PeerRunsHTTPClient) SendFile

func (c *PeerRunsHTTPClient) SendFile(_ context.Context, grant string, file map[string]any, data []byte) (map[string]any, error)

Sends one turn file in chunks from the offset the peer holds, the peer checking the whole digest

func (*PeerRunsHTTPClient) Status

func (c *PeerRunsHTTPClient) Status(_ context.Context, roomID, profile, sessionID, grant string) (map[string]any, error)

Live state of the observed run

func (*PeerRunsHTTPClient) Stop

func (c *PeerRunsHTTPClient) Stop(ctx context.Context, dispatch *jsonutil.Object, grant string) (map[string]any, error)

func (*PeerRunsHTTPClient) StopReceipt

func (c *PeerRunsHTTPClient) StopReceipt(_ context.Context, taskID string, executionGeneration int64, grant string) (map[string]any, error)

Stops the exact durable remote run after a home restart, nil when no receipt exists

type PeerRunsHTTPError

type PeerRunsHTTPError struct {
	Msg                  string
	Retryable            bool
	Ambiguous            bool
	NotAdmitted          bool
	StatusCode           int
	ErrorCode            string
	NeedsReauthorization bool
	Cause                error
	Detail               string
}

Controlled peer HTTP failure classified for retry, ambiguity and admission

func DigestReauthorizationError

func DigestReauthorizationError(catalog *GatewayRoomCatalog, capabilityDigest, executionPolicyDigest *string) *PeerRunsHTTPError

Fail closed error when a refreshed catalog drifted from the frozen digests, policy checked first

func (*PeerRunsHTTPError) Error

func (e *PeerRunsHTTPError) Error() string

func (*PeerRunsHTTPError) Unwrap

func (e *PeerRunsHTTPError) Unwrap() error

type PendingAdmission

type PendingAdmission struct {
	AdmissionReceipt
	InputID         string
	Text            string
	DisplayKind     string
	DisplayMetadata map[string]any
	Controls        []string
	Steering        bool
}

Queued admission with its input text, transcript display kind and metadata, queued row verbs and steering flag

type PendingControls

type PendingControls struct {
	RemoteResponders map[string]func(kind, promptID, value string) error
	// contains filtered or unexported fields
}

Generation bound projection and control of the blocking approval and clarify prompts of one session

func NewPendingControls

func NewPendingControls(events *SessionEvents) *PendingControls

Controls publishing on a session's event stream

type PendingPairing

type PendingPairing struct {
	Platform, RequestID string
	UserID, UserName    any
	AgeMinutes          int
}

Pending request row as the list surfaces show it, the code itself never included

type PendingRetry

type PendingRetry struct {
	Platform  string
	Profile   string
	NotBefore float64
}

Earliest redelivery deadline of this process's waiting failed rows for one adapter identity

func PendingRetries

func PendingRetries(ctx context.Context, now *float64) ([]PendingRetry, error)

This process's failed rows awaiting a timer, one entry per adapter identity with its earliest deadline

type Platform

type Platform string

Messaging platform value, built in members plus plugin pseudo members created on demand

const (
	PlatformLocal          Platform = "local"
	PlatformTelegram       Platform = "telegram"
	PlatformDiscord        Platform = "discord"
	PlatformWhatsApp       Platform = "whatsapp"
	PlatformWhatsAppCloud  Platform = "whatsapp_cloud"
	PlatformSlack          Platform = "slack"
	PlatformSignal         Platform = "signal"
	PlatformMattermost     Platform = "mattermost"
	PlatformMatrix         Platform = "matrix"
	PlatformEmail          Platform = "email"
	PlatformSMS            Platform = "sms"
	PlatformDingTalk       Platform = "dingtalk"
	PlatformAPIServer      Platform = "api_server"
	PlatformWebhook        Platform = "webhook"
	PlatformMSGraphWebhook Platform = "msgraph_webhook"
	PlatformFeishu         Platform = "feishu"
	PlatformWeCom          Platform = "wecom"
	PlatformWeComCallback  Platform = "wecom_callback"
	PlatformWeixin         Platform = "weixin"
	PlatformBlueBubbles    Platform = "bluebubbles"
	PlatformQQBot          Platform = "qqbot"
	PlatformYuanbao        Platform = "yuanbao"
	PlatformRelay          Platform = "relay"
)

func ParsePlatform

func ParsePlatform(ctx context.Context, value any) (Platform, error)

The platform for a value, accepting bundled or registered plugin names, ValueError for anything else

func PlatformMemberMap

func PlatformMemberMap() []Platform

Values of the member map by name, pseudo members included in creation order as __members__ lists them

func PlatformMembers

func PlatformMembers() []Platform

Built in members in declaration order, pseudo members never iterate

func (Platform) Name

func (p Platform) Name() string

Member name, the value upper cased with dashes and spaces as underscores

type PlatformAdapter

type PlatformAdapter interface {
	Base() *BasePlatformAdapter
	Connect(ctx context.Context, isReconnect bool) (bool, error)
	Disconnect(ctx context.Context) error
	Send(ctx context.Context, chatID, content, replyTo string, metadata map[string]any) (SendResult, error)
	GetChatInfo(ctx context.Context, chatID string) (map[string]any, error)

	Name() string
	IsConnected() bool
	MessageLenFn() func(string) int
	MaxMessageLengthForChat(chatID string) (int, error)
	MessageLenFnForChat(chatID string) (func(string) int, error)
	EnforcesOwnAccessPolicy() bool
	AuthorizationIsUpstream() bool
	SupportsDraftStreaming(chatType string, metadata map[string]any, chatID string) bool
	PrefersFreshFinalStreaming(content string, metadata map[string]any, chatID string) bool
	StreamingOverflowLimit() (int, bool)
	SendDraft(ctx context.Context, chatID string, draftID int, content string, metadata map[string]any) (SendResult, error)
	RenderMessageEvent(event StreamEvent, sink StreamSink)
	FormatToolEvent(ctx context.Context, event StreamEvent, mode string, previewMaxLen int) (string, bool)
	FormatToolPreview(preview tools.ToolPreview) string
	SendPathDegraded() bool
	MarkConnected(ctx context.Context, listenerBase string)
	MarkDisconnected(ctx context.Context)
	SetFatalError(ctx context.Context, code, message string, retryable bool)
	WirePluginHandlers(ctx context.Context, native any)
	RewirePluginHandlers(ctx context.Context)
	TextBatchKey(ctx context.Context, event *MessageEvent) (string, error)
	EnqueueTextEvent(ctx context.Context, event *MessageEvent) error
	TextBatchDelayFor(pending *MessageEvent) float64
	PopTextBatch(key string) *MessageEvent
	DispatchTextBatch(ctx context.Context, event *MessageEvent) error
	FlushTextBatch(ctx context.Context, key string) error
	HandleMessage(ctx context.Context, event *MessageEvent) error
	CreateHandoffThread(ctx context.Context, parentChatID, name string) (string, bool, error)
	EditMessage(ctx context.Context, chatID, messageID, content string, finalize bool) (SendResult, error)
	DeleteMessage(ctx context.Context, chatID, messageID string) (bool, error)
	SendPrivateNotice(ctx context.Context, chatID string, userID *string, content, replyTo string, metadata map[string]any) (SendResult, error)
	SendTyping(ctx context.Context, chatID string, metadata map[string]any) error
	StopTyping(ctx context.Context, chatID string, metadata map[string]any) error
	SendMultipleImages(ctx context.Context, chatID string, images []ImageRef, metadata map[string]any, humanDelay float64) (SendResult, error)
	SendImage(ctx context.Context, chatID, imageURL, caption, replyTo string, metadata map[string]any) (SendResult, error)
	SendAnimation(ctx context.Context, chatID, animationURL, caption, replyTo string, metadata map[string]any) (SendResult, error)
	SendImageFile(ctx context.Context, chatID, imagePath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)
	SendVoice(ctx context.Context, chatID, audioPath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)
	SendVideo(ctx context.Context, chatID, videoPath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)
	SendDocument(ctx context.Context, chatID, filePath, caption, fileName, replyTo string, metadata, extra map[string]any) (SendResult, error)
	EAHeader(ctx context.Context) string
	EAReasonLabel(ctx context.Context) string
	EASmartDenyLine(ctx context.Context) string
	EAActionLabelsFor(ctx context.Context) map[string]string
	EAEscape(text string) string
	ExecApprovalCmdBudget(ctx context.Context, description string, smartDenied bool) int
	SendExecApproval(ctx context.Context, chatID, command, sessionKey string, description *string, metadata map[string]any, allowPermanent, allowSession, smartDenied bool, requestID *string) (SendResult, error)
	SendExecApprovalPrompt(ctx context.Context, prompt *ExecApprovalPrompt) (SendResult, error)
	SendSlashConfirm(ctx context.Context, chatID, title, message, sessionKey, confirmID string, metadata map[string]any) (SendResult, error)
	SendClarify(ctx context.Context, chatID, question string, choices []string, clarifyID, sessionKey string, metadata map[string]any) (SendResult, error)
	EmitWarning(ctx context.Context, chatID, content, replyTo string, metadata map[string]any, logicalPlatform Platform) (*SendResult, error)
	EmitMediaWarning(ctx context.Context, chatID, notice, caption, replyTo string, metadata, shownMetadata map[string]any) (SendResult, error)
	WarningText(ctx context.Context, visible string, hidden *string, logicalPlatform Platform, chatID string, metadata map[string]any) *string
	WarningNotificationsEnabled(ctx context.Context, logicalPlatform Platform, chatID string, metadata map[string]any) bool
	PrepareTTSText(ctx context.Context, text string) string
	PlayTTS(ctx context.Context, chatID, audioPath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)
	SupportsStreamingTTS(chatID string, format AudioFormat) bool
	BeginStreamingTTS(ctx context.Context, chatID string, format AudioFormat, metadata map[string]any) (*StreamingTTSHandle, error)
	WriteStreamingTTS(ctx context.Context, handle *StreamingTTSHandle, chunk []byte) error
	FinishStreamingTTS(ctx context.Context, handle *StreamingTTSHandle, interrupted bool) error
	AbortStreamingTTS(ctx context.Context, handle *StreamingTTSHandle, errText *string) error
	OnProcessingStart(ctx context.Context, event *MessageEvent) error
	OnProcessingComplete(ctx context.Context, event *MessageEvent, outcome ProcessingOutcome) error
	SendRetryIsFinal(result SendResult) bool
	ResumePartialSend(ctx context.Context, chatID string, result SendResult, replyTo string, metadata map[string]any) (*SendResult, error)
	SendPlainFallback(ctx context.Context, chatID, content, replyTo string, metadata map[string]any) (SendResult, error)
	ProcessMessageBackground(ctx context.Context, event *MessageEvent, sessionKey string) error
	KeepTyping(ctx context.Context, chatID string, interval float64, metadata map[string]any, stopEvent *InterruptEvent)
	InterruptSessionActivity(ctx context.Context, sessionKey, chatID string, metadata map[string]any)
	CancelBackgroundTasks(ctx context.Context)
	ToolsetsForSource(source *SessionSource) ([]string, bool)
	FormatMessage(content string) string
}

The overridable method set every platform adapter overrides

func InstantiateBuiltinAdapter

func InstantiateBuiltinAdapter(ctx context.Context, platform Platform, config *PlatformConfig) (PlatformAdapter, error)

Core adapter of a platform, nil when the platform is not builtin or its requirements are unmet

type PlatformConfig

type PlatformConfig struct {
	Enabled                    bool
	Token                      any
	APIKey                     any
	HomeChannel                *HomeChannel
	ReplyToMode                any
	GatewayRestartNotification bool
	TypingIndicator            bool
	TypingStatusText           any
	ChannelOverrides           map[string]*ChannelOverride
	Extra                      map[string]any
}

Configuration of one messaging platform

func EnableFromEnv

func EnableFromEnv(ctx context.Context, cfg *GatewayConfig, platform Platform) *PlatformConfig

Enables a platform on env credentials unless config.yaml disabled it, warning once

func NewPlatformConfig

func NewPlatformConfig() *PlatformConfig

Platform config with the dataclass defaults

func PlatformConfigFromDict

func PlatformConfigFromDict(ctx context.Context, raw any) (*PlatformConfig, error)

Platform config of a block, non typed top level keys promoted into extra with explicit extra winning

func (*PlatformConfig) ToDict

func (c *PlatformConfig) ToDict() map[string]any

Mapping form, token and api key only when truthy

type PlatformEntry

type PlatformEntry struct {
	Name                       string                                                                                                                       `py:"name"`
	Label                      string                                                                                                                       `py:"label"`
	AdapterFactory             AdapterFactory                                                                                                               `py:"adapter_factory"`
	CheckFn                    func() bool                                                                                                                  `py:"check_fn"`
	ScopedCheckFn              func(ctx context.Context) bool                                                                                               `py:"scoped_check_fn"`
	ValidateConfig             func(cfg *PlatformConfig) (bool, error)                                                                                      `py:"validate_config"`
	ScopedValidateConfig       func(ctx context.Context, cfg *PlatformConfig) (bool, error)                                                                 `py:"scoped_validate_config"`
	EnsureDepsFn               func(ctx context.Context) (bool, error)                                                                                      `py:"ensure_deps_fn"`
	IsConnected                func(ctx context.Context, cfg *PlatformConfig) (bool, error)                                                                 `py:"is_connected"`
	RequiredEnv                []string                                                                                                                     `py:"required_env"`
	InstallHint                string                                                                                                                       `py:"install_hint"`
	SetupFn                    func(ctx context.Context) error                                                                                              `py:"setup_fn"`
	Source                     string                                                                                                                       `py:"source"`
	PluginName                 string                                                                                                                       `py:"plugin_name"`
	AllowedUsersEnv            string                                                                                                                       `py:"allowed_users_env"`
	AllowAllEnv                string                                                                                                                       `py:"allow_all_env"`
	MaxMessageLength           int                                                                                                                          `py:"max_message_length"`
	PIISafe                    bool                                                                                                                         `py:"pii_safe"`
	Emoji                      string                                                                                                                       `py:"emoji"`
	AllowUpdateCommand         bool                                                                                                                         `py:"allow_update_command"`
	PlatformHint               string                                                                                                                       `py:"platform_hint"`
	EnvEnablementFn            func(ctx context.Context) map[string]any                                                                                     `py:"env_enablement_fn"`
	ApplyYAMLConfigFn          func(ctx context.Context, yamlCfg, block map[string]any) (map[string]any, error)                                             `py:"apply_yaml_config_fn"`
	CronDeliverEnvVar          string                                                                                                                       `py:"cron_deliver_env_var"`
	ParseTargetRefFn           func(ref string) (chatID string, threadID *string, ok bool)                                                                  `py:"parse_target_ref_fn"`
	ValidateTargetRefFn        func(ref string) any                                                                                                         `py:"validate_target_ref_fn"`
	SendMessageHandler         func(ctx context.Context, args map[string]any, chatID, platformName string, pconfig *PlatformConfig) (map[string]any, error) `py:"send_message_handler"`
	StandaloneSenderFn         func(ctx context.Context, kwargs map[string]any) (map[string]any, error)                                                     `py:"standalone_sender_fn"`
	TrustedInbound             bool                                                                                                                         `py:"trusted_inbound"`
	DisplayTier                string                                                                                                                       `py:"display_tier"`
	DisplayOverrides           map[string]any                                                                                                               `py:"display_overrides"`
	SharedEnvPrefixes          []string                                                                                                                     `py:"shared_env_prefixes"`
	ConfigConnectedFn          func(cfg *PlatformConfig) bool                                                                                               `py:"config_connected_fn"`
	AllowBotsEnv               string                                                                                                                       `py:"allow_bots_env"`
	OwnPolicyEnv               []string                                                                                                                     `py:"own_policy_env"`
	GroupAllowedChatsEnv       string                                                                                                                       `py:"group_allowed_chats_env"`
	AllowlistSuppressesPairing bool                                                                                                                         `py:"allowlist_suppresses_pairing"`
	TargetRefSyntaxFn          func(ref string) any                                                                                                         `py:"target_ref_syntax_fn"`
	StandaloneSend             *StandaloneSendPolicy                                                                                                        `py:"standalone_send"`
	EnvOverrides               []EnvStep                                                                                                                    `py:"env_overrides"`
	EnvEnableCredentials       []string                                                                                                                     `py:"env_enable_credentials"`
	// Lines the setup of the platform shows before its questions
	SetupInstructions []string `py:"setup_instructions"`
	// Questions the setup of the platform asks when it has no setup function, each answer saved under its variable
	SetupVars []SetupVar `py:"setup_vars"`
}

Metadata and factory of one platform adapter, py tags naming the keyword each field takes

func ConfiguredPluginEntries

func ConfiguredPluginEntries(ctx context.Context, registry *PlatformRegistry, yamlCfg any, platformNames []string, h string) []*PlatformEntry

Plugin entries of platforms this profile configures, already loaded entries always included

func NewPlatformEntry

func NewPlatformEntry(name, label string, factory AdapterFactory, check func() bool) *PlatformEntry

Entry with the dataclass defaults, plugin source, plug emoji and the update command allowed

func (*PlatformEntry) HasValidateConfig

func (e *PlatformEntry) HasValidateConfig() bool

Whether the entry declares a config validator, scoped or plain

func (*PlatformEntry) RunCheck

func (e *PlatformEntry) RunCheck(ctx context.Context) bool

Result of the entry's check, the scoped check reading the caller's profile secret scope when declared

func (*PlatformEntry) RunValidateConfig

func (e *PlatformEntry) RunValidateConfig(ctx context.Context, cfg *PlatformConfig) (bool, error)

Result of the entry's config validator, the scoped one reading the caller's profile secret scope when declared

func (*PlatformEntry) SetKeywords

func (e *PlatformEntry) SetKeywords(kwargs map[string]any) error

Sets entry fields from keyword arguments, TypeError for an unknown keyword or a value of the wrong type

type PlatformEventHandler

type PlatformEventHandler func(ctx context.Context, event map[string]any, source *SessionSource) error

PlatformEventHandler is the runner owned boundary for normalized platform events

type PlatformHTTPClientOptions

type PlatformHTTPClientOptions struct {
	Timeout         *time.Duration
	FollowRedirects *bool
	Limits          *HTTPXLimits
	DefaultLimits   bool
	ResponseHooks   []func(resp *http.Response) error
	// Whether the client reads the proxy variables of the environment, nil reading them
	TrustEnv *bool
}

How a platform HTTP client is built, nil fields taking the platform defaults

type PlatformRegistry

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

Central registry of platform adapters, plugin entries isolated per profile home and loaded lazily

func NewPlatformRegistry

func NewPlatformRegistry() *PlatformRegistry

Empty registry

func (*PlatformRegistry) ActivationEnv

func (r *PlatformRegistry) ActivationEnv(name string) map[string]bool

Env names recorded for a deferred platform

func (*PlatformRegistry) AllEntries

func (r *PlatformRegistry) AllEntries(ctx context.Context) []*PlatformEntry

Every registered entry, loading every deferred platform

func (*PlatformRegistry) ConfiguredEntries

func (r *PlatformRegistry) ConfiguredEntries(ctx context.Context, wanted func(string) bool) []*PlatformEntry

Loaded entries after materializing only the deferred platforms wanted accepts

func (*PlatformRegistry) CreateAdapter

func (r *PlatformRegistry) CreateAdapter(ctx context.Context, name string, cfg *PlatformConfig) any

Adapter of a platform, nil when no entry exists, deps are missing, validation fails or the factory errors

func (*PlatformRegistry) Get

Entry of a name, running its deferred loader first when one is pending

func (*PlatformRegistry) IsDeferredLoadCancelled

func (r *PlatformRegistry) IsDeferredLoadCancelled(name, scope string) bool

Whether ownership teardown cancelled an in flight loader

func (*PlatformRegistry) IsRegistered

func (r *PlatformRegistry) IsRegistered(ctx context.Context, name string) bool

Whether a name is registered or pending, never loading the adapter

func (*PlatformRegistry) LoadedEntries

func (r *PlatformRegistry) LoadedEntries(ctx context.Context) []*PlatformEntry

Entries already materialized, never running a deferred loader

func (*PlatformRegistry) NoteActivationEnv

func (r *PlatformRegistry) NoteActivationEnv(name string, envNames []string)

Records the env names a deferred platform's manifest declares

func (*PlatformRegistry) PendingNames

func (r *PlatformRegistry) PendingNames(ctx context.Context) []string

Deferred names of the current scope that have not loaded yet

func (*PlatformRegistry) PluginEntries

func (r *PlatformRegistry) PluginEntries(ctx context.Context) []*PlatformEntry

Entries whose source is a plugin

func (*PlatformRegistry) Register

func (r *PlatformRegistry) Register(ctx context.Context, entry *PlatformEntry, scope string) error

Registers an entry, last writer wins, a plugin entry's scope inferred from its code when not given

func (*PlatformRegistry) RegisterDeferred

func (r *PlatformRegistry) RegisterDeferred(name string, loader *plugins.DeferredPlatformLoader, scope string)

Registers a lazy loader run at most once on first lookup, a concrete registration dropping it

func (*PlatformRegistry) RegisteredNames

func (r *PlatformRegistry) RegisteredNames(ctx context.Context) map[string]bool

Concrete and deferred names of the current scope and process wide, never loading an adapter

func (*PlatformRegistry) RequiredEnvNames

func (r *PlatformRegistry) RequiredEnvNames(ctx context.Context) map[string]bool

Required env of every loaded entry of the current scope and process wide

func (*PlatformRegistry) RestoreRegistration

func (r *PlatformRegistry) RestoreRegistration(name string, curEntry *PlatformEntry, curLoader *plugins.DeferredPlatformLoader,
	prevEntry *PlatformEntry, prevLoader *plugins.DeferredPlatformLoader, scope string) bool

Restores a previous registration when the full state is still the current one

func (*PlatformRegistry) SnapshotRegistration

func (r *PlatformRegistry) SnapshotRegistration(name, scope string) (*PlatformEntry, *plugins.DeferredPlatformLoader)

Concrete and deferred state of a name without resolving it

func (*PlatformRegistry) Unregister

func (r *PlatformRegistry) Unregister(ctx context.Context, name, scope string) (bool, error)

Removes an entry, true when it existed, the scope inferred from the caller when not given

type PlatformSetupFns

type PlatformSetupFns struct {
	DeclinesReconfigure func(ctx context.Context, label, question string, envVars ...string) (bool, error)
	SavePrompted        func(ctx context.Context, envVar, question string, o SavePromptedOptions) (string, error)
	PromptAllowlist     func(ctx context.Context, envVar, question, successMsg, openMsg string) (string, error)
	SavePort            func(ctx context.Context, envVar, value, def string) error
}

The setup_platforms helpers platform wizards share, resolved at call time so tests can observe them

type PluginMessageRunner

type PluginMessageRunner interface {
	SessionStore() *SessionStore
	RestoredSource(ctx context.Context, entry *SessionEntry) (*SessionSource, error)
	SessionKeyForSource(ctx context.Context, source *SessionSource) (string, error)
	PluginLocalSession(ctx context.Context, source *SessionSource, sessionKey, pluginHome, pluginID string) (*LiveSession, error)
	PluginMessagingSessionOwned(ctx context.Context, sessionKey, pluginHome, pluginID string) bool
	DeliveryAdapterFor(ctx context.Context, source *SessionSource) (PlatformAdapter, error)
	ThreadMetadataForSource(source *SessionSource, replyToMessageID *string) map[string]any
}

Running gateway methods plugin message delivery resolves a session through, gateway/run.py GatewayRunner

type PolicySnapshot

type PolicySnapshot struct {
	ThroughSeq        int64
	StoppedThroughSeq int64
	Events            []map[string]any
	Watermarks        map[[2]string]int64
}

Bounded active policy input at one durable room log cursor, watermarks keyed by thread and member

type PostDeliveryCallback

type PostDeliveryCallback func(ctx context.Context) error

Deferred callback fired after a turn's reply was delivered

type PostTarget

type PostTarget struct {
	Platform  string
	ChatID    string
	Adapter   PlatformAdapter
	Metadata  map[string]any
	Live      *LiveSession
	NoticeKey string
}

Resolved conversation, a messaging adapter and chat or a local session's live viewers

type PreDialError

type PreDialError struct{ Msg string }

Authority call that died before its RPC reached the socket, a definite no send safe to retry

func (*PreDialError) Error

func (e *PreDialError) Error() string

type PrepareStallTracker

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

Per room consecutive preparation failures shared by driver room workers and RPC callers

func NewPrepareStallTracker

func NewPrepareStallTracker() *PrepareStallTracker

func (*PrepareStallTracker) Clear

func (t *PrepareStallTracker) Clear(roomID string)

func (*PrepareStallTracker) Failed

func (t *PrepareStallTracker) Failed(roomID string, err error) bool

Records one failure, true exactly once when this failure stalls the room

func (*PrepareStallTracker) LastError

func (t *PrepareStallTracker) LastError(roomID string) *string

Last recorded failure text of the room, nil when none

func (*PrepareStallTracker) Stall

func (t *PrepareStallTracker) Stall(roomID string, err error)

Marks a failed explicit Retry stalled at once, without a second room event

func (*PrepareStallTracker) Stalled

func (t *PrepareStallTracker) Stalled(roomID string) bool

Whether the room's preparation stalled

type PressureEntry

type PressureEntry[A any] struct {
	Key   string
	Agent A
}

One cached session and its agent in least to most recently used order

func PlanPressureEvictions

func PlanPressureEvictions[A any](ordered []PressureEntry[A], isEvictable func(key string, agent A) bool, maxEvictions, protectRecent int) []PressureEntry[A]

Cached sessions to shed least recently used first, capped per pass with the hottest half protected at most

type Principal

type Principal struct {
	Subject      string
	ProfileID    string
	Capabilities map[string]bool
	TransportID  string
}

Authenticated caller with its profile, capability set and transport

type ProcessingOutcome

type ProcessingOutcome string
const (
	ProcessingSuccess   ProcessingOutcome = "success"
	ProcessingFailure   ProcessingOutcome = "failure"
	ProcessingCancelled ProcessingOutcome = "cancelled"
)

func FollowupCancelOutcome

func FollowupCancelOutcome(ctx context.Context, adapter PlatformAdapter) ProcessingOutcome

Cancelled for a cancel the adapter itself routed, failure for any other, the background processing classification

type ProducerHooksRunner

type ProducerHooksRunner interface {
	HMPreGatewayDispatchHook(ctx context.Context, event *MessageEvent, source *SessionSource) *MessageEvent
	RunPostAdmissionHook(ctx context.Context, event *MessageEvent, source *SessionSource, sessionKey string) (bool, *string, error)
}

Runner running the producer admission plugin hooks, run_inbound_hooks _hm_pre_gateway_dispatch_hook and run_inbound_consumer run_post_admission_hook

type ProducerScopeRunner

type ProducerScopeRunner interface {
	AuthorityRunner
	SessionAuthority() *SessionAuthority
	OwningProfile(adapter PlatformAdapter, platform Platform) (registered bool, profile string)
	Canonicalize(ctx context.Context, source *SessionSource, transportProfile, primaryHome string) *RoutingIdentity
	ResolveProfileHomeForSource(ctx context.Context, source *SessionSource) (string, error)
	AdmitPrimarySource(ctx context.Context, source *SessionSource, defaultHome string) (string, bool)
}

Runner seams producer ingress admits through, authz_mixin _owning_profile and run_adapters _canonicalize and _admit_primary_source

type ProfileOwnership

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

Reservations of canonical profile homes held through open locked descriptors

func NewProfileOwnership

func NewProfileOwnership() *ProfileOwnership

Empty ownership with no reservations

func (*ProfileOwnership) Close

func (o *ProfileOwnership) Close()

Releases every reservation unless a registered writer is still running

func (*ProfileOwnership) Hold

func (o *ProfileOwnership) Hold(h string) (func(), bool)

Enters background work in home, refused once its reservation was released, the lock outliving every entered work

func (*ProfileOwnership) Homes

func (o *ProfileOwnership) Homes() []string

Homes reserved in reservation order

func (*ProfileOwnership) Owns

func (o *ProfileOwnership) Owns(h string) bool

Whether home is reserved here

func (*ProfileOwnership) Release

func (o *ProfileOwnership) Release(h string)

Releases the reservation of home, its lock file left in place

func (*ProfileOwnership) Reserve

func (o *ProfileOwnership) Reserve(ctx context.Context, homes []string, purpose string) error

Reserves every home all or nothing, purpose marking a maintenance holder in the lock record

func (*ProfileOwnership) StartWriter

func (o *ProfileOwnership) StartWriter(run func())

Registers then starts a writer so a partial startup cannot forget a live one

func (*ProfileOwnership) StartWriterThread

func (o *ProfileOwnership) StartWriterThread(alive func() bool, start func())

Registers a thread shaped writer by its liveness probe and then starts it, so a respawned writer still counts

type ProfileRoute

type ProfileRoute struct {
	Name       any
	Platform   any
	Profile    string
	GuildID    *string
	ChatID     *string
	ThreadID   *string
	Enabled    any
	BotProfile *string
	UserID     *string
}

One routing rule mapping a platform scope to a profile

func MatchProfileRoute

func MatchProfileRoute(ctx context.Context, routes []*ProfileRoute, q RouteQuery) (*ProfileRoute, error)

First, most specific, route matching the query

func ParseProfileRoutes

func ParseProfileRoutes(ctx context.Context, raw any) ([]*ProfileRoute, error)

Profile routes of config.yaml sorted most specific first, TypeError for a non iterable value

func (*ProfileRoute) Matches

func (r *ProfileRoute) Matches(ctx context.Context, q RouteQuery) (bool, error)

True when every discriminator the route declares holds

func (*ProfileRoute) Specificity

func (r *ProfileRoute) Specificity() int

Match weight, a higher value is more specific

func (*ProfileRoute) ToDict

func (r *ProfileRoute) ToDict() map[string]any

Mapping of every field, user_id only when set

type ProfileRouteRejected

type ProfileRouteRejected struct {
	Args []any
}

An explicit route matched a profile this gateway does not serve

func (*ProfileRouteRejected) Error

func (e *ProfileRouteRejected) Error() string

func (*ProfileRouteRejected) Profile

func (e *ProfileRouteRejected) Profile() any

The rejected profile when the error carries one

type ProxyConnector

type ProxyConnector struct {
	Type     string
	Host     string
	Port     int
	Username string
	Password string
	// contains filtered or unexported fields
}

func NewProxyConnector

func NewProxyConnector(proxyURL string) (*ProxyConnector, error)

Connector for a socks5, socks4 or http proxy URL that resolves target names on the proxy side

func (*ProxyConnector) DialContext

func (c *ProxyConnector) DialContext(ctx context.Context, network, addr string) (net.Conn, error)

Opens a connection to the address tunnelled through the proxy

func (*ProxyConnector) Transport

func (c *ProxyConnector) Transport() *http.Transport

HTTP transport whose every connection goes through the proxy

type ProxyKwargs

type ProxyKwargs struct {
	Connector *ProxyConnector
	Proxy     string
}

func ProxyKwargsForAiohttp

func ProxyKwargsForAiohttp(proxyURL string) (session, request ProxyKwargs, err error)

Session and request proxy settings for a standalone client, every scheme through a connector

func ProxyKwargsForBot

func ProxyKwargsForBot(proxyURL string) (ProxyKwargs, error)

Bot client proxy settings, a connector for socks proxies and the plain URL for http ones

type PublicationPlan

type PublicationPlan struct {
	TaskID       string
	TerminalKind string
	Events       []EventPlan
}

Ordered visible and terminal effects of one driver task

func PlanPublication

func PlanPublication(roomValue any, events []any, task DiscussionTaskPlan, status string, result any, executionGeneration *int64, localProfiles []string) (PublicationPlan, error)

Plans idempotent room effects of one terminal driver task, a newer same thread send cancelling a late result

type QueuedControlConnection

type QueuedControlConnection interface {
	SessionAuthority() *SessionAuthority
	Actor() Principal
	Operator() bool
	Submission(ctx context.Context, ref SessionRef, params *jsonutil.Object) (Submission, error)
}

Connection surface the queued row verbs read, its authority, actor, operator flag and submission parser

type ReactionAdapter

type ReactionAdapter interface {
	AddReaction(ctx context.Context, chatID, messageID, emoji string) error
	RemoveReaction(ctx context.Context, chatID, messageID string) error
}

Optional reaction surface an adapter provides for the outcome reaction swap

type ReactionHandler

type ReactionHandler func(ctx context.Context, event map[string]any) error

ReactionHandler receives normalized emoji reaction events

type ReactionsEnabler

type ReactionsEnabler interface {
	ReactionsEnabled(ctx context.Context) bool
}

Optional runtime switch for the outcome reactions

type RecoverableHandleCache

type RecoverableHandleCache struct {
	Handles map[string]any
	Lock    *sync.Mutex
	// contains filtered or unexported fields
}

Caches handles by path while failed opens back off and heal inside the process

func NewRecoverableHandleCache

func NewRecoverableHandleCache() *RecoverableHandleCache

Cache with the default clock, retry delays, handle map and lock

func NewRecoverableHandleCacheWith

func NewRecoverableHandleCacheWith(opts RecoverableHandleCacheOptions) *RecoverableHandleCache

Cache over the given handle map, lock, clock and retry delays

func (*RecoverableHandleCache) CloseAll

func (c *RecoverableHandleCache) CloseAll(closeHandle func(handle any))

Drains every cached handle under the lock and closes each outside it

func (*RecoverableHandleCache) Get

func (c *RecoverableHandleCache) Get(ctx context.Context, path string, opener func() (any, error), nonCacheable func(error) bool) (any, error)

Cached handle or one single flight open, nil without error while a retry is in flight or backing off

func (*RecoverableHandleCache) GetWith

func (c *RecoverableHandleCache) GetWith(ctx context.Context, path string, opener func() (any, error), opts HandleCacheGetOptions) (any, error)

Cached handle or one bounded open, raising non cacheable errors and every error under RaiseOnError

func (*RecoverableHandleCache) LastError

func (c *RecoverableHandleCache) LastError(path string) string

Error text the latest failed open of the path raised, empty when none is recorded

func (*RecoverableHandleCache) LastFailure

func (c *RecoverableHandleCache) LastFailure(path string) error

Error the latest failed open of the path returned, nil when none is recorded

type RecoverableHandleCacheOptions

type RecoverableHandleCacheOptions struct {
	Handles           map[string]any
	Lock              *sync.Mutex
	Clock             func() float64
	InitialRetryDelay *float64
	MaxRetryDelay     *float64
}

Constructor keywords of the cache, nil fields taking the upstream defaults

type RecoveredSecrets

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

Frozen config secrets in path order with the paths whose profile value changed and the stamping session

func (*RecoveredSecrets) Get

func (r *RecoveredSecrets) Get(path secretPath) (any, bool)

Frozen secret value at a path and whether the path is held

func (*RecoveredSecrets) Len

func (r *RecoveredSecrets) Len() int

Number of held secrets

func (*RecoveredSecrets) Set

func (r *RecoveredSecrets) Set(path secretPath, value any)

Value stored at a path, replacing an earlier value in place

type RedirectReceiver

type RedirectReceiver interface {
	Redirect(text string) bool
}

Agent seam taking a redirect of the running turn

type RefusedOwner

type RefusedOwner struct {
	ReasonCode string
	Pid        int
	Remedy     string
}

RefusedOwner is this user's gateway behind a boundary the client must not cross, a PermissionError

func (*RefusedOwner) Error

func (e *RefusedOwner) Error() string

func (*RefusedOwner) Is

func (e *RefusedOwner) Is(target error) bool

type RegistryCommand

type RegistryCommand struct {
	Name, BusyPolicy, BusyHandler string
}

Registry command a typed name resolves to, with the busy policy and mid run variant key of its definition

type RelayAdapter

type RelayAdapter struct {
	*BasePlatformAdapter
	// contains filtered or unexported fields
}

RelayAdapter is the generic gateway adapter fronted by the connector, advertising its negotiated capabilities

func NewRelayAdapter

func NewRelayAdapter(config *PlatformConfig, descriptor CapabilityDescriptor, transport RelayTransportConn) *RelayAdapter

Adapter for the platform config with its pre handshake descriptor and an optional transport

func (*RelayAdapter) AbandonOpenDraft

func (a *RelayAdapter) AbandonOpenDraft(ctx context.Context, chatID, content string, metadata map[string]any) (SendResult, error)

Seals an orphaned open stream with the text, a no op when nothing is armed

func (*RelayAdapter) AuthorizationIsUpstream

func (a *RelayAdapter) AuthorizationIsUpstream() bool

The connector enforces authorization, so relay users are not default denied locally

func (*RelayAdapter) AutoThreadInfoForChat

func (a *RelayAdapter) AutoThreadInfoForChat(chatID string) any

Thread id and initial name of the auto thread the connector made for the latest send, nil when none

func (*RelayAdapter) Connect

func (a *RelayAdapter) Connect(ctx context.Context, isReconnect bool) (bool, error)

Wires the transport handlers, dials, adopts the negotiated descriptor and watches for revocation

func (*RelayAdapter) CreateHandoffThread

func (a *RelayAdapter) CreateHandoffThread(ctx context.Context, parentChatID, name string) (string, bool, error)

Creates a thread or topic under the parent through the connector, false on any failure

func (*RelayAdapter) DeleteMessage

func (a *RelayAdapter) DeleteMessage(ctx context.Context, chatID, messageID string) (bool, error)

Deletes a relayed message when the chat's descriptor advertises delete, false otherwise or on failure

func (*RelayAdapter) Descriptor

func (a *RelayAdapter) Descriptor() CapabilityDescriptor

Negotiated capability profile of the primary identity

func (*RelayAdapter) Disconnect

func (a *RelayAdapter) Disconnect(ctx context.Context) error

Stops the revocation monitor, asks the connector to buffer, then closes the transport within the remaining budget

func (*RelayAdapter) EditMessage

func (a *RelayAdapter) EditMessage(ctx context.Context, chatID, messageID, content string, finalize bool) (SendResult, error)

Edits a relayed message through the connector

func (*RelayAdapter) EditMessageWithMetadata

func (a *RelayAdapter) EditMessageWithMetadata(ctx context.Context, chatID, messageID, content string, finalize bool, metadata map[string]any) (SendResult, error)

Edits a relayed message with its routing metadata, the structured decline carried in the result

func (*RelayAdapter) FrontsPlatform

func (a *RelayAdapter) FrontsPlatform(platform Platform) bool

Whether the transport advertised the platform among its handshake identities

func (*RelayAdapter) GetChatInfo

func (a *RelayAdapter) GetChatInfo(ctx context.Context, chatID string) (map[string]any, error)

Chat info from the connector, a local DM shape when the op is unadvertised or there is no transport

func (*RelayAdapter) GoDormant

func (a *RelayAdapter) GoDormant(ctx context.Context) (bool, error)

Quiesces the relay for a scale to zero suspend with the reconnect path left armed

func (*RelayAdapter) HoldRedial

func (a *RelayAdapter) HoldRedial() bool

Parks the transport's reconnect supervisor, false when it did not take

func (*RelayAdapter) MaxMessageLengthForChat

func (a *RelayAdapter) MaxMessageLengthForChat(chatID string) (int, error)

func (*RelayAdapter) MessageLenFn

func (a *RelayAdapter) MessageLenFn() func(string) int

Length function of the primary descriptor unit

func (*RelayAdapter) MessageLenFnForChat

func (a *RelayAdapter) MessageLenFnForChat(chatID string) (func(string) int, error)

func (*RelayAdapter) NativeTaskCardDestinationSupported

func (a *RelayAdapter) NativeTaskCardDestinationSupported(chatID string, replyTo *string, metadata map[string]any) *bool

Whether a chat can host a card, a Slack chat only inside a thread

func (*RelayAdapter) NativeTaskCardsEnabled

func (a *RelayAdapter) NativeTaskCardsEnabled() (bool, error)

Turn runner opt in probe of the native task card lane

func (*RelayAdapter) OnInterrupt

func (a *RelayAdapter) OnInterrupt(ctx context.Context, sessionKey, chatID string) error

Bridges a connector delivered stop into the per session interrupt path

func (*RelayAdapter) OnProcessingComplete

func (a *RelayAdapter) OnProcessingComplete(ctx context.Context, event *MessageEvent, outcome ProcessingOutcome) error

Swaps the in progress reaction for the outcome one

func (*RelayAdapter) OnProcessingStart

func (a *RelayAdapter) OnProcessingStart(ctx context.Context, event *MessageEvent) error

Adds the in progress reaction

func (*RelayAdapter) PrefersFreshFinalStreaming

func (a *RelayAdapter) PrefersFreshFinalStreaming(content string, metadata map[string]any, chatID string) bool

Fresh final delivery for a link bearing final when Slack unfurl is forced on for the chat's platform

func (*RelayAdapter) PrimeRoutingCache

func (a *RelayAdapter) PrimeRoutingCache(event *MessageEvent)

Warms the per chat egress routing caches from a synthetic event

func (*RelayAdapter) RelayTransport

func (a *RelayAdapter) RelayTransport() any

Transport the session ingress relay connector check reads

func (*RelayAdapter) ReleaseRedial

func (a *RelayAdapter) ReleaseRedial() bool

Undoes a hold when the suspend did not land, false when it did not take

func (*RelayAdapter) RenameThread

func (a *RelayAdapter) RenameThread(ctx context.Context, threadID, name string, opts ThreadRenameOptions) (bool, error)

Renames a thread through the connector, its no clobber guard preferred over the legacy name guard

func (*RelayAdapter) Send

func (a *RelayAdapter) Send(ctx context.Context, chatID, content, replyTo string, metadata map[string]any) (SendResult, error)

Sends text, sealing an open stream with a turn final and recording any connector created auto thread

func (*RelayAdapter) SendClarify

func (a *RelayAdapter) SendClarify(ctx context.Context, chatID, question string, choices []string, clarifyID, sessionKey string, metadata map[string]any) (SendResult, error)

Native button clarify with positional option ids, open ended or unavailable ones falling back to the base

func (*RelayAdapter) SendDocument

func (a *RelayAdapter) SendDocument(ctx context.Context, chatID, filePath, caption, fileName, replyTo string, metadata, extra map[string]any) (SendResult, error)

func (*RelayAdapter) SendDraft

func (a *RelayAdapter) SendDraft(ctx context.Context, chatID string, draftID int, content string, metadata map[string]any) (SendResult, error)

Streams one draft frame, a sealed stream's straggler swallowed and a declined frame retiring the open draft

func (*RelayAdapter) SendExecApprovalPrompt

func (a *RelayAdapter) SendExecApprovalPrompt(ctx context.Context, prompt *ExecApprovalPrompt) (SendResult, error)

Native button exec approval, failing when the lane is unavailable so the text fallback runs

func (*RelayAdapter) SendFollowUp

func (a *RelayAdapter) SendFollowUp(ctx context.Context, sessionKey, kind, content string, metadata map[string]any) (SendResult, error)

Sends through a session bound shared identity capability, the connector resolving the credential

func (*RelayAdapter) SendForPlatform

func (a *RelayAdapter) SendForPlatform(ctx context.Context, platform Platform, chatID, content string, metadata map[string]any) (SendResult, error)

Sends to an advertised logical platform, refusing one the transport does not front

func (*RelayAdapter) SendImage

func (a *RelayAdapter) SendImage(ctx context.Context, chatID, imageURL, caption, replyTo string, metadata map[string]any) (SendResult, error)

Image URL through the send_media lane, else the base text and URL behaviour

func (*RelayAdapter) SendImageFile

func (a *RelayAdapter) SendImageFile(ctx context.Context, chatID, imagePath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)

func (*RelayAdapter) SendNativeTaskCardProgress

func (a *RelayAdapter) SendNativeTaskCardProgress(ctx context.Context, chatID string, tasks []map[string]string, title string, replyTo *string, metadata map[string]any, fallbackText string) (SendResult, error)

Sends the task card progress chunks, a decline carried in the result

func (*RelayAdapter) SendSlashConfirm

func (a *RelayAdapter) SendSlashConfirm(ctx context.Context, chatID, title, message, sessionKey, confirmID string, metadata map[string]any) (SendResult, error)

Three button slash command confirmation, failing when the lane is unavailable so text intercept runs

func (*RelayAdapter) SendTyping

func (a *RelayAdapter) SendTyping(ctx context.Context, chatID string, metadata map[string]any) error

Egresses one typing frame carrying the chat's live status phrase when one is set

func (*RelayAdapter) SendVideo

func (a *RelayAdapter) SendVideo(ctx context.Context, chatID, videoPath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)

func (*RelayAdapter) SendVoice

func (a *RelayAdapter) SendVoice(ctx context.Context, chatID, audioPath, caption, replyTo string, metadata, extra map[string]any) (SendResult, error)

func (*RelayAdapter) StatusMetadataForTurn

func (a *RelayAdapter) StatusMetadataForTurn(chatID, anchor string, metadata map[string]any) map[string]any

Typing metadata of a turn with its status anchor fixed on the turn's own message

func (*RelayAdapter) StopNativeTaskCardProgress

func (a *RelayAdapter) StopNativeTaskCardProgress(ctx context.Context, chatID string, replyTo *string, metadata map[string]any) (SendResult, error)

Closes the card stream of the turn, the connector result carried back

func (*RelayAdapter) StopTyping

func (a *RelayAdapter) StopTyping(ctx context.Context, chatID string, metadata map[string]any) error

Sends the explicit empty status clear, Slack chats only

func (*RelayAdapter) StreamIsMessageForChat

func (a *RelayAdapter) StreamIsMessageForChat(chatID string) bool

Seal semantics only for a chat whose governing descriptor is Slack

func (*RelayAdapter) SupportsDraftStreaming

func (a *RelayAdapter) SupportsDraftStreaming(chatType string, metadata map[string]any, chatID string) bool

Draft streaming only when the chat platform advertises draft and no Slack unfurl hints are configured

func (*RelayAdapter) SupportsInchannelContinuableForPlatform

func (a *RelayAdapter) SupportsInchannelContinuableForPlatform(platform string) (bool, error)

Whether one fronted platform hosts the flat continuable cron surface, the primary bit when unnegotiated

func (*RelayAdapter) SupportsNativeTaskCards

func (a *RelayAdapter) SupportsNativeTaskCards() bool

Native task cards only when the connector advertises the op

func (*RelayAdapter) WaitForAutoThreadInfo

func (a *RelayAdapter) WaitForAutoThreadInfo(ctx context.Context, chatID string, timeout float64) (any, error)

Auto thread info after the next send into the chat, nil when the timeout passes first

func (*RelayAdapter) WarningNotificationsEnabled

func (a *RelayAdapter) WarningNotificationsEnabled(ctx context.Context, logicalPlatform Platform, chatID string, metadata map[string]any) bool

Warning policy of the logical platform, the metadata or chat platform standing in

type RelayAdmission

type RelayAdmission <-chan error

RelayAdmission settles with the off reader admission outcome, context.Canceled for a cancelled one

type RelayConnectionClosed

type RelayConnectionClosed struct {
	Rcvd *relayCloseFrame
	Sent *relayCloseFrame
	Err  error
}

RelayConnectionClosed is a websocket closed abnormally, carrying the received and sent close frames

func (*RelayConnectionClosed) Error

func (e *RelayConnectionClosed) Error() string

func (*RelayConnectionClosed) Unwrap

func (e *RelayConnectionClosed) Unwrap() error

type RelayDeliveryAdapter

type RelayDeliveryAdapter interface {
	SendForPlatform(ctx context.Context, platform Platform, chatID, content string, metadata map[string]any) (SendResult, error)
	FrontsPlatform(platform Platform) bool
}

RelayDeliveryAdapter is the relay transport that sends for the logical platforms it fronts

type RelayHTTPError

type RelayHTTPError struct {
	Code   int
	Reason string
	Header http.Header
	Body   []byte
}

RelayHTTPError is the urllib HTTPError of a relay request with its status, reason and error body

func (*RelayHTTPError) Error

func (e *RelayHTTPError) Error() string

type RelayInboundHandler

type RelayInboundHandler func(ctx context.Context, event *MessageEvent) (RelayAdmission, error)

RelayInboundHandler admits a connector delivered event, a non nil admission deferring the frame ACK

type RelayInterruptHandler

type RelayInterruptHandler func(ctx context.Context, sessionKey, chatID string) error

RelayInterruptHandler receives a connector interrupt for a session and chat

type RelayMediaClient

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

RelayMediaClient talks to the connector media routes with the per gateway signed bearer

func NewRelayMediaClient

func NewRelayMediaClient(baseURL, gatewayID, secret string) *RelayMediaClient

Client for the connector base with the gateway credentials, absent ones empty

func (*RelayMediaClient) Download

func (c *RelayMediaClient) Download(ctx context.Context, url string, suggestedName *string) (string, error)

Local temp path of a downloaded attachment, empty on any failure

func (*RelayMediaClient) DownloadWithName

func (c *RelayMediaClient) DownloadWithName(ctx context.Context, url string, suggestedName *string) (string, string, bool, error)

Temp path and original display name of a downloaded attachment, ok false on any failure

func (*RelayMediaClient) Enabled

func (c *RelayMediaClient) Enabled() bool

True when the base URL and both per gateway credentials are present

func (*RelayMediaClient) IsRelayMediaURL

func (c *RelayMediaClient) IsRelayMediaURL(url string) bool

True when the URL is a connector re host reference needing the bearer

func (*RelayMediaClient) Upload

func (c *RelayMediaClient) Upload(ctx context.Context, filePath string, mime, filename *string) (string, error)

Reference URL of the uploaded file, empty on any failure

func (*RelayMediaClient) UploadWithError

func (c *RelayMediaClient) UploadWithError(ctx context.Context, filePath string, mime, filename *string) (string, string, error)

Reference URL or the failure reason, transient failures retried after the configured delays

type RelayPassthroughHandler

type RelayPassthroughHandler func(ctx context.Context, forward *PassthroughForward, bufferID any) error

RelayPassthroughHandler receives a forwarded passthrough request and its buffer id

type RelayProvisionRefused

type RelayProvisionRefused struct{ Msg string }

RelayProvisionRefused is a connector refusal of provision carrying its own reason

func (*RelayProvisionRefused) Error

func (e *RelayProvisionRefused) Error() string

type RelayRouteUnknown

type RelayRouteUnknown struct{ Msg string }

Relay routing could not be determined, callers fail closed

func (*RelayRouteUnknown) Error

func (e *RelayRouteUnknown) Error() string

type RelayRuntimeError

type RelayRuntimeError struct{ Msg string }

RelayRuntimeError is a provision or policy failure with a user facing message

func (*RelayRuntimeError) Error

func (e *RelayRuntimeError) Error() string

type RelayTransportConn

type RelayTransportConn interface {
	Connect(ctx context.Context) (bool, error)
	Disconnect(ctx context.Context, budgetS *float64) error
	Handshake(ctx context.Context) (CapabilityDescriptor, error)
	SetInboundHandler(handler RelayInboundHandler)
	SendOutbound(ctx context.Context, action map[string]any, platform string) (map[string]any, error)
	GetChatInfo(ctx context.Context, chatID string) (map[string]any, error)
	SendInterrupt(ctx context.Context, sessionKey string, reason *string) error
	SendFollowUp(ctx context.Context, action map[string]any, platform string) (map[string]any, error)
}

RelayTransportConn is the gateway to connector transport contract the relay adapter drives

type RelayTransportOptions

type RelayTransportOptions struct {
	Identities           [][2]string
	ConnectTimeoutS      *float64
	OutboundTimeoutS     *float64
	GatewayID            string
	UpgradeSecret        string
	Reconnect            bool
	ReconnectBackoffS    *float64
	ReconnectMaxBackoffS *float64
}

RelayTransportOptions are the keyword arguments of the transport constructor

type RelayURLError

type RelayURLError struct{ Reason string }

RelayURLError is a relay request failure before any HTTP reply, carrying the transport reason

func (*RelayURLError) Error

func (e *RelayURLError) Error() string

type ReplayCursor

type ReplayCursor struct {
	Epoch    string
	Sequence int64
}

Replay epoch and sequence an attach resumes from

type ReplicaEpochRegressionError

type ReplicaEpochRegressionError struct{ *ReplicaError }

Page or demotion carrying an older authority epoch than stored

func (*ReplicaEpochRegressionError) Unwrap

func (e *ReplicaEpochRegressionError) Unwrap() error

type ReplicaError

type ReplicaError struct{ *HostedRoomError }

Invalid or conflicting replica operation

func (*ReplicaError) Unwrap

func (e *ReplicaError) Unwrap() error

type ReplicaGapError

type ReplicaGapError struct{ *ReplicaError }

Page that does not start at the replica's next expected sequence

func (*ReplicaGapError) Unwrap

func (e *ReplicaGapError) Unwrap() error

type ReplyModeStep

type ReplyModeStep struct {
	Platform Platform
	Env      string
}

Reply mode step whose platform and env stay readable to the profile channel scan

func (ReplyModeStep) Apply

func (s ReplyModeStep) Apply(ctx context.Context, cfg *GatewayConfig) error

type ResponseStore

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

ResponseStore keeps Responses API state for previous_response_id chaining and Idempotency-Key identity

func NewResponseStore

func NewResponseStore(ctx context.Context, maxSize int, dbPath string, maxIdentities int) (*ResponseStore, error)

Store at the path, the home response_store.db by default, process memory when the file cannot open

func (*ResponseStore) Atomically

func (s *ResponseStore) Atomically(ctx context.Context, fn func(ctx context.Context) (any, error)) (any, error)

Runs a sequence of store calls as one unit no other caller interleaves, the calls taking the given context

func (*ResponseStore) BindRequestAdmission

func (s *ResponseStore) BindRequestAdmission(ctx context.Context, key, admissionID string) error

Binds a request key to its canonical admission, refused as a conflict when bound to another

func (*ResponseStore) BindRequestKey

func (s *ResponseStore) BindRequestKey(ctx context.Context, key, fingerprint string, model any) (bool, error)

Reserves one immutable request digest, false when the key is bound to another fingerprint

func (*ResponseStore) Close

func (s *ResponseStore) Close(ctx context.Context)

Closes the connection, a close failure swallowed

func (*ResponseStore) Delete

func (s *ResponseStore) Delete(ctx context.Context, responseID string) (bool, error)

Removes a response, its conversation mappings and its settled identity, true when anything was deleted

func (*ResponseStore) ForgetUnadmittedRequest

func (s *ResponseStore) ForgetUnadmittedRequest(ctx context.Context, key string) error

Drops a request key that never reached an admission

func (*ResponseStore) Get

func (s *ResponseStore) Get(ctx context.Context, responseID string) (any, error)

Stored response by id with its access time refreshed, nil when absent or corrupt

func (*ResponseStore) GetConversation

func (s *ResponseStore) GetConversation(ctx context.Context, name string) (string, error)

Latest response id of a conversation name, empty when unmapped

func (*ResponseStore) Len

func (s *ResponseStore) Len(ctx context.Context) (int, error)

Stored response body count

func (*ResponseStore) OrderOutput

func (s *ResponseStore) OrderOutput(ctx context.Context, key string, items []*jsonutil.Object) ([]*jsonutil.Object, error)

Items sorted by their allocated output index

func (*ResponseStore) OutputIndex

func (s *ResponseStore) OutputIndex(ctx context.Context, key, itemID string) (int64, error)

Output index allocated to an item of a request, shared by retries and parallel observers

func (*ResponseStore) Put

func (s *ResponseStore) Put(ctx context.Context, responseID string, data any) error

Stores a response, an idem record never overwritten, evicting past capacity

func (*ResponseStore) RequestAdmission

func (s *ResponseStore) RequestAdmission(ctx context.Context, key string) (string, error)

Canonical admission bound to a request key, empty when none

func (*ResponseStore) RequestCreatedAt

func (s *ResponseStore) RequestCreatedAt(ctx context.Context, key string) (*int64, error)

Creation second of a request key, nil when unbound

func (*ResponseStore) RequestKeyMatches

func (s *ResponseStore) RequestKeyMatches(ctx context.Context, key, fingerprint string) (bool, error)

Whether a request key is unbound or bound to the fingerprint

func (*ResponseStore) RequestModel

func (s *ResponseStore) RequestModel(ctx context.Context, key string, fallback any) (any, error)

Accepted wire model label of a request key, upgrading an older binding to the fallback

func (*ResponseStore) SetConversation

func (s *ResponseStore) SetConversation(ctx context.Context, name, responseID string) error

Maps a conversation name to its latest response id

type RetiredService

type RetiredService struct {
	Name, Path string
	System     bool
}

One gateway service definition installed under a name this release replaced

func RetiredGatewayServices

func RetiredGatewayServices(ctx context.Context) ([]RetiredService, error)

Gateway services of the home in effect installed under a retired name, LaunchAgents on macOS and units under systemd

type RetryRewrite

type RetryRewrite struct {
	DB        *state.SessionDB
	SessionID string
	Source    *SessionSource
	Write     func(ctx context.Context, conn state.SQLiteConn) error
	OnCommit  func()
	Applied   bool
	// contains filtered or unexported fields
}

One retry transcript rewrite applied at most once inside the admission write of its re-send

type RetryRewriteRefused

type RetryRewriteRefused struct {
	Msg   string
	Cause error
}

Refusal of a planned retry rewrite that stopped applying, the re-send refused with it and nothing written

func (*RetryRewriteRefused) Error

func (e *RetryRewriteRefused) Error() string

func (*RetryRewriteRefused) Unwrap

func (e *RetryRewriteRefused) Unwrap() error

type RetryableIngressScope

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

Awaited dispatch scope whose transport has not acknowledged the delivery yet

func RetryableIngress

func RetryableIngress(ctx context.Context) (context.Context, *RetryableIngressScope, func())

Scopes an awaited dispatch so a parked route is only recorded, closed when the returned func runs

func (*RetryableIngressScope) Refused

func (s *RetryableIngressScope) Refused() bool

Whether a parked route inside the scope was recorded for a retryable answer

type RoomConflictError

type RoomConflictError struct{ *HostedRoomError }

An idempotency key reused for different room state

func (*RoomConflictError) Unwrap

func (e *RoomConflictError) Unwrap() error

type RoomExecutionPolicy

type RoomExecutionPolicy struct {
	Version         int64
	TargetProfile   string
	EnabledToolsets []string
	ApprovalMode    string
	MaxIterations   int64
	PolicyDigest    string
}

Immutable target policy applied at the agent and approval boundaries

func CurrentRoomExecutionPolicy

func CurrentRoomExecutionPolicy(ctx context.Context) *RoomExecutionPolicy

Room execution policy the context carries, nil outside a room turn

func RoomExecutionPolicyFromMapping

func RoomExecutionPolicyFromMapping(value any) (*RoomExecutionPolicy, error)

Policy validated from its wire mapping with its digest recomputed and checked

func (*RoomExecutionPolicy) AsMapping

func (p *RoomExecutionPolicy) AsMapping() *jsonutil.Object

Wire mapping of the policy with its toolsets as a list

type RoomExecutionPolicyError

type RoomExecutionPolicyError struct{ Msg string }

A RoomLink execution policy that is malformed or no longer current, a ValueError

func (*RoomExecutionPolicyError) Error

func (e *RoomExecutionPolicyError) Error() string

type RoomGrantIssue

type RoomGrantIssue struct {
	GrantID, RoomID, HomeInstallID, AuthorityGatewayID any
	AuthorityEpoch                                     any
	MemberID, TargetInstallID, TargetProfile           any
	ExecutionPolicyDigest                              string
	Permissions                                        []any
	IssuedAt                                           *float64
	TTLSeconds                                         *float64
	StatusTTLSeconds                                   *float64
	StatusExpiresAt                                    *float64
}

Keyword arguments of one room grant issue, the identity values validated as the issuer receives them

type RoomHistoryExpiredError

type RoomHistoryExpiredError struct{ *RoomNotFoundError }

A retired room id whose history compaction removed its log

func (*RoomHistoryExpiredError) Reason

func (e *RoomHistoryExpiredError) Reason() string

Stable wire reason of the error

func (*RoomHistoryExpiredError) Unwrap

func (e *RoomHistoryExpiredError) Unwrap() error

type RoomNotFoundError

type RoomNotFoundError struct{ *HostedRoomError }

A room that does not exist or has been disbanded

func (*RoomNotFoundError) Unwrap

func (e *RoomNotFoundError) Unwrap() error

type RoomProbeUnavailableError

type RoomProbeUnavailableError struct{ *HostedRoomError }

A non blocking ownership probe that cannot read the room store

func (*RoomProbeUnavailableError) Unwrap

func (e *RoomProbeUnavailableError) Unwrap() error

type RoomShareSyncError

type RoomShareSyncError struct{ Msg string }

Error a home sent the sync route that the client should see as a bad request

func (*RoomShareSyncError) Error

func (e *RoomShareSyncError) Error() string

type RoomUnavailableError

type RoomUnavailableError struct{ *DriverStateError }

Hosted room that does not exist or was disbanded

func (*RoomUnavailableError) Unwrap

func (e *RoomUnavailableError) Unwrap() error

type RoomValueError

type RoomValueError struct{ Msg string }

A plain ValueError raised by a hosted room validator

func (*RoomValueError) Error

func (e *RoomValueError) Error() string

func (*RoomValueError) ErrorKind

func (e *RoomValueError) ErrorKind() string

Kind label of the error

type RosterProfile

type RosterProfile struct {
	IsDefault   bool
	Model       any
	Provider    any
	Description string
	DisplayName string
	SkillCount  int
}

Profile facts a Bots roster row shows, read from the profile directory

type RouteQuery

type RouteQuery struct {
	Platform       string
	GuildID        *string
	ChatID         *string
	ThreadID       *string
	ParentChatID   *string
	AdapterProfile *string
	UserID         *string
}

Inbound discriminators a route is matched against, nil for an absent value

type RoutingCachePrimer

type RoutingCachePrimer interface {
	PrimeRoutingCache(event *MessageEvent)
}

Relay adapter that warms its egress routing cache from a synthetic event before replying

type RoutingIdentity

type RoutingIdentity struct {
	TransportProfile  string
	RuntimeProfile    string
	AuthorizationHome string
	RuntimeHome       string
	Multiplexed       bool
	Transport         weak.Pointer[BasePlatformAdapter]
	TransportInferred bool
}

RoutingIdentity is who a turn is, resolved once at ingress, with explicit transport and runtime profiles

func CanonicalIdentity

func CanonicalIdentity(ctx context.Context, source *SessionSource, runner TransportOwnerRunner, adapter PlatformAdapter, transportProfile, primaryHome string) (*RoutingIdentity, error)

Identity pinned on the source, else one resolved against the primary home, nil when the route is unresolved

func IdentityOf

func IdentityOf(source *SessionSource) *RoutingIdentity

Identity pinned on the source by resolution, nil when none is pinned

func RestoreIdentity

func RestoreIdentity(ctx context.Context, source *SessionSource, runner any, transportProfile *string) (*RoutingIdentity, error)

Pins the identity of a source rebuilt from durable state from its persisted receiving bot

func (*RoutingIdentity) Adapter

func (r *RoutingIdentity) Adapter() PlatformAdapter

Live receiving adapter, nil when it is gone or was never known

func (*RoutingIdentity) Namespace

func (r *RoutingIdentity) Namespace() string

Agent namespace prefix of this identity's session keys

func (*RoutingIdentity) SessionKeyProfile

func (r *RoutingIdentity) SessionKeyProfile() string

Runtime profile under multiplexing, empty for the legacy namespace of a standalone gateway

func (*RoutingIdentity) StorePath

func (r *RoutingIdentity) StorePath() string

Session database path under the runtime home

type RunIdempotencyRecord

type RunIdempotencyRecord struct {
	RunID        *string
	Status       any
	OwnerPID     int64
	OwnerStarted int64
	UpdatedAt    float64
}

RunIdempotencyRecord is the stored public run status of one reservation with its owner

type RunIdempotencyStore

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

RunIdempotencyStore holds durable tenant scoped reservations of run requests by idempotency key

func NewRunIdempotencyStore

func NewRunIdempotencyStore(ctx context.Context, dbPath string) (*RunIdempotencyStore, error)

Store at the path, the home runs_idempotency.db by default, process memory when the file cannot open

func (*RunIdempotencyStore) Close

func (s *RunIdempotencyStore) Close() error

Closes the connection

func (*RunIdempotencyStore) Durable

func (s *RunIdempotencyStore) Durable() bool

Whether reservations survive this process

func (*RunIdempotencyStore) ExtendRetention

func (s *RunIdempotencyStore) ExtendRetention(ctx context.Context, scope, runID string, until float64) (bool, error)

Persists the latest verified recovery horizon of a run, true when exactly one row changed

func (*RunIdempotencyStore) Forget

func (s *RunIdempotencyStore) Forget(ctx context.Context, scope, key string) error

Releases a reservation whose run was refused before it existed

func (*RunIdempotencyStore) Lookup

func (s *RunIdempotencyStore) Lookup(ctx context.Context, scope, key, fingerprint string, retentionUntil float64) (string, *RunIdempotencyRecord, error)

Missing, reused or conflict for a key without reserving it

func (*RunIdempotencyStore) OwnsRun

func (s *RunIdempotencyStore) OwnsRun(ctx context.Context, scope, runID string) (bool, error)

Whether the scope holds the run

func (*RunIdempotencyStore) Reserve

func (s *RunIdempotencyStore) Reserve(ctx context.Context, scope, key, fingerprint, runID string, status any, ownerPID, ownerStarted int64,
	retentionUntil float64) (string, *RunIdempotencyRecord, error)

Atomically reserves a key, created with the new record or reused or conflict with the stored one

func (*RunIdempotencyStore) StatusForRun

func (s *RunIdempotencyStore) StatusForRun(ctx context.Context, scope, runID string, retentionUntil float64) (*RunIdempotencyRecord, error)

Durable run status inside its authenticated scope, nil when the scope holds no such run

func (*RunIdempotencyStore) UpdateStatus

func (s *RunIdempotencyStore) UpdateStatus(ctx context.Context, runID string, status any) error

Replaces the stored public status of a run

type RunnerDeliveryContract

Runner methods that adapter delivery, plugin messages, parked refusals and the gateway loop callers reach at runtime

type RunnerIngressContract

type RunnerIngressContract interface {
	DurableActiveTurnClearer

	SessionAuthorityHolder
	// contains filtered or unexported methods
}

Runner methods the session ingress, local restore, drain, identity, route mount and worker construction call

type RunnerModelContract

type RunnerModelContract interface {
	// contains filtered or unexported methods
}

Runner methods the messaging chat picks, the model and compress mutations and the policy tier call

type RuntimeStartError

type RuntimeStartError struct {
	Reason string
	State  string
}

RuntimeStartError is a start the service manager refused or failed, with the verdict state it reports

func (*RuntimeStartError) Error

func (e *RuntimeStartError) Error() string

type RuntimeStatusUpdate

type RuntimeStatusUpdate struct {
	Fields                map[string]any
	ClearProfilePlatforms bool
	DropProfilePlatforms  string
	KeepPlatforms         []string
}

One runtime status update, Fields holding every explicitly passed keyword with nil standing for None

type RuntimeStatusWriter

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

Persists the latest status snapshot on one background goroutine, newer submissions replacing the pending one

func NewRuntimeStatusWriter

func NewRuntimeStatusWriter(writeFn func(path string, payload *jsonutil.Object) error) *RuntimeStatusWriter

Writer persisting through writeFn, the merged atomic file write when writeFn is nil

func (*RuntimeStatusWriter) Flush

func (w *RuntimeStatusWriter) Flush(timeout time.Duration) bool

Waits boundedly for every snapshot submitted so far

func (*RuntimeStatusWriter) Submit

func (w *RuntimeStatusWriter) Submit(ctx context.Context, path string, payload *jsonutil.Object) int

Queues a deep copy of payload for path and returns its generation

func (*RuntimeStatusWriter) Wait

func (w *RuntimeStatusWriter) Wait(generation int, timeout *time.Duration) (bool, error)

Blocks until generation or a later snapshot persisted, false on timeout or failure, the failure raised without a timeout

type STTClip

type STTClip struct {
	Transcript *string
	Note       string
}

Transcript of one voice clip, nil when transcription failed, with the note that stands in for it

type STTSDrainTask

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

Drain task of one consumer with its completion channel

func (*STTSDrainTask) Done

func (t *STTSDrainTask) Done() bool

Whether the drain task has ended

type SavePromptedOptions

type SavePromptedOptions struct {
	Password            bool
	SuccessMsg, SkipMsg string
	Transform           func(string) string
}

Keyword options of save_prompted, the success message may name {value}

type ScopedLockDirUnusable

type ScopedLockDirUnusable struct {
	Msg   string
	Dir   string
	Cause error
}

The scoped lock directory this token cannot create, read or replace locks in, a permission error

func (*ScopedLockDirUnusable) Error

func (e *ScopedLockDirUnusable) Error() string

func (*ScopedLockDirUnusable) Is

func (e *ScopedLockDirUnusable) Is(target error) bool

func (*ScopedLockDirUnusable) Unwrap

func (e *ScopedLockDirUnusable) Unwrap() error

type SelfPostEndpoint

type SelfPostEndpoint interface {
	SelfPostTarget() (host string, port int, apiKey, modelName string)
}

Bind address, key and model name a stateless adapter's own listener answers on

type SendResult

type SendResult struct {
	Success                bool
	MessageID              any
	Error                  any
	RawResponse            any
	Retryable              bool
	RetryAfter             *float64
	ContinuationMessageIDs []any
	ErrorKind              *string
}

SendResult is the outcome of one adapter send or edit, gateway/platforms/base.py SendResult

func SendChunks

func SendChunks(ctx context.Context, chunks []string, sendOne func(ctx context.Context, chunk string) (*SendResult, error)) (*SendResult, error)

Sends the chunks in order and stops at the first failure, marking a partial overflow after delivered chunks

type ServiceChoiceError

type ServiceChoiceError struct{ Msg string }

ValueError of a service choice that is neither install nor decline

func (*ServiceChoiceError) Error

func (e *ServiceChoiceError) Error() string

func (*ServiceChoiceError) ErrorKind

func (e *ServiceChoiceError) ErrorKind() string

type ServiceIdentityError

type ServiceIdentityError struct {
	Reason  string
	Foreign bool
}

ServiceIdentityError is a binding refusal, Foreign when the service serves another install root

func (*ServiceIdentityError) Error

func (e *ServiceIdentityError) Error() string

type ServiceSetupOptions

type ServiceSetupOptions struct {
	Context     string
	Interactive bool
	Install     bool
}

Keyword arguments of the service setup, an empty Context meaning setup

type ServiceUserError

type ServiceUserError struct{ Msg string }

Raised when the account a system service should run as cannot be chosen or found

func (*ServiceUserError) Error

func (e *ServiceUserError) Error() string

type ServiceVerb

type ServiceVerb func(ctx context.Context, actor Principal, transport tuihost.Transport, request map[string]any) *jsonutil.Object

ServiceVerb answers one verb of the service table with its whole reply frame, nil when the reply goes to the transport later

type SessionAuthorities

type SessionAuthorities struct {
	LaunchKey   string
	Multiplexed bool
	// contains filtered or unexported fields
}

Registry of the session authorities one runtime serves keyed by the home key of each profile home

func NewSessionAuthorities

func NewSessionAuthorities(launchHome string, multiplexed bool) *SessionAuthorities

Registry holding no slot yet for the launch home, multiplexed when the config says so

func (*SessionAuthorities) Active

Authority of the active runtime scope, the launch one unscoped or never multiplexed, nil for an unserved scope

func (*SessionAuthorities) Add

func (s *SessionAuthorities) Add(profileHome string, authority *SessionAuthority, name *string) error

Registers the authority of a home, a nil authority reserving the slot while it is built

func (*SessionAuthorities) Authorities

func (s *SessionAuthorities) Authorities() []*SessionAuthority

Built authorities including retiring ones, a snapshot that skips slots still being built

func (*SessionAuthorities) Contains

func (s *SessionAuthorities) Contains(profileHome string) bool

Whether the home holds a slot, a slot still being built included

func (*SessionAuthorities) ForHome

func (s *SessionAuthorities) ForHome(profileHome string) *SessionAuthority

Authority owning the home, nil when this process does not serve it

func (*SessionAuthorities) Launch

func (s *SessionAuthorities) Launch() (*SessionAuthority, error)

Authority of the launch home, KeyError when the launch slot was never added

func (*SessionAuthorities) Len

func (s *SessionAuthorities) Len() int

Count of built authorities, a slot still being built not counted

func (*SessionAuthorities) ProfileIDs

func (s *SessionAuthorities) ProfileIDs() map[string]bool

Set of profile ids of the serving authorities

func (*SessionAuthorities) ProfileName

func (s *SessionAuthorities) ProfileName(authority *SessionAuthority) (string, bool)

Served profile name of the authority, false for the launch profile

func (*SessionAuthorities) Remove

func (s *SessionAuthorities) Remove(profileHome string) (*SessionAuthority, error)

Drops the slot of a home and returns its authority, refusing the launch slot

func (*SessionAuthorities) Replace

func (s *SessionAuthorities) Replace(profileHome string, authority *SessionAuthority) error

Fills the slot a nil add reserved once the authority exists

func (*SessionAuthorities) Require

func (s *SessionAuthorities) Require(profileHome string) (*SessionAuthority, error)

Authority owning the home, profile_mismatch when this process does not serve it

func (*SessionAuthorities) ServedProfiles

func (s *SessionAuthorities) ServedProfiles() []map[string]any

Profile id and home of each serving authority

func (*SessionAuthorities) Serving

func (s *SessionAuthorities) Serving() []*SessionAuthority

Authorities accepting work, neither a slot still being built nor a retiring one

func (*SessionAuthorities) Starting

func (s *SessionAuthorities) Starting(ctx context.Context, profile string) (string, <-chan struct{}, bool)

Key and started channel of the slot the profile names while its authority is still being built

func (*SessionAuthorities) StartingHomes

func (s *SessionAuthorities) StartingHomes() []string

Keys of every slot whose authority is still being built

type SessionAuthority

type SessionAuthority struct {
	Runner AuthorityRunner

	ProfileID  string
	InstanceID string
	DB         *state.SessionDB
	Epoch      int64
	Sessions   map[string]*LiveSession

	PendingResults map[string]*jsonutil.Object

	Retiring bool
	Retired  bool

	Events            map[string]tuihost.Transport
	HostedRoomService HostedAdmissionChecker
	// contains filtered or unexported fields
}

Gateway owned live sessions and canonical durable FIFO scheduling of one profile store

func APIAuthorityForHome

func APIAuthorityForHome(runner any, profileHome string) (*SessionAuthority, error)

Session authority a runtime reserved for a home, nil when none

func ActiveAuthority

func ActiveAuthority(ctx context.Context, runner any) (*SessionAuthority, error)

Authority of the active runtime scope of a runner

func AllAuthorities

func AllAuthorities(runner any) []*SessionAuthority

Every authority the runner holds, retiring ones included

func AuthorityForHome

func AuthorityForHome(runner any, profileHome string) (*SessionAuthority, error)

Authority serving a profile home, nil when this runtime does not serve it

func AuthorityForProfileID

func AuthorityForProfileID(runner any, profileID string) (*SessionAuthority, error)

Authority serving the profile id home, nil when this runtime does not serve it

func ConversationHead

func ConversationHead(ctx context.Context, runner any, sessionID string) (*SessionAuthority, *string, string, error)

Authority, local owner and row id a repoint of a session onto a messaging lane carries

func InitializeSessionAuthority

func InitializeSessionAuthority(ctx context.Context, runner AuthorityRunner, profileID, instanceID string, db *state.SessionDB, register bool) (*SessionAuthority, error)

Builds the authority of a profile store after exclusive ownership, before any adapter or API connects

func NewSessionAuthority

func NewSessionAuthority(runner AuthorityRunner, profileID, instanceID string, db *state.SessionDB, epoch int64) *SessionAuthority

Authority over a profile store at its runtime epoch

func ProducerScope

func ProducerScope(ctx context.Context, adapter PlatformAdapter, event *MessageEvent) (context.Context, *SessionAuthority, error)

Authority that admits a producer delivery and the context carrying its callback and runtime scope

func RequireActiveAuthority

func RequireActiveAuthority(ctx context.Context, runner any, store func() (*state.SessionDB, error)) (*SessionAuthority, error)

Active scope's authority whose store is the caller's, refused retryably while parked and else profile_mismatch

func ServingAuthorities

func ServingAuthorities(runner any) []*SessionAuthority

Authorities that accept work, no unbuilt slot and none retiring

func TrackTurnWorker

func TrackTurnWorker(ctx context.Context, runner any, worker TurnWorkerHandle, holder sideAgentInterruptible) (*SessionAuthority, error)

Registers a turn worker and its agent holder on the active authority, nil when the runner serves none

func (*SessionAuthority) AdmissionWaiterDone

func (a *SessionAuthority) AdmissionWaiterDone(admissionID string) <-chan struct{}

Channel closed once the admission's waiter resolves, the waiter registered when none is held yet

func (*SessionAuthority) AdmitAutomation

func (a *SessionAuthority) AdmitAutomation(ctx context.Context, adapter PlatformAdapter, event *MessageEvent, identity string, replaces *string, fold []string) (AdmissionReceipt, error)

Commits an automation input of a producer into its owner's FIFO

func (*SessionAuthority) AdmitNative

func (a *SessionAuthority) AdmitNative(ctx context.Context, event *MessageEvent) (AdmissionReceipt, error)

Commits a messaging input before its acknowledgement, in the order its route's inputs arrived

func (*SessionAuthority) AdoptAgent

func (a *SessionAuthority) AdoptAgent(sessionID string, generation int64, agent any)

Installs the turn's agent for the running claim, firing a stop and the steers latched for that generation

func (*SessionAuthority) Attach

func (a *SessionAuthority) Attach(ctx context.Context, actor Principal, ref SessionRef, history bool, replayFrom *ReplayCursor) (SubscriptionSnapshot, error)

Joins a session's event stream and snapshots it, with its transcript unless the viewer pages it itself

func (*SessionAuthority) Authorize

func (a *SessionAuthority) Authorize(ctx context.Context, actor Principal, ref SessionRef, capability string) error

Checks serving, profile, capability and ownership of a session, restoring a stored one into memory

func (*SessionAuthority) AwaitBotReplyPublished

func (a *SessionAuthority) AwaitBotReplyPublished(ctx context.Context, deliveryID string, timeout *time.Duration) error

Waits until the owner's reply watcher for a delivery published its outcome, the timeout bounding the wait

func (*SessionAuthority) CancelOrClaimed

func (a *SessionAuthority) CancelOrClaimed(ctx context.Context, actor Principal, ref SessionRef, admissionID string) (*jsonutil.Object, error)

Cancels a row read queued, returning the started row when the drain claimed it first

func (*SessionAuthority) CancelQueued

func (a *SessionAuthority) CancelQueued(ctx context.Context, actor Principal, ref SessionRef, admissionID string) (AdmissionReceipt, error)

Cancels a queued admission, committing and settling its observers as one tracked task

func (*SessionAuthority) CheckApprovalGeneration

func (a *SessionAuthority) CheckApprovalGeneration(ctx context.Context, sessionID string, generation int64) error

Refuses with a runtime store error when generation is no longer the session's running claim

func (*SessionAuthority) ClaimedTurnStopped

func (a *SessionAuthority) ClaimedTurnStopped(owner string, generation int64) bool

ClaimedTurnStopped reports whether a Stop is latched or delivered for the claimed owner generation

func (*SessionAuthority) CronCancellations

func (a *SessionAuthority) CronCancellations() int

Number of pending cron cancellation latches of the authority

func (*SessionAuthority) DBPath

func (a *SessionAuthority) DBPath() string

Path of the authority's state database, the key the cron owner registry binds by

func (*SessionAuthority) DeferReset

func (a *SessionAuthority) DeferReset(route string, reset func(ctx context.Context) error)

Defers a route's auto reset until the drain settles the executing admission

func (*SessionAuthority) Detach

func (a *SessionAuthority) Detach(ctx context.Context, actor Principal, subscriptionID string, endReason string, orphaned bool) error

Ends a viewer's subscription, the last viewer leaving closing or handing back its session

func (*SessionAuthority) EndExecution

func (a *SessionAuthority) EndExecution(live *LiveSession, sessionID string)

Drops the session's executing generation under its event stream lock once a claimed turn returns

func (*SessionAuthority) ExecutingGeneration

func (a *SessionAuthority) ExecutingGeneration(sessionID string) (int64, bool)

Generation the session is executing, false when no turn holds the running claim

func (*SessionAuthority) FenceRoute

func (a *SessionAuthority) FenceRoute(route string)

Fences a route so its messaging input still capturing or waiting never commits

func (*SessionAuthority) Handle

Handle of one session the authority holds

func (*SessionAuthority) HasLiveSession

func (a *SessionAuthority) HasLiveSession(sessionID string) bool

Whether the authority holds a live session under the id

func (*SessionAuthority) Interrupt

func (a *SessionAuthority) Interrupt(ctx context.Context, actor Principal, ref SessionRef, generation int64) (SessionHandle, error)

Stops the running turn of a generation, latching the stop for the agent the turn has yet to adopt

func (*SessionAuthority) Live

func (a *SessionAuthority) Live(sessionID string) (*LiveSession, bool)

Live session the authority holds for the id and whether it holds one

func (*SessionAuthority) LiveSessionViews

func (a *SessionAuthority) LiveSessionViews() []LiveSessionView

Live sessions the authority holds in session id order, read under the authority lock

func (*SessionAuthority) LogicalOwner

func (a *SessionAuthority) LogicalOwner(ctx context.Context, sessionID string) (string, error)

Compression lineage root of a session, the FIFO and admission identity of its route

func (*SessionAuthority) PendingPrompts

func (a *SessionAuthority) PendingPrompts(sessionID string, generation *int64) ([]*jsonutil.Object, bool)

Pending prompts of a live session's generation after stale ones settle, false when the session is not live

func (*SessionAuthority) PendingStops

func (a *SessionAuthority) PendingStops() map[string]int64

Copy of the stops latched for a turn that adopted no agent yet, by session id

func (*SessionAuthority) PhysicalTarget

func (a *SessionAuthority) PhysicalTarget(ctx context.Context, ref SessionRef) (string, error)

Compression tip of a session, the session itself without one

func (*SessionAuthority) PublishExecution

func (a *SessionAuthority) PublishExecution(sessionID string, generation int64, eventType string, payload any) (bool, error)

Publishes a worker callback's event only while its exact claim still executes

func (*SessionAuthority) PublishRoute

func (a *SessionAuthority) PublishRoute(ctx context.Context, source *SessionSource, sid, route string) (SessionRef, error)

Publishes the live entry of a reserved route and names its lane

func (*SessionAuthority) Receipt

func (a *SessionAuthority) Receipt(ctx context.Context, actor Principal, ref SessionRef, admissionID string) (AdmissionReceipt, error)

Receipt of an admission the caller owns or controls, a terminal row awaiting publication reading as its claim

func (*SessionAuthority) RecoverNativeSessions

func (a *SessionAuthority) RecoverNativeSessions(ctx context.Context, bindings []NativeBinding) (*jsonutil.Object, error)

Binds only server observed native routes and schedules them, each session answering ready or its refusal reason

func (*SessionAuthority) Register

func (a *SessionAuthority) Register(ctx context.Context, source *SessionSource) (SessionRef, error)

Binds a messaging source to its session, the routing entry reserved and the live entry published

func (*SessionAuthority) RegisterApproval

func (a *SessionAuthority) RegisterApproval(ctx context.Context, sessionID string, generation int64, route string, data map[string]any, timeoutS *float64) error

Registers an approval prompt of the running generation with the session's pending controls

func (*SessionAuthority) RegisterClarify

func (a *SessionAuthority) RegisterClarify(ctx context.Context, sessionID string, generation int64, entry *tools.ClarifyEntry, timeoutS *float64) error

Registers a clarify prompt of the running generation with the session's pending controls

func (*SessionAuthority) ReleaseAdmissionWaiter

func (a *SessionAuthority) ReleaseAdmissionWaiter(admissionID string)

Drops an admission's waiter, resolving it with no result unless it already resolved

func (*SessionAuthority) RequireAdmissionOpen

func (a *SessionAuthority) RequireAdmissionOpen() error

Refusal while the runtime drains or retires, nil when admission is open

func (*SessionAuthority) Resolve

func (a *SessionAuthority) Resolve(ctx context.Context, actor Principal, ref SessionRef) (SessionHandle, error)

Handle of a session the actor may read

func (*SessionAuthority) ResolveUnknown

func (a *SessionAuthority) ResolveUnknown(ctx context.Context, actor Principal, ref SessionRef, admissionID string, generation int64) (AdmissionReceipt, error)

Operator acknowledgement that an unknown turn will not finish, resuming the paused FIFO behind it

func (*SessionAuthority) ResolveUnknownAsOwner

func (a *SessionAuthority) ResolveUnknownAsOwner(ctx context.Context, ref SessionRef, admissionID string, generation int64, notice any) (AdmissionReceipt, error)

Resolves an unknown turn past authorization, committing the result this owner captured when it has one

func (*SessionAuthority) Respond

func (a *SessionAuthority) Respond(ctx context.Context, actor Principal, ref SessionRef, generation any, promptID any, response any, kind string) (any, error)

Answers an approval or clarify prompt of the running generation for a subscribed viewer

func (*SessionAuthority) RouteEpoch

func (a *SessionAuthority) RouteEpoch(route string) int

How many messaging stop and new commands fenced a route

func (*SessionAuthority) StampClaim

func (a *SessionAuthority) StampClaim(ctx context.Context, ref SessionRef, live *LiveSession, row *jsonutil.Object) error

Stamps the claim's execution on the stream in the same tracked task as its commit

func (*SessionAuthority) SteerAgent

func (a *SessionAuthority) SteerAgent(ctx context.Context, ref SessionRef, generation int64, text *string) (any, bool, error)

Agent a steer for the running generation reaches, the text latched when the turn adopted none yet

func (*SessionAuthority) SteerRunningGeneration

func (a *SessionAuthority) SteerRunningGeneration(ctx context.Context, sessionID string, generation int64, text string) (any, bool, error)

Agent a steer for the session's running generation reaches, the text latched under the stream lock when none is resident

func (*SessionAuthority) Submit

func (a *SessionAuthority) Submit(ctx context.Context, actor Principal, request Submission, opts SubmitOptions) (AdmissionReceipt, error)

Admits a viewer's input into its session's FIFO, an interactive caller queueing through a restart wait

func (*SessionAuthority) SubscriberCount

func (a *SessionAuthority) SubscriberCount(sessionID string) int

Viewers subscribed to the live session of the id, read under the authority lock, zero when none is live

func (*SessionAuthority) UnserveStopCounts

func (a *SessionAuthority) UnserveStopCounts() (managed, crons, sides int)

Live managed workers, cron cancellations and unabandoned side agents an unserve of the authority stops

type SessionAuthorityHolder

type SessionAuthorityHolder interface {
	SessionAuthority() *SessionAuthority
}

Runner exposing its session authority, the shared runtime owning non command input when present

type SessionAuthorityProtocol

type SessionAuthorityProtocol interface {
	Create(ctx context.Context, actor Principal, request SessionCreate) (SessionHandle, error)
	Resolve(ctx context.Context, actor Principal, ref SessionRef) (SessionHandle, error)
	Attach(ctx context.Context, actor Principal, ref SessionRef, history bool, replayFrom *ReplayCursor) (SubscriptionSnapshot, error)
	Detach(ctx context.Context, actor Principal, subscriptionID string, endReason *string) error
	Submit(ctx context.Context, actor Principal, request Submission) (AdmissionReceipt, error)
	Receipt(ctx context.Context, actor Principal, ref SessionRef, admissionID string) (AdmissionReceipt, error)
	CancelQueued(ctx context.Context, actor Principal, ref SessionRef, admissionID string) (AdmissionReceipt, error)
	Interrupt(ctx context.Context, actor Principal, ref SessionRef, generation int64) (SessionHandle, error)
	Respond(ctx context.Context, actor Principal, ref SessionRef, generation int64, promptID string, response map[string]any) (map[string]any, error)
	Mutate(ctx context.Context, actor Principal, ref SessionRef, revision int64, requestID, action string, arguments map[string]any) (SessionHandle, error)
}

Public session authority surface, live execution state never crossing it

type SessionCompressJob

type SessionCompressJob struct {
	Model      string
	Runtime    map[string]any
	Config     map[string]any
	Options    map[string]any
	Resident   any
	Head       []map[string]any
	Tail       []map[string]any
	Messages   []map[string]any
	FocusTopic *string
	SafeMode   bool
	DB         *state.SessionDB
	Target     string
	// Smallest tail and summary the built in compressor allows
	Aggressive bool
}

One canonical compress summarize the agent side runs under the session's policy scope

type SessionCompressor

type SessionCompressor interface {
	// Compressed transcript of the job, nil when nothing was removed, with the engine that ran
	Summarize(ctx context.Context, job SessionCompressJob) ([]map[string]any, any, error)
	// Whether the engine is the built in compressor
	BuiltinEngine(engine any) bool
	// Ends a one off engine's session, logging a failure
	EndEngine(engine any, sessionID string, messages []map[string]any)
	// Manual compression report every native compress prints
	ManualSummary(before, after []map[string]any, beforeTokens, afterTokens int, engine any) map[string]any
	// Post commit engine boundary and relay and metrics segment hand off
	NotifyCompressionComplete(ctx context.Context, engine any, platform, sessionKey, newSessionID, oldSessionID string)
	// Fires post_compaction for a committed manual compress
	FirePostCompaction(ctx context.Context, sessionID, oldSessionID string, beforeTokens, afterTokens, messagesRemoved any)
	// Rough request estimate of messages with a system prompt and tool schemas
	RequestTokens(ctx context.Context, messages []map[string]any, systemPrompt string, tools []map[string]any) int
	// Rough message only estimate
	MessagesTokens(ctx context.Context, messages []map[string]any) int
	// System prompt and tool schemas an agent sends
	RequestBasis(agent any) (string, []map[string]any)
}

Agent side of a canonical session compress, its context engines and token estimates

var SessionCompress SessionCompressor

Agent side of every canonical compress, assigned at startup by the command wiring

type SessionContext

type SessionContext struct {
	Source                 *SessionSource
	ConnectedPlatforms     []Platform
	HomeChannels           *orderedutil.Map[Platform, *HomeChannel]
	SharedMultiUserSession bool
	SessionKey             string
	SessionID              string
	CreatedAt              *datetime
	UpdatedAt              *datetime
}

Full session context the dynamic system prompt section renders

func BuildSessionContext

func BuildSessionContext(ctx context.Context, source *SessionSource, cfg *GatewayConfig, entry *SessionEntry) *SessionContext

Session context of the source with connected platforms, their home channels and the entry identity

func (*SessionContext) ToDict

func (c *SessionContext) ToDict() *jsonutil.Object

Wire dict of the context with platform values, home channel dicts and isoformat times

type SessionCreate

type SessionCreate struct {
	RequestID string
	Cwd       string
	Source    string
	Policy    map[string]any
}

Session creation request with its launch policy fields

type SessionEntry

type SessionEntry struct {
	SessionKey          string
	SessionID           string
	CreatedAt           datetime
	UpdatedAt           datetime
	Origin              *SessionSource
	DisplayName         *string
	Platform            Platform
	ChatType            string
	Metadata            *jsonutil.Object
	InputTokens         int64
	OutputTokens        int64
	CacheReadTokens     int64
	CacheWriteTokens    int64
	TotalTokens         int64
	EstimatedCostUSD    float64
	CostStatus          string
	LastPromptTokens    int64
	WasAutoReset        bool
	AutoResetReason     *string
	ResetHadActivity    bool
	PrevSessionID       *string
	IsFreshReset        bool
	ExpiryFinalized     bool
	Suspended           bool
	ResumePending       bool
	ResumeReason        *string
	LastResumeMarkedAt  *datetime
	ActiveTurnToken     *string
	ActiveTurnStartedAt *datetime
	ModelOverride       *jsonutil.Object
	TransportProfile    *string
	PromptPin           *jsonutil.Object
	Yolo                *bool
}

Routing index entry mapping a session key to its current session id and metadata

func NewSessionEntry

func NewSessionEntry(sessionKey, sessionID string, createdAt, updatedAt datetime) *SessionEntry

Entry with the dataclass defaults for the given key, id and timestamps

func ResetAndRehomeMessages

func ResetAndRehomeMessages(ctx context.Context, runner AuthorityRunner, sessionKey, oldSessionID string) (*SessionEntry, func(), error)

Compression exhaustion reset with its messaging rows rehomed, for the runner's turn recovery

func SessionEntryFromDict

func SessionEntryFromDict(ctx context.Context, data *jsonutil.Object) (*SessionEntry, error)

Entry rebuilt from its wire form, rejecting traversal ids and keys

func (*SessionEntry) ActiveTurnStartedTimestamp

func (e *SessionEntry) ActiveTurnStartedTimestamp() (float64, bool)

Epoch seconds the entry's active turn marker was stamped at, false without one

func (*SessionEntry) LastResumeMarkedTimestamp

func (e *SessionEntry) LastResumeMarkedTimestamp() (float64, bool)

Epoch seconds of the entry's last resume mark, false when it was never marked

func (*SessionEntry) ResumeMarkerTimestamp

func (e *SessionEntry) ResumeMarkerTimestamp() float64

Epoch seconds of the entry's last resume mark, else of its last update

func (*SessionEntry) ToDict

func (e *SessionEntry) ToDict() *jsonutil.Object

Wire form of the entry in its fixed key order

type SessionEntryError

type SessionEntryError struct{ Kind, Msg string }

Error raised by SessionEntryFromDict for a malformed or unsafe entry

func (*SessionEntryError) Error

func (e *SessionEntryError) Error() string

func (*SessionEntryError) ErrorKind

func (e *SessionEntryError) ErrorKind() string

Kind label of the error, the one receipt checks and failure logs classify it by

type SessionEventObserver

type SessionEventObserver struct {
	Observe func(frame *jsonutil.Object)
}

Synchronous same goroutine recipient of every published frame

type SessionEvents

type SessionEvents struct {
	Lock   syncutil.ReentrantMutex
	Fanout *tuihost.FanoutTransport

	Epoch    string
	Sequence int

	Execution  *jsonutil.Object
	Observers  map[*SessionEventObserver]bool
	OnOverflow func(transport tuihost.Transport)
	// contains filtered or unexported fields
}

Authority local subscription ordering over the bounded fanout and the shared replay cache

func NewSessionEvents

func NewSessionEvents() *SessionEvents

Event stream under a private replay key freed when the stream is collected

func (*SessionEvents) CatchUp

func (e *SessionEvents) CatchUp(transport tuihost.Transport, epoch string, sequence int)

Writes a joining transport the frames published after its replay cursor, the caller holding Lock

func (*SessionEvents) Publish

func (e *SessionEvents) Publish(sessionID any, payload any, eventType string, execution *jsonutil.Object) bool

Stamps, records and fans out one event frame, true when a live viewer or observer took it

func (*SessionEvents) Release

func (e *SessionEvents) Release()

Frees the replay frames of a session that ended with no viewer left

func (*SessionEvents) Since

func (e *SessionEvents) Since(epoch string, sequence int) *jsonutil.Object

Replay window after a cursor, empty and snapshot required when the cursor fell outside it

func (*SessionEvents) Watermark

func (e *SessionEvents) Watermark() (string, int)

Current replay epoch and sequence, a fresh epoch once the shared cache evicted this session

type SessionHandle

type SessionHandle struct {
	Ref                 SessionRef
	InstanceID          string
	AuthorityEpoch      int64
	Revision            int64
	ExecutionGeneration int64
	ExecutionState      string
}

Owner view of one session with its epoch, revision and execution generation

type SessionIDPeeker

type SessionIDPeeker interface {
	PeekSessionID(sessionKey string) (string, bool)
}

Optional routing index mapping a session key to its transcript session id

type SessionRef

type SessionRef struct {
	ProfileID string
	SessionID string
}

Profile scoped session identity

func CreateLocalSession

func CreateLocalSession(ctx context.Context, a *SessionAuthority, actor Principal, params map[string]any) (SessionRef, error)

Stages, commits and publishes a local session inline for synchronous callers with no trusted policy

func CreatePeerBotChat

func CreatePeerBotChat(ctx context.Context, a *SessionAuthority, actor Principal) (*SessionRef, error)

Mints the canonical Bot Chat for a peer as tracked owner work a cancelled caller cannot abandon midway

type SessionRuntimeFacts

type SessionRuntimeFacts interface {
	Provider() string
	BaseURL() string
	APIMode() string
	ReasoningConfig() map[string]any
}

Route and effort a built agent reports as its session's own, mid voice turn included

type SessionSchedule

type SessionSchedule func(ctx context.Context, a *SessionAuthority, ref SessionRef) error

Step that schedules the FIFO drain of a session, the SessionAuthority._schedule method

func SwapSessionSchedule

func SwapSessionSchedule(schedule SessionSchedule) SessionSchedule

Installs the scheduling step every admission reaches and returns the one it replaced

type SessionSource

type SessionSource struct {
	Platform                  Platform
	ChatID                    string
	ChatName                  *string
	ChatType                  string
	UserID                    *string
	UserName                  *string
	ThreadID                  *string
	ChatTopic                 *string
	UserIDAlt                 *string
	ChatIDAlt                 *string
	IsBot                     bool
	ScopeID                   *string
	GuildID                   *string
	ParentChatID              *string
	MessageID                 *string
	RoleAuthorized            bool
	Profile                   *string
	ProfileRouteRejected      bool
	AutoThreadCreated         bool
	AutoThreadInitialName     *string
	ProspectiveThreadID       *string
	DeliveredViaUpstreamRelay bool
	DetachedRoute             *string
	// contains filtered or unexported fields
}

SessionSource is where a message originated, routing responses and recording cron delivery origin

func DetachedLiveSource

func DetachedLiveSource(runner AuthorityRunner, store *SessionStore, key string) (*SessionSource, error)

Source of the conversation still live on a detached key, nil when none is

func ReplaceSource

func ReplaceSource(source *SessionSource, edit func(*SessionSource)) *SessionSource

Copy of the source with its wire invisible provenance kept and the given edit applied

func SessionEnvSource

func SessionEnvSource(ctx context.Context, runner any, source *SessionSource) (*SessionSource, error)

SessionEnvSource is the source a turn's session variables name, the local view for a conversation its chat moved past

func SessionSourceFromDict

func SessionSourceFromDict(ctx context.Context, data map[string]any) (*SessionSource, error)

Source rebuilt from its wire dict, an unknown platform failing as Platform does

func (*SessionSource) Description

func (s *SessionSource) Description() string

Human readable description of the source with its thread when it has one

func (*SessionSource) Normalize

func (s *SessionSource) Normalize() *SessionSource

Mirrors scope id and the deprecated guild id onto each other with scope id winning and defaults the chat type

func (*SessionSource) SetTransportAdapterRef

func (s *SessionSource) SetTransportAdapterRef(adapter PlatformAdapter)

Binds the adapter that received the message, the transport ref the base adapter stamps

func (*SessionSource) ToDict

func (s *SessionSource) ToDict() *jsonutil.Object

Byte stable wire layout with the always present fields then the truthy optionals around the scope pair

func (*SessionSource) TransportAdapterRef

func (s *SessionSource) TransportAdapterRef() PlatformAdapter

Adapter that received the message, nil when no transport ref was stamped

type SessionStore

type SessionStore struct {
	SessionsDir string
	Config      *GatewayConfig
	// Called with the key, session id and origin once a route names another conversation
	RouteNamed func(sessionKey, sessionID string, origin *SessionSource)
	// Called with the cause when transcript rows stop reaching the store and wait in the spool
	StoreFailed func(err error)
	// contains filtered or unexported fields
}

Gateway routing index and transcripts over SQLite with the sessions.json mirror

func NewSessionStore

func NewSessionStore(ctx context.Context, sessionsDir string, config *GatewayConfig, hasActiveProcessesFn func(sessionKey string) (bool, error)) *SessionStore

Store over the sessions dir priming the state database handle of the active scope

func (*SessionStore) AdvanceCompressionSession

func (s *SessionStore) AdvanceCompressionSession(ctx context.Context, sessionKey, expectedSessionID, targetSessionID string) (*SessionEntry, error)

Compare and swap advance of one route along a verified compression lineage, nil when the route moved

func (*SessionStore) AppendToTranscript

func (s *SessionStore) AppendToTranscript(ctx context.Context, sessionID string, message map[string]any, skipDB bool) error

Appends a message through the reroute chain under the drain lock, a skipped DB write doing nothing

func (*SessionStore) ChatLabels

func (s *SessionStore) ChatLabels(ctx context.Context, platform Platform, scopeID *string, chatID string) (chatName, chatTopic any, ok bool, err error)

Chat name and topic last recorded, ok false when none was, an error when the store is unreadable

func (*SessionStore) ClearDirtyTranscript

func (s *SessionStore) ClearDirtyTranscript(sessionID string)

Drops the dirty transcript mark of the session

func (*SessionStore) ClearResumePending

func (s *SessionStore) ClearResumePending(ctx context.Context, sessionKey string) (bool, error)

Clears the resume pending flag after a resumed turn, true when it was set

func (*SessionStore) ClearTurnActive

func (s *SessionStore) ClearTurnActive(ctx context.Context, sessionKey, token string) (bool, error)

Compare and swap clear of the active turn marker, false when a newer turn owns it

func (*SessionStore) CloseAllDBHandles

func (s *SessionStore) CloseAllDBHandles()

Closes every session database handle this store opened

func (*SessionStore) DB

Pinned database or the one of the active scope, a live system guard returned as the error

func (*SessionStore) DBForKey

func (s *SessionStore) DBForKey(ctx context.Context, sessionKey string) SessionStoreDB

Session database a routing key resolves to

func (*SessionStore) DBForSessionID

func (s *SessionStore) DBForSessionID(ctx context.Context, sessionID string) SessionStoreDB

Database holding the session transcript, nil when none resolves

func (*SessionStore) DBHandleCache

func (s *SessionStore) DBHandleCache() *RecoverableHandleCache

Scope following handle cache the store opens its state.db through, nil before the store opened one

func (*SessionStore) DiscardActiveTurnMarkers

func (s *SessionStore) DiscardActiveTurnMarkers(ctx context.Context) (int, error)

Clears orphan turn markers after a verified clean shutdown

func (*SessionStore) FenceRetiredRoutes

func (s *SessionStore) FenceRetiredRoutes(ctx context.Context, sessionIDs []string, namespace string, expiring []string) error

Durably retires the ids in the routing index's own database, failing when it cannot take the fence

func (*SessionStore) FilterLoadedEntries

func (s *SessionStore) FilterLoadedEntries(ctx context.Context, keep func(entry *SessionEntry) bool) []*SessionEntry

Loaded routing entries the keep function selects, read under the store lock after loading

func (*SessionStore) GenerateSessionKey

func (s *SessionStore) GenerateSessionKey(ctx context.Context, source *SessionSource) (string, error)

Session key the store derives for source

func (*SessionStore) GetModelOverride

func (s *SessionStore) GetModelOverride(ctx context.Context, sessionKey string) *jsonutil.Object

Copy of the persisted model override, nil when none

func (*SessionStore) GetOrCreateSession

func (s *SessionStore) GetOrCreateSession(ctx context.Context, source *SessionSource, forceNew, touchActivity bool) (*SessionEntry, error)

Single flight lookup or create per routing key, overlapping callers sharing the owner's result

func (*SessionStore) GetPromptPin

func (s *SessionStore) GetPromptPin(ctx context.Context, sessionKey string, expectedSessionID *string) *jsonutil.Object

Copy of the prompt pin while the route still owns the expected session, nil otherwise

func (*SessionStore) GetSessionMetadata

func (s *SessionStore) GetSessionMetadata(ctx context.Context, sessionKey, key string, def any) any

Metadata value stored on a live entry, the default when absent

func (*SessionStore) HasAnySessions

func (s *SessionStore) HasAnySessions(ctx context.Context) bool

Whether any session was ever created, state.db counting ended sessions

func (*SessionStore) HasInputOwner

func (s *SessionStore) HasInputOwner(ctx context.Context, sessionID, owner string) (bool, error)

Whether the accepted input owner appears on the live continuation or its compression ancestors

func (*SessionStore) HasPlatformMessageID

func (s *SessionStore) HasPlatformMessageID(ctx context.Context, sessionID, platformMessageID string) bool

Whether a message with the platform message id is persisted, false without a store or on a failed lookup

func (*SessionStore) IsPublishedCompressionChild

func (s *SessionStore) IsPublishedCompressionChild(ctx context.Context, parentSessionID, childSessionID string) bool

Whether the child is an atomically published compression continuation of the parent, false on any error

func (*SessionStore) IsSessionEndedInDB

func (s *SessionStore) IsSessionEndedInDB(ctx context.Context, sessionID, sessionKey string) bool

Whether the session row is ended in the profile store that owns the session key

func (*SessionStore) ListSessions

func (s *SessionStore) ListSessions(ctx context.Context, activeMinutes *int) []*SessionEntry

Every routing entry newest first, only those active within the minutes when given

func (*SessionStore) LoadTranscript

func (s *SessionStore) LoadTranscript(ctx context.Context, sessionID string) ([]any, error)

Every message of the session's canonical transcript, a failed read raising TranscriptReadError

func (*SessionStore) LoadedEntry

func (s *SessionStore) LoadedEntry(ctx context.Context, sessionKey string) *SessionEntry

Loaded index entry of a routing key, nil when the key has none

func (*SessionStore) LookupBySessionID

func (s *SessionStore) LookupBySessionID(ctx context.Context, sessionID string) *SessionEntry

Live entry routing to the persisted session id, nil when none

func (*SessionStore) LookupBySessionKey

func (s *SessionStore) LookupBySessionKey(ctx context.Context, sessionKey string) *SessionEntry

Persisted routing entry for the exact key, nil when none

func (*SessionStore) LookupSessionIDUnderLock

func (s *SessionStore) LookupSessionIDUnderLock(ctx context.Context, sessionKey string) string

Session id of the route read under the store lock, empty when the store holds no entry

func (*SessionStore) MarkResumePending

func (s *SessionStore) MarkResumePending(ctx context.Context, sessionKey, reason string) (bool, error)

Marks the session resumable after a restart interruption unless it is suspended

func (*SessionStore) MarkTurnActive

func (s *SessionStore) MarkTurnActive(ctx context.Context, sessionKey string) (string, error)

Persists ownership of the running turn and returns its token, empty when the entry is missing

func (*SessionStore) PeekSessionID

func (s *SessionStore) PeekSessionID(sessionKey string) (string, bool)

Session id the key routes to under the lock, false when unknown

func (*SessionStore) PersistRotatedCompressionChild

func (s *SessionStore) PersistRotatedCompressionChild(ctx context.Context, parentSessionID, childSessionID string, messages []map[string]any) bool

Makes a rotated compression child durable, a published child already is, anything else gets rewritten

func (*SessionStore) PinDB

func (s *SessionStore) PinDB(db SessionStoreDB)

Pins the session database for every later read, nil selecting the JSONL fallback

func (*SessionStore) ProfileHomeForKey

func (s *SessionStore) ProfileHomeForKey(sessionKey string) string

Profile home that owns a session key, empty for the default profile

func (*SessionStore) PruneOldEntries

func (s *SessionStore) PruneOldEntries(ctx context.Context, maxAgeDays int) (int, error)

Drops routing entries idle past the age keeping suspended and busy ones, zero or less disables

func (*SessionStore) PurgeProfileRouting

func (s *SessionStore) PurgeProfileRouting(ctx context.Context, profile string) (int, error)

Drops a deleted profile's live routing entries and persists the drop

func (*SessionStore) RecordChatLabels

func (s *SessionStore) RecordChatLabels(ctx context.Context, source *SessionSource) (bool, error)

Persists the source's chat name and topic as observed now, false when no database handle exists

func (*SessionStore) RecordGatewaySessionPeer

func (s *SessionStore) RecordGatewaySessionPeer(ctx context.Context, sessionID, sessionKey string, source *SessionSource) error

Records the platform peer of a gateway session in the state database

func (*SessionStore) RecoverInterruptedTurns

func (s *SessionStore) RecoverInterruptedTurns(ctx context.Context, maxAgeSeconds int) (int, error)

Promotes crash left turn markers into resume pending and returns how many were newly promoted

func (*SessionStore) RekeyProfileRouting

func (s *SessionStore) RekeyProfileRouting(ctx context.Context, oldName, newName string) (int, error)

Rekeys the live routing index from one profile namespace to another refusing collisions

func (*SessionStore) RemoveBySessionID

func (s *SessionStore) RemoveBySessionID(ctx context.Context, sessionID string) (int, error)

Drops every routing entry naming the hard deleted session and persists the drop

func (*SessionStore) ReplayHeldTranscripts

func (s *SessionStore) ReplayHeldTranscripts(ctx context.Context) (int, int)

Writes every spooled and queued row of every waiting session in order, returning rows written and sessions still waiting

func (*SessionStore) ResetSession

func (s *SessionStore) ResetSession(ctx context.Context, sessionKey string, displayName *string) (*SessionEntry, error)

Forces a reset onto a fresh session id, local routes through the authority reset

func (*SessionStore) ResolveProfileForKey

func (s *SessionStore) ResolveProfileForKey(source *SessionSource) (any, error)

Profile namespace for session keys, nil when multiplexing is off

func (*SessionStore) ResolveSessionIDForKey

func (s *SessionStore) ResolveSessionIDForKey(ctx context.Context, sessionKey string, notAfter *float64) (string, SessionStoreDB)

Session id and owning store for a key during shutdown flush recovery, never minting a session

func (*SessionStore) RetireRuntimeSessions

func (s *SessionStore) RetireRuntimeSessions(sessionIDs []string)

Publishes a committed retirement by dropping every entry naming the ids

func (*SessionStore) RewindSession

func (s *SessionStore) RewindSession(ctx context.Context, sessionID string, n int, requireRetryableComposite bool) (map[string]any, error)

Backs up n user turns by soft delete, nil without a store or rewindable turn, a replay policy ValueError raised

func (*SessionStore) RewriteTranscript

func (s *SessionStore) RewriteTranscript(ctx context.Context, sessionID string, messages []map[string]any, activeOnly, rejectActiveTurnLease bool) bool

Replaces a session's transcript under the drain lock, true when it lands or no store exists

func (*SessionStore) RoutingDB

func (s *SessionStore) RoutingDB(ctx context.Context) SessionStoreDB

The one store owning the routing index whatever scope is active, nil when it cannot be opened

func (*SessionStore) RoutingHome

func (s *SessionStore) RoutingHome() string

Home of the routing index the store owns, empty before initialization

func (*SessionStore) Save

func (s *SessionStore) Save(ctx context.Context) error

Persists the session index under the store lock

func (*SessionStore) SetModelOverride

func (s *SessionStore) SetModelOverride(ctx context.Context, sessionKey string, override any) error

Persists or clears the model override with its non secret keys only, durable before published

func (*SessionStore) SetPromptPin

func (s *SessionStore) SetPromptPin(ctx context.Context, sessionKey string, pin any, expectedSessionID *string) (bool, error)

Persists the prompt pin unless the route moved off the expected session, the candidate durable first

func (*SessionStore) SetSessionMetadata

func (s *SessionStore) SetSessionMetadata(ctx context.Context, sessionKey, key string, value any) (bool, error)

Persists a small JSON value on the entry without advancing its activity clock

func (*SessionStore) SetSessionYolo

func (s *SessionStore) SetSessionYolo(ctx context.Context, sessionKey string, enabled *bool) (bool, error)

Persists the lane yolo toggle, false when the key has no entry or it is unchanged

func (*SessionStore) SpoolHeldTranscripts

func (s *SessionStore) SpoolHeldTranscripts(ctx context.Context) int

Spools every queued row before shutdown, a row the spool refuses written to sessions/<id>.jsonl as the last copy

func (*SessionStore) StripRetiredMirrorRoutes

func (s *SessionStore) StripRetiredMirrorRoutes(ctx context.Context, sessionIDs []string) error

Drops from an existing sessions.json every retired route, only those naming the ids when given

func (*SessionStore) SuspendSession

func (s *SessionStore) SuspendSession(ctx context.Context, sessionKey string) (bool, error)

Marks the session suspended so its next access auto resets, true when it existed

func (*SessionStore) SwitchSession

func (s *SessionStore) SwitchSession(ctx context.Context, sessionKey, targetSessionID string, expectedSessionID *string, preservePromptPin bool) (*SessionEntry, error)

Points the key at an existing session, ending the current row and reopening the target

func (*SessionStore) TranscriptTailRole

func (s *SessionStore) TranscriptTailRole(ctx context.Context, sessionID string) string

Role of the newest live conversation row on the route reads follow, empty when none or unreadable

func (*SessionStore) UpdateSession

func (s *SessionStore) UpdateSession(ctx context.Context, sessionKey string, lastPromptTokens *int64, touchActivity bool) error

Updates lightweight metadata after an interaction, internal turns leaving the activity clock alone

type SessionStoreDB

type SessionStoreDB interface {
	GetSession(ctx context.Context, sessionID string) (*jsonutil.Object, error)
	GetMeta(ctx context.Context, key string) (string, bool, error)
	SetMeta(ctx context.Context, key, value string) error
	SessionCountGE(ctx context.Context, n int) (bool, error)
	CreateSession(n state.NewSession) error
	EndSession(sessionID, endReason string) error
	ReopenSession(ctx context.Context, sessionID string) error
	GetCompressionTip(ctx context.Context, sessionID string) (string, error)
	GetMessagesAsConversation(ctx context.Context, sessionID string, o state.ConversationOptions) ([]map[string]any, error)
	LocalReceipt(ctx context.Context, sessionID string) (*jsonutil.Object, error)
	RouteRetired(ctx context.Context, sessionKey, entryJSON string) (bool, error)
	GetCompressionLineage(ctx context.Context, sessionID string) ([]string, error)
	ExecuteWrite(ctx context.Context, fn func(conn state.SQLiteConn) error) error
}

Session database surface the store reads and writes, satisfied by the state SessionDB and test doubles

type SetupFns

type SetupFns struct {
	Prompt          func(question, def string, password bool) string
	PromptYesNo     func(question string, def bool) bool
	PromptChoice    func(question string, choices []string, def int) int
	PromptChecklist func(title string, items []string, preSelected []int) []int
	PrintHeader     func(title string)
	Info            func(lines ...any)
	PrintInfo       func(text string)
	PrintSuccess    func(text string)
	PrintWarning    func(text string)
	PrintError      func(text string)
	GetEnvValue     func(ctx context.Context, key string) (string, error)
	SaveEnvValue    func(ctx context.Context, key, value string) error
	IcebathHome     func(ctx context.Context) string
}

The functions platform wizards resolve at call time, a table tests replace like the patched module

type SetupPlatform

type SetupPlatform struct {
	Key, Label, Emoji, TokenVar, InstallHint string
	SetupInstructions                        []string
	Vars                                     []SetupVar
	Entry                                    *PlatformEntry
}

One messaging platform row of the setup menu, a built in form or a registry plugin entry

func AllPlatforms

func AllPlatforms(ctx context.Context) []SetupPlatform

Built in forms plus registry plugin platforms, discovering plugins first and hiding Matrix on Windows

type SetupVar

type SetupVar struct {
	Name, Prompt, Help    string
	Password, IsAllowlist bool
}

One setup form variable of a built in platform

type SharedIngress

type SharedIngress struct {
	App  *HTTPApp
	Base string
	URL  string
}

Published shared listener application of a secondary's adapter with its forwarding base and callback URL

type SharedIngressApp

type SharedIngressApp struct {
	Adapter PlatformAdapter
	App     *HTTPApp
}

Shared listener adapter and its app for one served named profile

func SharedIngressApps

func SharedIngressApps(runner any, profile string) []SharedIngressApp

Every shared listener app of a named served profile, nothing for default or an unknown profile

type ShutdownWatchdogOptions

type ShutdownWatchdogOptions struct {
	Done       *syncutil.Event
	SnapshotFn func() (any, error)
	ExitCode   *int
	DumpPath   string
	Name       string
}

Keyword options of the shutdown watchdog, nil ExitCode is 1 and empty DumpPath and Name take the defaults

type SideAgentHolder

type SideAgentHolder = sideAgentHolder

Holder the side agent ledger counts, abandoned once its work no longer holds the owner

type SilenceMarkerStreamHold

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

SilenceMarkerStreamHold gates live reply deltas that may be or end in a silence marker

func (*SilenceMarkerStreamHold) Feed

func (h *SilenceMarkerStreamHold) Feed(delta string) string

Part of the reply safe to show now, holding a possible bare or closing marker

func (*SilenceMarkerStreamHold) Finish

func (h *SilenceMarkerStreamHold) Finish() string

Remainder the completed reply delivers, nothing for a bare marker

type SkillCommandEntry

type SkillCommandEntry struct{ Name, Description, CmdKey string }

Skill autocomplete row with its description and the command key it runs

type SlackAPIError

type SlackAPIError struct {
	Message  string
	Response map[string]any
}

Slack Web API failure carrying the decoded response body

func (*SlackAPIError) Error

func (e *SlackAPIError) Error() string

type SlackDirectoryAdapter

type SlackDirectoryAdapter interface {
	SlackTeamClients() *orderedutil.Map[string, SlackDirectoryClient]
}

Slack adapter exposing one Web API client per connected workspace

type SlackDirectoryClient

type SlackDirectoryClient interface {
	UsersConversations(ctx context.Context, types string, excludeArchived bool, limit int, cursor string) (map[string]any, error)
	ConversationsInfo(ctx context.Context, channel string) (map[string]any, error)
	UsersInfo(ctx context.Context, user string) (map[string]any, error)
}

Slack Web API calls the directory makes, each returning the decoded response body

type SlashAccessPolicy

type SlashAccessPolicy struct {
	Enabled             bool
	AdminUserIDs        map[string]struct{}
	UserAllowedCommands map[string]struct{}
}

Resolved slash command gating of one platform and scope

func PolicyForRunnerSource

func PolicyForRunnerSource(runner SlashAccessRunner, source *SessionSource) SlashAccessPolicy

Slash policy from the profile whose bot received the source, failing closed for an uncached served profile

func PolicyForSource

func PolicyForSource(gatewayConfig *GatewayConfig, source *SessionSource) SlashAccessPolicy

Slash gating policy for a source, a blank chat type resolving to whichever scope is gated

func PolicyFromExtra

func PolicyFromExtra(extra map[string]any, scope string) SlashAccessPolicy

Policy of one scope from a platform extra dict, the DM command list falling back to the group list

func (SlashAccessPolicy) CanRun

func (p SlashAccessPolicy) CanRun(userID any, canonicalCmd string) bool

Admins run anything, other users the help and whoami floor plus the allowed command list

func (SlashAccessPolicy) IsAdmin

func (p SlashAccessPolicy) IsAdmin(userID any) bool

True for everyone while gating is off, otherwise only for listed admin ids

type SlashAccessRunner

type SlashAccessRunner interface {
	RunnerConfig() *GatewayConfig
	PrimaryProfileName() string
	ProfileConfigs() map[string]*GatewayConfig
}

Runner state the profile aware slash policy reads

type SlashCommandEntry

type SlashCommandEntry struct{ Name, Description, ArgsHint string }

Slash command row of the command registry or a plugin with its description and args hint

type SourceFields

type SourceFields struct {
	ChatName              *string
	ChatType              string
	UserID                *string
	UserName              *string
	ThreadID              *string
	ChatTopic             *string
	UserIDAlt             *string
	ChatIDAlt             *string
	IsBot                 bool
	ScopeID               *string
	GuildID               *string
	ParentChatID          *string
	MessageID             *string
	RoleAuthorized        bool
	AutoThreadCreated     bool
	AutoThreadInitialName *string
}

Keyword fields of BuildSource beyond the chat id, unset pointers standing for None

type SourceProfileResolver

type SourceProfileResolver interface {
	ProfileNameForSource(ctx context.Context, source *SessionSource, adapterProfile *string) (*string, error)
}

Runner seam naming the routed profile of a source, a refused route raising *ProfileRouteRejected

type SpawnedGateway

type SpawnedGateway interface {
	Poll() (int, bool)
	Pid() int
}

SpawnedGateway is a requested daemon, polled for an exit status without waiting

func SpawnUnmanagedGateway

func SpawnUnmanagedGateway(ctx context.Context, profileHome string, deadline float64, idleExit, force bool) (SpawnedGateway, error)

Requests a detached daemon for profile home with its own env, never readiness, persistence or a replace

type SpoolSessionResolver

type SpoolSessionResolver func(ctx context.Context, sessionKey string, notAfter *float64) (string, SessionStoreDB)

Session key to id resolution with the store owning the key, an empty id or nil store meaning unresolved

type StaleLeaseError

type StaleLeaseError struct{ *DriverStateError }

Lease generation that can no longer mutate room state

func (*StaleLeaseError) Unwrap

func (e *StaleLeaseError) Unwrap() error

type StaleTaskError

type StaleTaskError struct{ *DriverStateError }

Obsolete task attempt or cancellation trying to commit

func (*StaleTaskError) Unwrap

func (e *StaleTaskError) Unwrap() error

type StandaloneSendPolicy

type StandaloneSendPolicy struct {
	Label                  string
	Media                  bool
	AllSends               bool
	Captionable            bool
	EmptyListBetweenChunks bool
	ForwardForceDocument   bool
	Mentions               bool
	TextDirect             bool
}

Routing rules for sending a platform through its standalone sender instead of the live adapter

type StartupRestoreTaskJoiner

type StartupRestoreTaskJoiner interface {
	JoinStartupRestore(ctx context.Context, name string, wait func(ctx context.Context) error)
}

Runner seam holding the startup restore gate open until an adapter recovery task finishes

type StartupWatchdogHandle

type StartupWatchdogHandle struct {
	TimeoutS float64
	ExitCode int
	// contains filtered or unexported fields
}

Disarm and inspect handle of the armed startup watchdog goroutine

func (*StartupWatchdogHandle) Disarm

func (h *StartupWatchdogHandle) Disarm()

Stands the watchdog down unless the fire transition already claimed the state

func (*StartupWatchdogHandle) IsAlive

func (h *StartupWatchdogHandle) IsAlive() bool

True while the watchdog goroutine is still running

func (*StartupWatchdogHandle) Kick

func (h *StartupWatchdogHandle) Kick(extraS any)

Pushes the deadline out to now plus the timeout plus extra seconds, garbage counting as zero

func (*StartupWatchdogHandle) Lease

func (h *StartupWatchdogHandle) Lease(expectedS any, phase string)

Claims a progress lease of up to expected seconds for a phase, clamped per call

type StatusMetadataForTurner

type StatusMetadataForTurner interface {
	StatusMetadataForTurn(chatID, anchor string, metadata map[string]any) map[string]any
}

Optional adapter hook fixing the status thread of a turn on its own triggering message

type SteerReceiver

type SteerReceiver interface {
	Steer(text string) bool
}

Agent seam taking a mid turn steer

type StepRunner

type StepRunner = stepRunner

Runner that performs one yielded write, for sequences built outside the package

type StopTiming

type StopTiming struct {
	RestartDrainTimeout   *float64
	StopRequestedBySignal bool
	LaunchdExitTimeoutS   *float64
}

Stop timing attributes a runner carries, a nil drain is the shipped default

type StoreOutageMessage

type StoreOutageMessage struct {
	Event *MessageEvent
	Path  string
}

One store outage copy turned back into an inbound message, with the file that keeps it until its turn settles

func TakeStoreOutageMessages

func TakeStoreOutageMessages(ctx context.Context, store *SessionStore) []StoreOutageMessage

Store outage copies of the spool rebuilt as inbound messages of their chats in arrival order, copies the store kept deleted

type StoredRoomLink struct {
	RoomID              string
	MemberID            string
	TargetURL           string
	TargetProfile       string
	Grant               string
	Catalog             *GatewayRoomCatalog
	CancellationScopeID string
	TraceID             string
	TransportSecurity   string
	Status              string
	UpdatedAt           float64
}

Negotiated hosted room link, its grant never formatted

func LoadRoomLinks(ctx context.Context, dbPath string) ([]StoredRoomLink, error)

Every stored link, failing on the first malformed row

func LoadRoomLinksTolerant

func LoadRoomLinksTolerant(ctx context.Context, dbPath string) ([]StoredRoomLink, []string, error)

Healthy stored links, malformed rows quarantined by identity

func MakeStoredRoomLink(roomID, memberID, targetURL, targetProfile, grant string, catalog *GatewayRoomCatalog, cancellationScopeID, traceID string) (StoredRoomLink, error)

Fresh ready link of a negotiated route

func StoredRoomLinkFromMapping

func StoredRoomLinkFromMapping(value any) (StoredRoomLink, error)

Validated stored link of a mapping

func StoredRoomLinkFromRecord

func StoredRoomLinkFromRecord(value map[string]any) (StoredRoomLink, error)

Validated stored link of a SQLite record, its catalog JSON decoded

func (StoredRoomLink) AsRecord

func (l StoredRoomLink) AsRecord() (map[string]any, error)

SQLite record of the link with its catalog serialized

func (StoredRoomLink) CatalogMapping

func (l StoredRoomLink) CatalogMapping() *jsonutil.Object

Canonical catalog mapping of the link

func (StoredRoomLink) String

func (l StoredRoomLink) String() string

Field view of the link without its grant

type StormInfo

type StormInfo struct {
	Count    int
	WindowS  float64
	BackoffS float64
}

Respawn storm check result, start count in the window and the backoff to sleep

func RecordStartAndCheckStorm

func RecordStartAndCheckStorm(ctx context.Context, h string, maxStarts int, windowS, backoffCapS float64) *StormInfo

Records this start in gateway-starts.log, a storm reported past maxStarts in the window, bookkeeping failures swallowed

type StreamBoundary

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

Future of an interaction boundary, true once the consumer processed it cleanly

func (*StreamBoundary) Done

func (b *StreamBoundary) Done() <-chan struct{}

Channel closed once the boundary settled

func (*StreamBoundary) Settled

func (b *StreamBoundary) Settled() bool

Whether the boundary settled

func (*StreamBoundary) Wait

func (b *StreamBoundary) Wait(ctx context.Context) (bool, error)

Outcome of a settled boundary, waiting until it settles or ctx ends

type StreamConsumerConfig

type StreamConsumerConfig struct {
	EditInterval           float64
	BufferThreshold        int
	Cursor                 string
	BufferOnly             bool
	FreshFinalAfterSeconds float64
	Transport              string
	ChatType               string
}

Runtime config of one stream consumer

func DefaultStreamConsumerConfig

func DefaultStreamConsumerConfig() *StreamConsumerConfig

Config carrying the dataclass defaults

type StreamConsumerOptions

type StreamConsumerOptions struct {
	Config           *StreamConsumerConfig
	Metadata         map[string]any
	OnNewMessage     func()
	OnBeforeFinalize func(ctx context.Context)
	InitialReplyToID string
	RunStillCurrent  func() bool
}

Options of a stream consumer beyond its adapter and chat

type StreamEvent

type StreamEvent interface {
	// contains filtered or unexported methods
}

StreamEvent is the closed union of transport events the agent worker emits to the stream consumer

type StreamFlushSignal

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

Barrier a worker thread blocks on until the consumer delivered everything queued before it

type StreamSink

type StreamSink interface {
	OnDelta(text string)
	OnSegmentBreak()
	OnCommentary(text string)
}

StreamSink is the stream consumer surface the adapter renders message events onto

type StreamTruncater

type StreamTruncater interface {
	TruncateMessage(content string, maxLength int, lenFn func(string) int) []string
}

Adapter with its own message splitter for stream overflow

type StreamingConfig

type StreamingConfig struct {
	Enabled                bool
	Transport              string
	EditInterval           float64
	BufferThreshold        int
	Cursor                 any
	FreshFinalAfterSeconds float64
}

Real time token streaming to messaging platforms

func DefaultStreamingConfig

func DefaultStreamingConfig() StreamingConfig

Streaming config with the dataclass defaults

func StreamingConfigFromDict

func StreamingConfigFromDict(raw any) StreamingConfig

Streaming config of a mapping, mode as a transport alias that also implies enabled

func (StreamingConfig) EnabledFor

func (s StreamingConfig) EnabledFor(platformOverride any) bool

Effective streaming for one platform, a per platform value only narrowing the global switch

func (StreamingConfig) GloballyEnabled

func (s StreamingConfig) GloballyEnabled() bool

The master switch, a transport of off also disabling

func (StreamingConfig) ToDict

func (s StreamingConfig) ToDict() map[string]any

Mapping of every field

type StreamingTTSConsumer

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

Consumes LLM text deltas and writes streaming PCM audio to an adapter as the reply generates

func NewStreamingTTSConsumer

func NewStreamingTTSConsumer(ctx context.Context, env *tools.Env, adapter PlatformAdapter, chatID string, metadata map[string]any, audioFormat *AudioFormat) *StreamingTTSConsumer

Consumer resolving the configured chunked streamer, inactive when the provider has no streaming API

func (*StreamingTTSConsumer) Abort

func (c *StreamingTTSConsumer) Abort(reason string)

Cancels the stream once from any goroutine and aborts an open adapter handle in the background

func (*StreamingTTSConsumer) Active

func (c *StreamingTTSConsumer) Active() bool

Whether a usable streaming provider was resolved

func (*StreamingTTSConsumer) Audible

func (c *StreamingTTSConsumer) Audible() bool

Whether PCM reached the adapter handle

func (*StreamingTTSConsumer) AudioFormat

func (c *StreamingTTSConsumer) AudioFormat() AudioFormat

Audio format the handle opens with, refreshed from the streamer at the first chunk

func (*StreamingTTSConsumer) Completed

func (c *StreamingTTSConsumer) Completed() bool

Whether the streaming audio was fully delivered

func (*StreamingTTSConsumer) Done

func (c *StreamingTTSConsumer) Done() bool

Whether the drain task was started and has ended

func (*StreamingTTSConsumer) Dropped

func (c *StreamingTTSConsumer) Dropped() bool

Whether queue saturation dropped at least one clause

func (*StreamingTTSConsumer) Finish

func (c *StreamingTTSConsumer) Finish()

Flushes the chunker tail and enqueues the end of text sentinel after every flushed clause

func (*StreamingTTSConsumer) OnDelta

func (c *StreamingTTSConsumer) OnDelta(text *string)

Feeds text to the chunker or flushes a segment boundary for nil, never blocking

func (*StreamingTTSConsumer) Partial

func (c *StreamingTTSConsumer) Partial() bool

Whether some audio was audible before a failure or a dropped clause

func (*StreamingTTSConsumer) Start

func (c *StreamingTTSConsumer) Start() *STTSDrainTask

Starts the drain task once and returns it

func (*StreamingTTSConsumer) SuppressWholeFile

func (c *StreamingTTSConsumer) SuppressWholeFile() bool

Whether the gateway skips the whole file TTS reply

func (*StreamingTTSConsumer) WaitComplete

func (c *StreamingTTSConsumer) WaitComplete(timeout float64) bool

Waits up to timeout seconds for the drain task without cancelling it, true only on full success

type StreamingTTSHandle

type StreamingTTSHandle struct {
	ChatID      string
	AudioFormat AudioFormat
	Audible     bool
	Aborted     bool
}

Handle of one streaming TTS session with the audible and aborted bookkeeping

type Submission

type Submission struct {
	RequestID string
	Ref       SessionRef
	Payload   map[string]any
	Intent    string
}

Prompt submission with its queue, steer or redirect intent

type SubmitOptions

type SubmitOptions struct {
	AuthorizeWrite       func(ctx context.Context, conn state.SQLiteConn) error
	QueueWhileRestarting bool
	ReplayGuard          func(ctx context.Context, conn state.SQLiteConn) error
	KanbanCard           any
}

Trusted caller options of a submission, never client payload fields

type SubscriptionSnapshot

type SubscriptionSnapshot struct {
	SubscriptionID   string
	Handle           SessionHandle
	ReplayEpoch      string
	LastSequence     int64
	History          []map[string]any
	Pending          []PendingAdmission
	Prompts          []map[string]any
	TranscriptTarget *string
}

Attach snapshot with history, pending admissions, open prompts and the resolved transcript target

type SystemExitError

type SystemExitError struct{ Code int }

Process exit the CLI performs after printing its guidance

func (*SystemExitError) Error

func (e *SystemExitError) Error() string

type SystemScopeRequiresRootError

type SystemScopeRequiresRootError struct{ Msg, Action string }

Raised when a system scope gateway operation runs without root

func (*SystemScopeRequiresRootError) Error

type SystemctlUnavailableError

type SystemctlUnavailableError struct{}

Raised when systemctl is not installed

func (SystemctlUnavailableError) Error

type SystemdWatchdog

type SystemdWatchdog struct {
	IntervalSeconds *float64
	// contains filtered or unexported fields
}

Feeds systemd while the event loop keeps making progress

func NewSystemdWatchdog

func NewSystemdWatchdog(configEnabled bool, lagToleranceSeconds any) *SystemdWatchdog

Watchdog reading WATCHDOG_USEC now, lag tolerance nil for a quarter of the interval

func (*SystemdWatchdog) Enabled

func (w *SystemdWatchdog) Enabled() bool

True when config allows it and systemd requested a watchdog interval

func (*SystemdWatchdog) HasTask

func (w *SystemdWatchdog) HasTask() bool

Whether a feed loop was started and not yet stopped

func (*SystemdWatchdog) Ready

func (w *SystemdWatchdog) Ready(status string) bool

Tells systemd the gateway is ready with a one line status

func (*SystemdWatchdog) RecordTick

func (w *SystemdWatchdog) RecordTick(scheduledAt, now float64) bool

Feeds systemd when the tick woke inside its lag budget, else marks the loop unhealthy once

func (*SystemdWatchdog) Start

func (w *SystemdWatchdog) Start(ctx context.Context) bool

Starts the feed loop on a running event loop, true when one runs afterwards

func (*SystemdWatchdog) Stop

func (w *SystemdWatchdog) Stop(ctx context.Context)

Stops feeding systemd and sends STOPPING=1 at most once

func (*SystemdWatchdog) Unhealthy

func (w *SystemdWatchdog) Unhealthy() bool

True once a late tick marked the loop unhealthy

type TTSStream

type TTSStream interface {
	Active() bool
	Start() *STTSDrainTask
	OnDelta(text *string)
	Finish()
	Abort(reason string)
	Done() bool
	SuppressWholeFile() bool
	WaitComplete(timeout float64) bool
}

Streaming TTS of one voice turn as the turn runner drives it

type TargetRefParse

type TargetRefParse struct {
	ChatID   *string
	ThreadID *string
}

Chat id and optional thread id a target syntax parser recognised, nil chat id when the group did not match

type TaskAttempt

type TaskAttempt struct {
	Identity            TaskIdentity
	Lease               DriverLease
	ExecutionGeneration int64
	CancelGeneration    int64
}

Exact running generation authorized to settle one task

func DriverStartTask

func DriverStartTask(ctx context.Context, dbPath string, identity TaskIdentity, lease DriverLease, expectedCancelGeneration int64, clock DriverClock) (TaskAttempt, error)

Moves one queued task to running under the current driver lease

type TaskConflictError

type TaskConflictError struct{ *DriverStateError }

Idempotency key reused for different task state

func (*TaskConflictError) Unwrap

func (e *TaskConflictError) Unwrap() error

type TaskIdentity

type TaskIdentity struct {
	RoomID   string `json:"room_id"`
	TaskID   string `json:"task_id"`
	ThreadID string `json:"thread_id"`
	TurnID   string `json:"turn_id"`
}

Stable identity of one admitted room turn

func NewTaskIdentity

func NewTaskIdentity(roomID, taskID, threadID, turnID any) (TaskIdentity, error)

Validated task identity

func (TaskIdentity) AsDict

func (t TaskIdentity) AsDict() map[string]any

Field mapping of the identity, the dataclass asdict shape

type TextDebounceState

type TextDebounceState struct {
	Event   *MessageEvent
	Task    *adapterTask
	FirstTS float64
	LastTS  float64
}

Buffered queue mode busy text burst of one session with its flush timer

func (*TextDebounceState) CancelTimer

func (s *TextDebounceState) CancelTimer(unless *adapterTask)

Cancels the pending flush timer when it is live and is not the given task

type ThreadParticipationTracker

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

Persisted set of threads the bot took part in, one json file per platform

func NewThreadParticipationTracker

func NewThreadParticipationTracker(ctx context.Context, platform string, maxTracked int) *ThreadParticipationTracker

Tracker seeded in file order from the platform state file, keeping at most maxTracked ids on persist

func (*ThreadParticipationTracker) Clear

func (t *ThreadParticipationTracker) Clear()

Forgets every thread in memory

func (*ThreadParticipationTracker) Contains

func (t *ThreadParticipationTracker) Contains(threadID string) bool

Whether the bot took part in the thread

func (*ThreadParticipationTracker) Mark

func (t *ThreadParticipationTracker) Mark(ctx context.Context, threadID string) error

Marks the thread as participated and persists inline

func (*ThreadParticipationTracker) MarkAsync

func (t *ThreadParticipationTracker) MarkAsync(ctx context.Context, threadID string) error

Marks the thread in memory at once and persists on a worker

type ThreadRenameOptions

type ThreadRenameOptions = plugins.ThreadRenameOptions

Keyword options of an adapter thread rename, one type for the runner lanes and the platform actions

type TicketStore

type TicketStore struct {
	InstanceID string
	// contains filtered or unexported fields
}

Private local bootstrap grants minted on the control listener and redeemed once by a local client

func NewTicketStore

func NewTicketStore(instanceID string, profileIDs map[string]bool) (*TicketStore, error)

Store for one runtime instance serving profileIDs, a ValueError without either

func (*TicketStore) Mint

func (s *TicketStore) Mint(profileID, subject, purpose, scope string, refuseRestartWait bool) (string, error)

Mints a single use ticket binding a profile, subject and purpose, a PermissionError for a rejected binding

func (*TicketStore) Outstanding

func (s *TicketStore) Outstanding() bool

Whether an unexpired ticket was minted and not yet redeemed

func (*TicketStore) ProfileIDs

func (s *TicketStore) ProfileIDs() map[string]bool

Served profile ids a ticket may bind

func (*TicketStore) Redeem

func (s *TicketStore) Redeem(ticket any, profileID *string, purpose string) (map[string]any, error)

Redeems a ticket once for its purpose, any served profile when profileID is nil, a PermissionError otherwise

func (*TicketStore) Revoke

func (s *TicketStore) Revoke()

Drops every outstanding ticket

func (*TicketStore) SetProfileIDs

func (s *TicketStore) SetProfileIDs(ids map[string]bool)

Replaces the served profile ids after the served set changed

type ToolCallChunk

type ToolCallChunk struct {
	ToolName string
	Preview  *string
	// Values as Python holds them, int64 for an int and float64 for a float
	Args    map[string]any
	ArgKeys []string
	Index   int
}

ToolCallChunk announces a tool call with its preview, arguments and per turn index

func (ToolCallChunk) OrderedArgKeys

func (c ToolCallChunk) OrderedArgKeys() []string

Argument keys in insertion order, the recorded order first then any key it misses in sorted order

type ToolCallFinished

type ToolCallFinished struct {
	ToolName string
	Duration float64
	OK       bool
	Index    int
}

ToolCallFinished closes a tool call with its wall clock duration and whether it returned

type TopicRecoveryFn

type TopicRecoveryFn func(source *SessionSource) (*string, error)

TopicRecoveryFn returns a replacement thread id for a source, nil keeping the current one

type TranscriptAppender

type TranscriptAppender interface {
	AppendMessage(ctx context.Context, sessionID string, fields map[string]any, guards state.AppendGuards) (int64, error)
}

Store surface a recovered row is appended through

type TranscriptLoader

type TranscriptLoader interface {
	LoadTranscript(ctx context.Context, sessionID string) ([]any, error)
}

Session store surface the history media lookup reads transcripts through

type TranscriptReadError

type TranscriptReadError struct {
	SessionID string
	Cause     error
}

Persisted history that cannot be read safely for the session

func (*TranscriptReadError) Error

func (e *TranscriptReadError) Error() string

func (*TranscriptReadError) Unwrap

func (e *TranscriptReadError) Unwrap() error

Read failure the error was raised from

type TransferredAttachment

type TransferredAttachment struct {
	Item map[string]any
	Data []byte
}

One validated bound manifest item and the bytes the authority transferred for it

type TransportOwnerRunner

type TransportOwnerRunner interface {
	TransportOwner(source *SessionSource) (adapter PlatformAdapter, profile string, ok bool)
}

TransportOwnerRunner is the runner seam that maps a source back to the adapter and profile that made it

type TurnSettlement

type TurnSettlement struct {
	Settled  *jsonutil.Object
	Response any
}

Outcome of one settlement attempt, the committed row and the reply it carries once it landed

type TurnWorkerHandle

type TurnWorkerHandle interface {
	WorkerDone() bool
}

Physical turn worker a stop must see exit, done once its executor thread returned

type UpdateOutputState

type UpdateOutputState struct {
	PrevStdout, PrevStderr io.Writer
	Stdout, Stderr         io.Writer
	LogFile                *os.File
	Installed              bool
}

Streams and log handle of one protected update run, the wrapped pair current while installed

func InstallHangupProtection

func InstallHangupProtection(stdout, stderr io.Writer, gatewayMode bool) *UpdateOutputState

Ignores SIGHUP outside gateway mode and wraps both streams with a mirror to the root home update log

type UpdateOutputStream

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

Writer of icebath update that mirrors to the update log and drops screen output once the terminal is gone

func NewUpdateOutputStream

func NewUpdateOutputStream(original, log io.Writer) *UpdateOutputStream

func (*UpdateOutputStream) Fd

func (s *UpdateOutputStream) Fd() uintptr

Descriptor of the original stream, the invalid descriptor when the original has none

func (*UpdateOutputStream) Flush

func (s *UpdateOutputStream) Flush() error

Flushes the log and the original, a failing original marked broken and never reported

func (*UpdateOutputStream) IsATTY

func (s *UpdateOutputStream) IsATTY() bool

True when the original is still usable and reports itself a terminal

func (*UpdateOutputStream) OriginalBroken

func (s *UpdateOutputStream) OriginalBroken() bool

True once a write or flush to the original failed

func (*UpdateOutputStream) Unwrap

func (s *UpdateOutputStream) Unwrap() io.Writer

Original stream every capability the mirror does not define itself resolves on

func (*UpdateOutputStream) Write

func (s *UpdateOutputStream) Write(data []byte) (int, error)

Mirrors to the log first, then the original until it fails once, always reporting the full length written

type UpdatePromptSender

type UpdatePromptSender interface {
	SendUpdatePrompt(ctx context.Context, chatID, prompt, def, sessionKey string, metadata map[string]any) (SendResult, error)
}

Adapter that renders the gateway update prompt as native buttons

type UserSystemdUnavailableError

type UserSystemdUnavailableError struct{ Msg string }

Raised when systemctl --user cannot reach the user D-Bus session, the message is the remediation

func (*UserSystemdUnavailableError) Error

type WakeNotAccepted

type WakeNotAccepted struct {
	Msg       string
	Reason    *string
	Permanent bool
	// contains filtered or unexported fields
}

No adapter admission, the store refusal code in Reason and Permanent once the refusal is proven final

func (*WakeNotAccepted) Error

func (e *WakeNotAccepted) Error() string

func (*WakeNotAccepted) Unwrap

func (e *WakeNotAccepted) Unwrap() error

type WakeOptions

type WakeOptions struct {
	Text                 string
	SessionID            string
	Source               *SessionSource
	NotificationCategory string
	Profile              string
}

Wake turn delivery options of DeliverWake

type WebHTTPError

type WebHTTPError struct {
	Status  int
	Text    string
	Headers map[string]string
}

WebHTTPError is a raised aiohttp HTTPException answered with its status, text and headers

func DefaultWebHTTPError

func DefaultWebHTTPError(status int, headers map[string]string) *WebHTTPError

Raised HTTP exception with the aiohttp default text of status and reason

func NewWebHTTPError

func NewWebHTTPError(status int, text string, headers map[string]string) *WebHTTPError

Raised HTTP exception with explicit text

func (*WebHTTPError) Error

func (e *WebHTTPError) Error() string

func (*WebHTTPError) Response

func (e *WebHTTPError) Response() *WebResponse

Response the exception answers

type WebHandler

type WebHandler func(ctx context.Context, request *WebRequest) (*WebResponse, error)

WebHandler answers one request like an aiohttp handler coroutine, an error raising out of it

type WebMiddleware

type WebMiddleware func(ctx context.Context, request *WebRequest, handler WebHandler) (*WebResponse, error)

WebMiddleware wraps the resolved handler of every request, the aiohttp new style middleware

type WebRequest

type WebRequest struct {
	Method        string
	RelURL        *url.URL
	Header        http.Header
	Remote        string
	ContentLength *int64
	ProtoMajor    int
	ProtoMinor    int
	MatchInfo     map[string]string
	ClientMaxSize int64
	// contains filtered or unexported fields
}

WebRequest is an aiohttp web.Request, its body read once under the application's client body cap

func NewWebRequest

func NewWebRequest(r *http.Request, clientMaxSize int64) *WebRequest

Request view of a net/http request with the remote peer address and the given body cap

func (*WebRequest) Clone

func (r *WebRequest) Clone(relURL *url.URL, clientMaxSize int64) *WebRequest

Copy of the request at another relative URL with its own body cap, sharing the body stream

func (*WebRequest) PathSafe

func (r *WebRequest) PathSafe() string

Request path with every escape decoded except slash and percent, the yarl path_safe form

func (*WebRequest) Query

func (r *WebRequest) Query() url.Values

Parsed query string keeping blank values

func (*WebRequest) QueryGet

func (r *WebRequest) QueryGet(key string) string

First query value of the key, empty when absent

func (*WebRequest) Read

func (r *WebRequest) Read() ([]byte, error)

Whole body, the 413 HTTP exception once the body reaches the client body cap

func (*WebRequest) ReadExactly

func (r *WebRequest) ReadExactly(ctx context.Context, n int) ([]byte, error)

Exactly n bytes of the raw body stream, or the shorter partial read when the stream ends first

type WebResponse

type WebResponse struct {
	Status  int
	Headers http.Header
	Body    []byte
	// contains filtered or unexported fields
}

WebResponse is an aiohttp web.Response with its status, headers and body bytes

func APIConfigUnavailableMiddleware

func APIConfigUnavailableMiddleware(ctx context.Context, request *WebRequest, handler WebHandler) (*WebResponse, error)

Answers a config backend outage with that request's 503 instead of ending the gateway

func APIProfileRejectionResponse

func APIProfileRejectionResponse(request *WebRequest) (*WebResponse, error)

The 404 for a rejected prefix, a default handle profile served elsewhere answering with its own body

func DispatchProfileIngress

func DispatchProfileIngress(ctx context.Context, runner any, profile, tail string, request *WebRequest, scoped bool) (*WebResponse, error)

Forwards /p/profile/tail to the profile adapter app routing /tail under that profile's runtime scope

func HandleMCPEventControl

func HandleMCPEventControl(ctx context.Context, adapter *WebhookAdapter, routeName string, routeConfig *jsonutil.Object, payload any, profile *string) (*WebResponse, error)

Response of a control envelope on an MCP event route, nil letting the delivery continue as an occurrence

func NewWebResponse

func NewWebResponse(status int, headers map[string]string) *WebResponse

Response with an empty body and the given headers

func ParkedProfileRefusalResponse

func ParkedProfileRefusalResponse(ctx context.Context, runner any, profile string, routeConfig map[string]any,
	admissionSource func() (*SessionSource, error)) (*WebResponse, error)

The 503 for a webhook whose profile is not served right now, nil when the delivery may proceed

func WebFileResponse

func WebFileResponse(request *WebRequest, path string, headers map[string]string) (*WebResponse, error)

File body with ETag, Last-Modified, conditional and range answers like aiohttp FileResponse

func WebJSONResponse

func WebJSONResponse(data any, status int, headers map[string]string) (*WebResponse, error)

JSON response of json.dumps with its default separators under application/json

func WebResponseFor

func WebResponseFor(request *WebRequest, resp *WebResponse, err error) *WebResponse

A raised HTTP exception as its own response, any other error as a logged 500, else the handler response

func WebTextResponse

func WebTextResponse(status int, text, contentType string, headers map[string]string) *WebResponse

Text response with the aiohttp utf-8 charset, text/plain unless a content type is given

func (*WebResponse) ContentType

func (r *WebResponse) ContentType() string

Mime type of the Content-Type header, application/octet-stream when none is set

func (*WebResponse) Text

func (r *WebResponse) Text() string

Body decoded as text

type WebSocketRelayTransport

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

WebSocketRelayTransport is the relay transport over a websocket the gateway dials to the connector

func NewWebSocketRelayTransport

func NewWebSocketRelayTransport(url, platform, botID string, o RelayTransportOptions) *WebSocketRelayTransport

Transport dialing the normalized connector URL for the primary platform and every fronted identity

func (*WebSocketRelayTransport) AuthRevoked

func (t *WebSocketRelayTransport) AuthRevoked() bool

True once the connector closed 4401 against a fresh token after a successful handshake

func (*WebSocketRelayTransport) BotIDFor

func (t *WebSocketRelayTransport) BotIDFor(platform string) any

Bot id hello'd for the platform, nil when this transport does not front it

func (*WebSocketRelayTransport) Connect

func (t *WebSocketRelayTransport) Connect(ctx context.Context) (bool, error)

Opens the socket, starts the reader and sends the hellos

func (*WebSocketRelayTransport) DescriptorForPlatform

func (t *WebSocketRelayTransport) DescriptorForPlatform(platform string) any

Negotiated descriptor of one fronted platform, nil when none was received

func (*WebSocketRelayTransport) Disconnect

func (t *WebSocketRelayTransport) Disconnect(ctx context.Context, budgetS *float64) error

Tears the socket down after draining in flight outbound frames within the remaining budget

func (*WebSocketRelayTransport) GetChatInfo

func (t *WebSocketRelayTransport) GetChatInfo(ctx context.Context, chatID string) (map[string]any, error)

Chat name and type the connector reports, the chat id and dm standing in when absent

func (*WebSocketRelayTransport) GoDormant

func (t *WebSocketRelayTransport) GoDormant(ctx context.Context, timeoutS float64) bool

Goes idle then closes the socket without closing the transport so the supervisor redials on wake

func (*WebSocketRelayTransport) GoIdle

func (t *WebSocketRelayTransport) GoIdle(ctx context.Context, timeoutS float64) bool

Asks the connector to buffer this instance, true only on its acknowledgement within the timeout

func (*WebSocketRelayTransport) Handshake

Descriptor the connector advertised, waiting up to the connect timeout for the first one

func (*WebSocketRelayTransport) HoldRedial

func (t *WebSocketRelayTransport) HoldRedial()

Parks the reconnect supervisor until release or the hold cap

func (*WebSocketRelayTransport) RelayAuthRevoked

func (t *WebSocketRelayTransport) RelayAuthRevoked() bool

True once revocation latched

func (*WebSocketRelayTransport) RelayClosing

func (t *WebSocketRelayTransport) RelayClosing() bool

True once disconnect began

func (*WebSocketRelayTransport) RelayConnected

func (t *WebSocketRelayTransport) RelayConnected() bool

True while a socket is held

func (*WebSocketRelayTransport) RelayGatewayID

func (t *WebSocketRelayTransport) RelayGatewayID() string

Enrolled gateway id presented on the upgrade

func (*WebSocketRelayTransport) RelayIdentities

func (t *WebSocketRelayTransport) RelayIdentities() any

Fronted platform and bot id pairs as JSON ready lists

func (*WebSocketRelayTransport) RelayURL

func (t *WebSocketRelayTransport) RelayURL() string

Connector URL the transport dials

func (*WebSocketRelayTransport) RelayUpgradeSecret

func (t *WebSocketRelayTransport) RelayUpgradeSecret() string

Per gateway upgrade secret

func (*WebSocketRelayTransport) ReleaseRedial

func (t *WebSocketRelayTransport) ReleaseRedial()

Lets the supervisor redial again

func (*WebSocketRelayTransport) SendFollowUp

func (t *WebSocketRelayTransport) SendFollowUp(ctx context.Context, action map[string]any, platform string) (map[string]any, error)

Issues a semantic follow up action against a session bound shared identity capability

func (*WebSocketRelayTransport) SendInterrupt

func (t *WebSocketRelayTransport) SendInterrupt(ctx context.Context, sessionKey string, reason *string) error

Routes a mid turn stop for the session to the connector

func (*WebSocketRelayTransport) SendOutbound

func (t *WebSocketRelayTransport) SendOutbound(ctx context.Context, action map[string]any, platform string) (map[string]any, error)

Carries an outbound action to the connector and returns its result

func (*WebSocketRelayTransport) SetInboundHandler

func (t *WebSocketRelayTransport) SetInboundHandler(handler RelayInboundHandler)

func (*WebSocketRelayTransport) SetInterruptInboundHandler

func (t *WebSocketRelayTransport) SetInterruptInboundHandler(handler RelayInterruptHandler)

func (*WebSocketRelayTransport) SetPassthroughHandler

func (t *WebSocketRelayTransport) SetPassthroughHandler(handler RelayPassthroughHandler)

type WebStreamResponse

type WebStreamResponse struct {
	*WebResponse
	// contains filtered or unexported fields
}

WebStreamResponse is an aiohttp StreamResponse, its status and headers sent at prepare and its body written in parts

func NewWebStreamResponse

func NewWebStreamResponse(status int, headers map[string]string) *WebStreamResponse

Stream response with the status and headers, sent to the client once prepared

func (*WebStreamResponse) Prepare

func (s *WebStreamResponse) Prepare(request *WebRequest) error

Sends the status and headers to the request's client, later header changes having no effect

func (*WebStreamResponse) Write

func (s *WebStreamResponse) Write(data []byte) error

Writes one body part and flushes it, kept in Body when no client is attached, a closed client as ConnectionResetError

func (*WebStreamResponse) WriteEOF

func (s *WebStreamResponse) WriteEOF() error

Ends the body, nothing further may be written

type WebhookAdapter

type WebhookAdapter struct {
	*BasePlatformAdapter
	// contains filtered or unexported fields
}

WebhookAdapter receives signed webhook POSTs, renders them into prompts and routes the responses back

func NewWebhookAdapter

func NewWebhookAdapter(config *PlatformConfig) (*WebhookAdapter, error)

Adapter for a webhook platform config, the error of a malformed port, limit or route table

func (*WebhookAdapter) AdapterAttr

func (a *WebhookAdapter) AdapterAttr(name string) any

Python attribute of the adapter by name, the signing credentials as its token

func (*WebhookAdapter) Coalescer

func (a *WebhookAdapter) Coalescer() *WebhookCoalescer

Route coalescer of the adapter

func (*WebhookAdapter) Connect

func (a *WebhookAdapter) Connect(ctx context.Context, isReconnect bool) (bool, error)

Starts the webhook listener after validating every route, false when the port cannot be bound

func (*WebhookAdapter) DeliveryInfo

func (a *WebhookAdapter) DeliveryInfo(chatID string) any

Delivery info recorded for a session chat id, nil when absent

func (*WebhookAdapter) Disconnect

func (a *WebhookAdapter) Disconnect(ctx context.Context) error

Flushes buffered coalesced events, stops the listener and marks the adapter disconnected

func (*WebhookAdapter) GetChatInfo

func (a *WebhookAdapter) GetChatInfo(ctx context.Context, chatID string) (map[string]any, error)

Chat info of a webhook delivery chat

func (*WebhookAdapter) ListenHost

func (a *WebhookAdapter) ListenHost() *string

Bound host, nil for the dual stack default

func (*WebhookAdapter) ListenPort

func (a *WebhookAdapter) ListenPort() int

Configured listen port

func (*WebhookAdapter) MaxBodyBytes

func (a *WebhookAdapter) MaxBodyBytes() int64

Body cap the listener and handlers enforce

func (*WebhookAdapter) ReloadDynamicRoutes

func (a *WebhookAdapter) ReloadDynamicRoutes(ctx context.Context)

Reloads agent created subscriptions when the stat identity of the subscriptions file changes

func (*WebhookAdapter) RenderPrompt

func (a *WebhookAdapter) RenderPrompt(template any, payload any, eventType any, routeName string) (string, error)

Renders a prompt template with dotted payload fields, a null field as null and a missing one left as written, the raw payload JSON for an empty template

func (*WebhookAdapter) RouteNames

func (a *WebhookAdapter) RouteNames() []string

Names of the live routes in table order

func (*WebhookAdapter) Runner

func (a *WebhookAdapter) Runner() *HTTPAppRunner

Running listener, nil before connect

func (*WebhookAdapter) Send

func (a *WebhookAdapter) Send(ctx context.Context, chatID, content, replyTo string, metadata map[string]any) (SendResult, error)

Delivers the agent response to the destination retained for its opaque chat id

func (*WebhookAdapter) Token

func (a *WebhookAdapter) Token() (string, error)

Signing credentials of the static routes as canonical JSON, the native replay binding of the connector

func (*WebhookAdapter) ToolsetsForSource

func (a *WebhookAdapter) ToolsetsForSource(source *SessionSource) ([]string, bool)

Per route toolsets override keyed on the authenticated webhook user id, false when the route sets none

func (*WebhookAdapter) ValidateSignature

func (a *WebhookAdapter) ValidateSignature(request *WebRequest, body []byte, secret string) bool

Validates a GitHub, GitLab, Svix, Standard Webhooks, Linear or generic HMAC signature of the body

func (*WebhookAdapter) WebhookDeliveryConfig

func (a *WebhookAdapter) WebhookDeliveryConfig(ctx context.Context, profile *string) (*GatewayConfig, error)

Gateway config of the profile a delivery is bound to, the runner's own for a bare route

func (*WebhookAdapter) WebhookProfileScope

func (a *WebhookAdapter) WebhookProfileScope(ctx context.Context, profile *string) (context.Context, error)

Runtime scope of a resolved profile prefix, the context unchanged for a bare route

func (*WebhookAdapter) WebhookRoute

func (a *WebhookAdapter) WebhookRoute(name string) (any, bool)

Route of a name in the live table

type WebhookCoalesceDispatch

type WebhookCoalesceDispatch func(payload any, prompt, deliveryID string, now float64, args WebhookDispatchArgs, superseded []string) *adapterTask

Spawner of the merged run of a settled group, its task awaited by a flush

type WebhookCoalesceRender

type WebhookCoalesceRender func(template string, payload any, eventType any, routeName string) (string, error)

Renderer of a coalesce key template against the payload, event type and route

type WebhookCoalescer

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

WebhookCoalescer debounces events of one entity and dispatches only the newest once quiet

func NewWebhookCoalescer

func NewWebhookCoalescer(dispatch WebhookCoalesceDispatch, render WebhookCoalesceRender) *WebhookCoalescer

Coalescer dispatching through the adapter spawner and rendering keys with its prompt renderer

func (*WebhookCoalescer) Enqueue

func (c *WebhookCoalescer) Enqueue(routeName string, coalesce *jsonutil.Object, payload, eventType any, prompt, deliveryID string,
	now float64, args WebhookDispatchArgs) (bool, error)

Buffers one event, false when the key did not resolve and the caller dispatches at once

func (*WebhookCoalescer) Flush

func (c *WebhookCoalescer) Flush()

Dispatches every pending group now and waits until each run is handed to the runner

func (*WebhookCoalescer) GroupKey

func (c *WebhookCoalescer) GroupKey(routeName, keyTemplate string, payload, eventType any) (string, bool, error)

Route qualified group key of a dotted field or brace template, false when a field did not resolve

func (*WebhookCoalescer) Pending

func (c *WebhookCoalescer) Pending() map[string]*WebhookPendingEvent

Pending groups by key in arrival order

type WebhookDispatchArgs

type WebhookDispatchArgs struct {
	RouteConfig *jsonutil.Object
	RouteName   string
	Profile     *string
	EventType   any
}

Arguments the adapter spawner receives with a settled event besides payload, prompt and delivery id

type WebhookPendingEvent

type WebhookPendingEvent struct {
	Payload      any
	Prompt       string
	DeliveryID   string
	FirstAt      float64
	Count        int
	DispatchArgs WebhookDispatchArgs
	Superseded   []string
}

WebhookPendingEvent is the newest event of a coalesce group with the group bookkeeping

func (*WebhookPendingEvent) PromptWithNote

func (e *WebhookPendingEvent) PromptWithNote() string

Prompt with the coalescing note appended when the group held more than one event

type WebhookRouteProcessor

type WebhookRouteProcessor struct {
	ScriptTimeoutSeconds int
}

WebhookRouteProcessor evaluates declarative route filters and optional script transforms

func NewWebhookRouteProcessor

func NewWebhookRouteProcessor(scriptTimeoutSeconds int) *WebhookRouteProcessor

Processor with a script timeout of at least one second

func (*WebhookRouteProcessor) FilterMatches

func (p *WebhookRouteProcessor) FilterMatches(ctx context.Context, spec, payload, eventType any, headers *jsonutil.Object) (bool, error)

Evaluates one filter spec, the all any and not combinators first and then the field operators

func (*WebhookRouteProcessor) ResolveFilterField

func (p *WebhookRouteProcessor) ResolveFilterField(field, payload, eventType any, headers *jsonutil.Object) (any, error)

Dotted field resolved against the payload, event and headers context, missing when absent

func (*WebhookRouteProcessor) RouteFiltersMatch

func (p *WebhookRouteProcessor) RouteFiltersMatch(ctx context.Context, routeConfig *jsonutil.Object, payload, eventType any, headers *jsonutil.Object) (bool, error)

Whether the route filters admit the event, a list requiring every spec and an object a single spec

func (*WebhookRouteProcessor) RunRouteScript

func (p *WebhookRouteProcessor) RunRouteScript(ctx context.Context, scriptValue any, payload any) (bool, *jsonutil.Object, error)

Runs a route script on the payload, false drops the webhook and a JSON object replaces the payload

type WindowsInstallOptions

type WindowsInstallOptions struct {
	Force           bool
	StartNow        *bool
	StartOnLogin    *bool
	ElevatedHandoff bool
}

Options of a Windows gateway install, nil choices asked before any elevation

type WorkRecordCapacityError

type WorkRecordCapacityError struct{ *WorkRecordError }

A full bounded evidence store

func (*WorkRecordCapacityError) Unwrap

func (e *WorkRecordCapacityError) Unwrap() error

type WorkRecordError

type WorkRecordError struct{ Msg string }

Controlled invalid or unavailable work evidence, a ValueError

func (*WorkRecordError) Error

func (e *WorkRecordError) Error() string

type WorkRecordPrefixError

type WorkRecordPrefixError struct{ *WorkRecordError }

A matching canonical history prefix that is not retained

func (*WorkRecordPrefixError) Unwrap

func (e *WorkRecordPrefixError) Unwrap() error

type WriteStep

type WriteStep = writeStep

One SQLite write a step sequence yields, for sequences built outside the package

type WriteSteps

type WriteSteps = writeSteps

Sequence of write steps returning its final value, for sequences built outside the package

func AdmitAPISteps

func AdmitAPISteps(ctx context.Context, adapter APITurnAdapter, turn *APITurn) WriteSteps

Admission of one API turn as write steps, its media captured and released around the admission write

func BindAPISteps

func BindAPISteps(ctx context.Context, a *SessionAuthority, sessionID string, hostedDispatch map[string]any, callerKey, walkedFrom string) WriteSteps

Binding of an API session as write steps, for a door outside the package

Source Files

Directories

Path Synopsis
platforms
a2a
feishu/feishuclient
Package feishuclient carries the lark client of a feishu comment agent turn to the feishu doc and drive tools
Package feishuclient carries the lark client of a feishu comment agent turn to the feishu doc and drive tools
irc
sms

Jump to

Keyboard shortcuts

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