Documentation
¶
Index ¶
- Constants
- Variables
- func CapMode(policyMode, sessionMode config.SessionMode) config.SessionMode
- func CheckDeviceShellArgs(commandPath string, args []string) error
- func CheckFlags(args []string) error
- func CheckMode(effective, required config.SessionMode) error
- func DesktopNotification(title string, message string)
- func HasDryRun(args []string) bool
- func IsDeviceShellCommand(commandPath string) bool
- func IsHelp(args []string) bool
- func MatchCommand(pattern, commandPath string) bool
- func ModeInfo(mode config.SessionMode) string
- func ParseMode(name string) (config.SessionMode, error)
- func ParseModeOrReset(name string) (config.SessionMode, error)
- func PrintsURLOnly(commandPath string, args []string) bool
- func RequiredMode(plan *Plan) config.SessionMode
- func RequiredModeFromPreview(plan *Plan, preview string) config.SessionMode
- func ResolveMode(ceiling, sessionMode, override config.SessionMode) config.SessionMode
- func ResolveSessionFile(sessionFile string, sessionHome string) string
- func SessionDefaultMode(sessionMode config.SessionMode) config.SessionMode
- func SessionKey(sessionFile string) string
- func SplitAtTerminator(args []string) (before []string, after []string, found bool)
- func SplitPipeline(commandLine string) ([][]string, error)
- func TokenExpiresAt(token string) *time.Time
- func WithRequest(ctx context.Context, r Request) context.Context
- type Approval
- type AuthProvider
- type Classifier
- type CommandInput
- type DeviceShellConfirmer
- type InteractiveLogin
- func (l *InteractiveLogin) AuthEnv(ctx context.Context) ([]string, error)
- func (l *InteractiveLogin) ExpiresAt() *time.Time
- func (l *InteractiveLogin) Login(ctx context.Context) error
- func (l *InteractiveLogin) LoginWith(ctx context.Context, secrets LoginSecrets) error
- func (l *InteractiveLogin) UsesToken() bool
- type LoginFunc
- type LoginSecrets
- type ModeChange
- type ModeController
- type ModeOption
- type Plan
- type Policy
- type Request
- type Requester
- type Result
- type Runner
- type Segment
- type Selection
- type Server
- func (s *Server) Active() (SessionInfo, *Runner)
- func (s *Server) EffectiveMode(key string, sessionMode string) config.SessionMode
- func (s *Server) Instructions() string
- func (s *Server) ModeOverride(key string) (config.SessionMode, bool)
- func (s *Server) New() *mcp.Server
- func (s *Server) SetMode(mode config.SessionMode, via string) (ModeChange, error)
- func (s *Server) SetSession(info SessionInfo, runner *Runner)
- func (s *Server) SetSessionKey(key string, info SessionInfo, runner *Runner)
- type SessionChoice
- type SessionInfo
- type SourceError
- type WebPicker
Constants ¶
const ( ModeSourceSession = "session" ModeSourceOverride = "override" )
Mode sources, used in the log and in the mode change result
const ( ToolRead = "c8y_read" ToolWrite = "c8y_write" ToolSession = "c8y_session" // PromptSwitchSession prompt to let the user switch the session (stdio mode) PromptSwitchSession = "switch_session" // PromptMode prompt to let the user change the mode of the current session PromptMode = "mode" )
const DefaultConfirmTimeout = 2 * time.Minute
DefaultConfirmTimeout how long the user has to confirm a device command
const DefaultPickerTimeout = 3 * time.Minute
DefaultPickerTimeout how long the user has to select a session in the browser
const EnvDeniedPaths = "C8Y_SETTINGS_FILES_DENIEDPATHS"
EnvDeniedPaths environment variable which sets the settings.files.deniedPaths setting of the commands, so they can't read files in the denied paths
const EnvForce = "C8Y_SETTINGS_DEFAULTS_FORCE"
EnvForce environment variable which sets the settings.defaults.force setting. It is only set for approved extension writes, so the c8y commands run by the extension don't ask for a confirmation
const SessionFilesSource = "Session files"
SessionFilesSource heading of the sessions from session files
Variables ¶
var BrowserCommands = []string{"applications open"}
BrowserCommands commands which open a page of the web UI in a browser. With --noBrowser they only print the page's address, without a request to Cumulocity
var DefaultDenyCommands = []string{
"mcp",
"sessions",
"settings",
"cli",
"alias",
"completion",
"extensions",
"microservices getBootstrapUser",
"deviceregistration getCredentials",
"remoteaccess connect run",
"remoteaccess server",
}
DefaultDenyCommands commands which are not available to the agent by default. They either expose secrets, change the local configuration, or open local network services.
var DefaultReadCommands = []string{
"version",
"template",
"util",
"* subscribe",
"* subscribeAll",
"operations wait",
"realtime subscribe",
"realtime subscribeAll",
}
DefaultReadCommands commands which never write to Cumulocity, in addition to any command whose name starts with a read verb (see readVerbPrefixes)
var DeniedFlags = []string{
"session",
"sessionUsername",
"sessionPassword",
"sessionMode",
"host",
"proxy",
"noProxy",
"insecure",
"outputFile",
"outputFileRaw",
"noLog",
"logMessage",
"force",
"confirm",
"confirmText",
"debug",
}
DeniedFlags global flags the agent is not allowed to set, as they would allow the agent to escape the policy (e.g. switching session or mode), write local files, or disable the audit trail
var DeniedShortFlags = []rune{'U', 'P', 'k', 'f', 'l'}
DeniedShortFlags shorthand versions of DeniedFlags
var DeviceShellCommands = []string{
"remoteaccess connect ssh",
}
DeviceShellCommands commands which run a shell command on a device through a Cumulocity remote access (ssh) tunnel. The agent can only use them non-interactively, with the command to run on the device after "--", e.g. "remoteaccess connect ssh --device 1234 -- systemctl status". They are always treated as write commands, as the shell command can change anything on the device, and their dry run mode would still run the command.
var ErrPickerCancelled = errors.New("the user cancelled the session selection")
ErrPickerCancelled the user cancelled the session selection
var ErrPickerTimeout = errors.New("the user did not select a session in time")
ErrPickerTimeout the user did not select a session in time
var ErrTOTPRequired = errors.New(config.TOTPCodeRequiredMessage)
ErrTOTPRequired the login needs a two-factor authentication code
Functions ¶
func CapMode ¶
func CapMode(policyMode, sessionMode config.SessionMode) config.SessionMode
CapMode returns the more restrictive of the policy mode and the session mode. An unset policy mode uses the session mode, and an unset session mode is prod (read only). The ci mode is treated like dev so the agent never gets more than dev.
func CheckDeviceShellArgs ¶
CheckDeviceShellArgs checks that a device shell command is only used non-interactively and doesn't open local listeners
func CheckFlags ¶
CheckFlags rejects any flags the agent is not allowed to use. Arguments after the argument terminator "--" are not c8y flags, so they are not checked.
func CheckMode ¶ added in v2.59.0
func CheckMode(effective, required config.SessionMode) error
CheckMode checks that the effective mode allows a plan which needs the required mode. It is shared by every entry point which runs commands.
func DesktopNotification ¶
DesktopNotification shows a desktop notification, if supported (best effort). The values are passed as arguments, so they are never interpreted as a script.
func IsDeviceShellCommand ¶
IsDeviceShellCommand returns true if the command runs a shell command on a device
func MatchCommand ¶
MatchCommand checks if a command path (e.g. "devices list") matches a pattern. Each word in the pattern is matched against the corresponding word of the command path and supports glob wildcards, e.g. "devices *", "* delete". A pattern also matches all sub commands, e.g. "devices" matches "devices list"
func ModeInfo ¶ added in v2.59.0
func ModeInfo(mode config.SessionMode) string
ModeInfo describes what the agent can do in a mode
func ParseMode ¶
func ParseMode(name string) (config.SessionMode, error)
ParseMode parses a mode name (prod, qual, dev). CI mode is not accepted
func ParseModeOrReset ¶ added in v2.59.0
func ParseModeOrReset(name string) (config.SessionMode, error)
ParseModeOrReset parses a mode name, or "reset" (returned as unset)
func PrintsURLOnly ¶ added in v2.58.0
PrintsURLOnly checks if a browser command was told to print the page's address instead of opening a browser
func RequiredMode ¶ added in v2.59.0
func RequiredMode(plan *Plan) config.SessionMode
RequiredMode returns the lowest mode which allows the plan, judged by the command verbs. Plans which only read data don't need a mode, commands which delete or remove data need dev, and any other plan needs to be able to create data (qual).
func RequiredModeFromPreview ¶ added in v2.59.0
func RequiredModeFromPreview(plan *Plan, preview string) config.SessionMode
RequiredModeFromPreview is like RequiredMode, but uses the HTTP methods of the dry run preview (POST/PUT: qual, DELETE: dev) when the preview shows any. Otherwise the command verb decides. Device shell commands need qual.
func ResolveMode ¶ added in v2.59.0
func ResolveMode(ceiling, sessionMode, override config.SessionMode) config.SessionMode
ResolveMode returns the mode the agent can use: min(ceiling, override if set, else the session mode). An unset ceiling is dev, an unset session mode is prod, and the ci mode counts as dev.
func ResolveSessionFile ¶
ResolveSessionFile returns the absolute path of the session file. A session can be given by name (e.g. --session my-tenant), in which case the matching file is looked up in the session home directory. The value is returned as is if no file is found.
func SessionDefaultMode ¶ added in v2.59.0
func SessionDefaultMode(sessionMode config.SessionMode) config.SessionMode
SessionDefaultMode returns the mode of the session itself, prod (read only) if it has none
func SessionKey ¶
SessionKey name used to identify a session, derived from the session file. Only known session file extensions are removed, as session names can contain dots, e.g. "example.cumulocity.com-firstname.lastname"
func SplitAtTerminator ¶
SplitAtTerminator splits the arguments at the argument terminator "--". The arguments after it are not interpreted as c8y flags.
func SplitPipeline ¶
SplitPipeline splits a command line into the individual c8y commands. The command is not passed to a shell, so only " | " (pipe surrounded by whitespace) between c8y commands is supported.
func TokenExpiresAt ¶
TokenExpiresAt returns the expiry time of a JWT token, or nil if it can't be determined
Types ¶
type Approval ¶
type Approval string
Approval controls how write commands are approved before they are executed
const ( // ApprovalAuto asks the user via MCP elicitation when the client supports it, // otherwise it relies on the MCP client's own tool permission prompt ApprovalAuto Approval = "auto" // ApprovalElicit always asks the user via MCP elicitation. If the client does // not support elicitation, then write commands are rejected ApprovalElicit Approval = "elicit" // ApprovalClient relies only on the MCP client's tool permission prompt // (the write tool is annotated as destructive) ApprovalClient Approval = "client" // ApprovalNone does not ask for any approval. Only use for trusted automation ApprovalNone Approval = "none" )
func ParseApproval ¶
type AuthProvider ¶
type AuthProvider interface {
// AuthEnv returns the environment variables containing the credentials
AuthEnv(ctx context.Context) ([]string, error)
}
AuthProvider provides the credentials for the commands run for the agent
type Classifier ¶
type Classifier struct {
Root *cobra.Command
Policy Policy
// contains filtered or unexported fields
}
Classifier resolves commands against the c8y command tree and applies the policy. It is safe for concurrent use
type CommandInput ¶
type CommandInput struct {
Command string `` /* 238-byte string literal not displayed */
Stdin string `json:"stdin,omitempty" jsonschema:"Optional data piped to the first command, e.g. newline separated ids or json lines"`
TimeoutSeconds int `json:"timeoutSeconds,omitempty" jsonschema:"Optional timeout in seconds"`
}
CommandInput input for the read/write tools
type DeviceShellConfirmer ¶
type DeviceShellConfirmer struct {
// Timeout how long the user has to answer. Defaults to DefaultConfirmTimeout
Timeout time.Duration
// contains filtered or unexported fields
}
DeviceShellConfirmer asks the user to confirm commands which run on a device, with a native dialog (macOS, or Linux with zenity or kdialog). The MCP client can't answer it. Commands are rejected if no dialog is available.
func (*DeviceShellConfirmer) Confirm ¶
func (c *DeviceShellConfirmer) Confirm(ctx context.Context, session SessionInfo, command string) error
Confirm returns nil if the user allows the command
type InteractiveLogin ¶
type InteractiveLogin struct {
// Executable path to the c8y binary
Executable string
// SessionFile session file to log in with. If empty (and no Provider is set), the
// session is read from environment variables
SessionFile string
// Provider extension session provider to log in with (<provider> or
// <extension>/<provider>), and SessionURI the session it returns. The provider is run
// without user interaction (its select command), also when the token is renewed
Provider string
SessionURI string
// SessionMode mode passed to the login command (to avoid the mode prompt)
SessionMode string
// Stderr receives the login's messages
Stderr io.Writer
// RenewBefore log in again when the token expires within this duration
RenewBefore time.Duration
// TempDir directory for the copy of the session file without secrets
TempDir string
// Renew optional function which logs in again when the token expires, instead of
// logging in without secrets. It is used to ask the user for the secrets in the
// browser. It must call login (which may be called several times, e.g. after a wrong
// passphrase) and return its last error. It is called while the login is locked
Renew func(ctx context.Context, login func(ctx context.Context, secrets LoginSecrets) error) error
// contains filtered or unexported fields
}
InteractiveLogin logs in using the existing "c8y sessions login" command, then provides the resulting token to the commands. The server has no terminal, so the login can't prompt: an encrypted session is unlocked with the pin entry command (settings.pinEntry) or the passphrase given in LoginSecrets, and a two-factor code is generated from the session's TOTP secret or given in LoginSecrets. The login is repeated when the token is about to expire (see Renew).
func (*InteractiveLogin) AuthEnv ¶
func (l *InteractiveLogin) AuthEnv(ctx context.Context) ([]string, error)
AuthEnv returns the credentials, logging in again if the token expires soon
func (*InteractiveLogin) ExpiresAt ¶
func (l *InteractiveLogin) ExpiresAt() *time.Time
ExpiresAt returns when the current token expires (if known)
func (*InteractiveLogin) Login ¶
func (l *InteractiveLogin) Login(ctx context.Context) error
Login runs the interactive login
func (*InteractiveLogin) LoginWith ¶
func (l *InteractiveLogin) LoginWith(ctx context.Context, secrets LoginSecrets) error
LoginWith runs the login with the secrets entered by the user (if any). It returns ErrTOTPRequired if a two-factor code is needed
func (*InteractiveLogin) UsesToken ¶
func (l *InteractiveLogin) UsesToken() bool
UsesToken returns true if the commands use a token (rather than basic auth)
type LoginFunc ¶
type LoginFunc func(ctx context.Context, choice SessionChoice, secrets LoginSecrets) (value any, err error)
LoginFunc logs in to the selected session with the secrets entered on the page. The passphrase is only set for sessions which need it (see SessionChoice.NeedsPassphrase). It returns ErrTOTPRequired if a two-factor code is needed, and a value which is returned by Pick
type LoginSecrets ¶
type LoginSecrets struct {
// Passphrase to unlock an encrypted session
Passphrase string
// TOTPCode two-factor authentication code
TOTPCode string
}
LoginSecrets secrets entered by the user for a login. They are passed to the login via an inherited pipe, and aren't kept
type ModeChange ¶ added in v2.59.0
type ModeChange struct {
Session string
From config.SessionMode
To config.SessionMode
// Source is ModeSourceOverride, or ModeSourceSession after a reset
Source string
// SessionMode the session's own mode
SessionMode config.SessionMode
}
ModeChange describes the result of a mode change
func (ModeChange) Message ¶ added in v2.59.0
func (c ModeChange) Message() string
Message describes the change for the conversation, e.g. "Mode is now dev (override; the session's own mode is prod)"
type ModeController ¶ added in v2.59.0
type ModeController interface {
SetMode(mode config.SessionMode, via string) (ModeChange, error)
}
ModeController changes the mode of the active session. Only the user may call it, via a transport's picker or prompts, never via a tool of the agent
type ModeOption ¶ added in v2.59.0
type ModeOption struct {
Name string
Info string
// Disabled the mode is above the ceiling
Disabled bool
// Override the mode is above the session's own mode
Override bool
Checked bool
}
ModeOption a mode in the mode control of a session
type Plan ¶
type Plan struct {
Segments []Segment
}
Plan the parsed and validated command(s) requested by the agent
func (*Plan) HasDeviceShell ¶
HasDeviceShell returns true if any of the segments runs a shell command on a device
func (*Plan) MarkDeviceCommands ¶
MarkDeviceCommands marks the segments which send a c8y_Command operation (a shell command run by the device's agent) as device shell commands. The data can come from the arguments or the input piped to the first command. This is a best effort check: a template can assemble the operation in other ways, so deny "operations create" to prevent device operations completely.
type Policy ¶
type Policy struct {
// Mode the ceiling: the maximum mode the agent may use, whatever the user
// chooses for a session. SessionModeUnset allows up to dev
Mode config.SessionMode
// Allow if non-empty, only commands matching one of these patterns are allowed
Allow []string
// Deny commands matching any of these patterns are rejected (wins over Allow)
Deny []string
// ReadCommands additional commands which should be treated as read-only
ReadCommands []string
// Approval how write commands are approved
Approval Approval
// Timeout default timeout per tool call
Timeout time.Duration
// MaxTimeout upper limit for the timeout requested by the agent
MaxTimeout time.Duration
// MaxOutputBytes maximum number of bytes returned to the agent per call
MaxOutputBytes int
// DenyPaths additional local files and folders the commands can't read, e.g. with
// --template, --data or --file. The session home folder and the active session
// file are always denied
DenyPaths []string
// AllowDeviceShell allows commands which run a shell command on a device (see
// DeviceShellCommands and c8y_Command operations). They still need a mode which
// allows creating data, and are approved like other write commands
AllowDeviceShell bool
}
Policy controls what the agent can and can't do
func DefaultPolicy ¶
func DefaultPolicy() Policy
func (Policy) Ceiling ¶ added in v2.59.0
func (p Policy) Ceiling() config.SessionMode
Ceiling returns the maximum mode the agent can use: the policy mode, or dev if unset
func (Policy) CheckCommand ¶
CheckCommand checks if the command is allowed by the allow/deny lists
func (Policy) IsReadCommand ¶
IsReadCommand checks if the command only reads data
type Request ¶ added in v2.60.0
type Request struct {
Session *mcp.ServerSession
// Tool and Command of a tool call, or Prompt the prompt which was used
Tool string
Command string
Prompt string
}
Request the MCP request which needs a session, e.g. a tool call or a prompt. It is stored in the context, so the session picker can show which agent asks for the session
type Requester ¶ added in v2.60.0
type Requester struct {
// Client name and version of the MCP client, e.g. "claude-code 2.1.0"
Client string
// Folder the working directory of the MCP server, which the agent sets when it starts
// the server (stdio mode), so it is usually the agent's project or worktree
Folder string
// Trigger what made the agent ask, e.g. the tool call or the prompt
Trigger string
// Command the c8y command of the tool call which triggered the picker
Command string
}
Requester the AI agent which asks for the session. It is shown in the session picker, so the user can tell the agents apart when several of them work at the same time
func DescribeRequester ¶ added in v2.60.0
DescribeRequester describes the agent which sent the request in the context
func (*Requester) Project ¶ added in v2.60.0
Project short name of the agent's workspace (the name of its folder), used to tell the browser tabs and notifications of several agents apart
func (*Requester) WithoutTrigger ¶ added in v2.60.0
WithoutTrigger returns a copy of the requester without the trigger, e.g. when the picker is opened later on by the server itself (such as when the token expires)
type Result ¶
type Result struct {
Stdout string
Stderr string
ExitCode int
// Truncated is true if the stdout was truncated
Truncated bool
}
Result output of the executed command(s)
type Runner ¶
type Runner struct {
// Executable path to the c8y binary
Executable string
// SessionFile session file which is used for all commands
SessionFile string
// DeniedPaths local files and folders the commands can't read or write, e.g.
// the session files, so their secrets can't be read with --template or --data
DeniedPaths []string
// SSHFallbackUser ssh user which device shell commands try if no user is given
// and the login with the local user name fails (empty to disable)
SSHFallbackUser string
// Mode the maximum mode used for write commands
Mode config.SessionMode
// BaseEnv base environment for the child processes (defaults to os.Environ())
BaseEnv []string
// Auth optional credentials provider. When set, credentials inherited from
// the server's environment are removed and the provider's credentials are
// used instead
Auth AuthProvider
}
Runner executes c8y commands as child processes
func (*Runner) Env ¶
func (r *Runner) Env(mode config.SessionMode, authEnv []string) []string
Env builds the environment for a child process
func (*Runner) Run ¶
func (r *Runner) Run(ctx context.Context, plan *Plan, stdin string, tag string, maxOutput int) (*Result, error)
Run executes the plan. Read-only commands are executed in prod (read-only) mode so the existing c8y mode checks reject any write request, even if the command was misclassified.
type Segment ¶
type Segment struct {
// Args arguments passed to c8y (without the leading "c8y")
Args []string
// CommandPath resolved command path, e.g. "devices list"
CommandPath string
// Read true if the command only reads data
Read bool
// DeviceShell true if the command runs a shell command on a device. It has no
// dry run mode, so no preview can be shown
DeviceShell bool
// Extension true if the command is provided by an extension. Extension commands
// (e.g. scripts) are passed the arguments as they are, and may reject unknown flags
Extension bool
}
Segment a single c8y command within a pipeline
type Selection ¶
type Selection struct {
Choice SessionChoice
// Mode the mode the user chose (a mode up to the ceiling), or unset if the page had no
// mode control. The caller applies it
Mode config.SessionMode
// ModeOnly true if only the mode of the current session is changed: no login was done
// and Value is nil
ModeOnly bool
// Value returned by the login (if any)
Value any
}
Selection the session selected by the user
type Server ¶
type Server struct {
Version string
// Session, Runner the session used by the commands. Use SetSession to change
// them once the server is running
Session SessionInfo
Runner *Runner
Policy Policy
Classifier *Classifier
// OnCall optional callback which is called after each tool call, e.g. to log the
// agent's activity
OnCall func(tool string, command string, outcome string)
// Gate optional check which is run before each tool call, e.g. to wait until the
// user has selected a session
Gate func(ctx context.Context, ss *mcp.ServerSession) error
// SwitchSession optional function which lets the user select another session. It is
// offered as an MCP prompt (in Claude Code a slash command), which only the user can
// run, not the agent. It returns a message for the conversation, and should not wait
// for the user's selection: tool calls wait for it instead (see Gate)
SwitchSession func(ctx context.Context) (string, error)
// SwitchSessionTo optional function which switches to the named session straight away
// if it needs no passphrase or code (and otherwise opens the picker at its unlock
// step), then applies the mode (if not empty). It is used by the switch_session prompt
// when the user gives a session or a mode
SwitchSessionTo func(ctx context.Context, session string, mode string) (string, error)
// SessionNames optional function which lists the names of the sessions, to complete
// the session argument of the switch_session prompt
SessionNames func(ctx context.Context) []string
// EnableModePrompt offers the mode prompt, which changes the mode of the current
// session (see SetMode)
EnableModePrompt bool
// ConfirmDeviceShell optional confirmation by the user of commands which run a shell
// command on a device, in addition to the normal approval. Unlike the approval, the
// MCP client can't answer it
ConfirmDeviceShell func(ctx context.Context, session SessionInfo, command string) error
// Logf optional function which logs mode changes
Logf func(format string, args ...any)
// contains filtered or unexported fields
}
Server MCP server which exposes go-c8y-cli to an agent
func (*Server) Active ¶
func (s *Server) Active() (SessionInfo, *Runner)
Active returns the session and runner used for new tool calls
func (*Server) EffectiveMode ¶ added in v2.59.0
func (s *Server) EffectiveMode(key string, sessionMode string) config.SessionMode
EffectiveMode returns the mode the agent gets in a session: the ceiling, limited by the override of the user, or the mode of the session
func (*Server) Instructions ¶
Instructions returns the instructions sent to the MCP client
func (*Server) ModeOverride ¶ added in v2.59.0
func (s *Server) ModeOverride(key string) (config.SessionMode, bool)
ModeOverride returns the mode the user chose for a session, if any
func (*Server) SetMode ¶ added in v2.59.0
func (s *Server) SetMode(mode config.SessionMode, via string) (ModeChange, error)
SetMode changes the mode of the active session without a new login. SessionModeUnset resets it to the session's own mode. The mode can't exceed the ceiling. via names the source of the change in the log. It must only be called for the user's choice.
func (*Server) SetSession ¶
func (s *Server) SetSession(info SessionInfo, runner *Runner)
SetSession changes the session used by the commands, e.g. when the user switches the session. Tool calls which have already started keep using the previous session, so a command always runs against the tenant it was approved for.
func (*Server) SetSessionKey ¶ added in v2.59.0
func (s *Server) SetSessionKey(key string, info SessionInfo, runner *Runner)
SetSessionKey is like SetSession for the session identified by key (the path of the session file, or the key of a provider session). The mode override of the session (if any) is applied to the runner.
type SessionChoice ¶
type SessionChoice struct {
// Path session file
Path string
Name string
Host string
Tenant string
Username string
// Current true if it is the session which is currently used
Current bool
// Mode the mode the agent can use with the session, e.g. "dev", and a description
// of what it allows
Mode string
ModeInfo string
// SessionMode the session's own mode, and MaxMode the highest mode the user can choose
// (the ceiling of the server). The mode control is only shown if MaxMode is set. Modes
// above SessionMode are an override, and are marked as such. Mode is preselected
SessionMode string
MaxMode string
// NeedsPassphrase true if the passphrase must be entered on the page to unlock the
// session (it is encrypted and no pin entry command is configured)
NeedsPassphrase bool
// NeedsCode true if a two-factor authentication code is expected, e.g. because the
// last login needed one. The code field is also shown when the login asks for it
NeedsCode bool
// Source where the session comes from, shown as the heading of its group, e.g.
// "Bitwarden". Empty for session files
Source string
// Provider extension session provider which listed the session, and URI its sessionUri.
// Both are empty for session files
Provider string
URI string
// Group optional grouping within the source, e.g. the folder of a vault
Group string
}
SessionChoice a session the user can select
func (SessionChoice) ModeOptions ¶ added in v2.59.0
func (c SessionChoice) ModeOptions() []ModeOption
ModeOptions returns the modes the user can choose for the session: prod, qual and dev, with the ones above MaxMode disabled. It returns nothing if the session has no MaxMode
type SessionInfo ¶
type SessionInfo struct {
Host string `json:"host"`
Tenant string `json:"tenant,omitempty"`
Username string `json:"username,omitempty"`
SessionName string `json:"session,omitempty"`
SessionMode string `json:"sessionMode"`
// Provider extension session provider which provides the session (if any)
Provider string `json:"provider,omitempty"`
}
SessionInfo non-secret information about the session used by the server
type SourceError ¶ added in v2.58.0
SourceError a source of sessions (e.g. a session provider) which could not list its sessions. It is shown in the picker instead of the source's sessions
type WebPicker ¶
type WebPicker struct {
// OpenBrowser opens the url in the browser. Defaults to the system browser
OpenBrowser func(url string) error
// Notify optional callback to draw the user's attention to the browser
Notify func(message string)
// Timeout how long the user has to select a session. Defaults to DefaultPickerTimeout
Timeout time.Duration
// Login optional function which logs in to the selected session, so the user sees
// straight away whether the session works, and can retry (e.g. after entering a
// wrong passphrase). The selection is only finished when the login succeeds
Login LoginFunc
// Requester optional description of the agent which asks for the session. It is shown
// on the page (and the project in the tab title and notification), so the user can tell
// the pickers of several agents apart
Requester *Requester
}
WebPicker lets the user select a session in the browser. It is used when the server has no terminal (stdio mode). A temporary web server listens on the loopback interface for a single selection. As other local processes can reach loopback ports, the page can only be opened with a random one-time code (passed in the URL which is opened in the browser), which is exchanged for a cookie, and the selection must come from the page itself (origin, host and csrf checks).
func (*WebPicker) Pick ¶
func (w *WebPicker) Pick(ctx context.Context, title string, choices []SessionChoice, problems ...SourceError) (*Selection, error)
Pick shows the sessions in the browser and returns the one the user selected (and logged in to, if Login is set)