aiusechat

package
v0.12.4-beta.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2025 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	InitialApprovalTimeout = 10 * time.Second
	KeepAliveExtension     = 10 * time.Second
)
View Source
const (
	APIType_Anthropic = "anthropic"
	APIType_OpenAI    = "openai"
)
View Source
const BuilderAppFileName = "app.go"
View Source
const BuilderMaxTokens = 24 * 1024
View Source
const DefaultAPI = APIType_OpenAI
View Source
const DefaultMaxTokens = 4 * 1024
View Source
const MaxEditFileSize = 100 * 1024 // 100KB
View Source
const ReadDirDefaultMaxEntries = 500
View Source
const ReadDirHardMaxEntries = 10000
View Source
const ReadFileDefaultLineCount = 100
View Source
const ReadFileDefaultMaxBytes = 50 * 1024
View Source
const StopReasonMaxBytes = "max_bytes"

Variables

View Source
var SystemPromptText = strings.Join([]string{
	`You are Wave AI, an intelligent assistant embedded within Wave Terminal, a modern terminal application with graphical widgets.`,
	`You appear as a pull-out panel on the left side of a tab, with the tab's widgets laid out on the right.`,
	`Widget context is provided as informationa only.`,
	`Do NOT assume any API access or ability to interact with the widgets except via tools provided (note that some widgets may expose NO tools, so their context is informational only).`,
}, " ")
View Source
var SystemPromptText_OpenAI = strings.Join([]string{
	`You are Wave AI, an assistant embedded in Wave Terminal (a terminal with graphical widgets).`,
	`You appear as a pull-out panel on the left; widgets are on the right.`,

	`Tools define your only capabilities. If a capability is not provided by a tool, you cannot do it.`,
	`Context from widgets is read-only unless a tool explicitly grants interaction.`,
	`Never fabricate data. If you lack data or access, say so and offer the next best step (e.g., suggest enabling a tool).`,

	`Be concise and direct. Prefer determinism over speculation. If a brief clarifying question eliminates guesswork, ask it.`,

	`User-attached text files may appear inline as <AttachedTextFile_xxxxxxxx file_name="...">\ncontent\n</AttachedTextFile_xxxxxxxx>.`,
	`User-attached directories use the tag <AttachedDirectoryListing_xxxxxxxx directory_name="...">JSON DirInfo</AttachedDirectoryListing_xxxxxxxx>.`,
	`If multiple attached files exist, treat each as a separate source file with its own file_name.`,
	`When the user refers to these files, use their inline content directly; do NOT call any read_text_file or file-access tools to re-read them unless asked.`,

	`When presenting commands or any runnable multi-line code, always use fenced Markdown code blocks.`,
	`Use an appropriate language hint after the opening fence (e.g., "bash" for shell commands, "go" for Go, "json" for JSON).`,
	`For shell commands, do NOT prefix lines with "$" or shell prompts. Use placeholders in ALL_CAPS (e.g., PROJECT_ID) and explain them once after the block if needed.`,
	"Reserve inline code (single backticks) for short references like command names (`grep`, `less`), flags, env vars, file paths, or tiny snippets not meant to be executed.",
	`You may use Markdown (lists, tables, bold/italics) to improve readability.`,
	`Never comment on or justify your formatting choices; just follow these rules.`,
	`When generating code or command blocks, try to keep lines under ~100 characters wide where practical (soft wrap; do not break tokens mid-word). Favor indentation and short variable names to stay compact, but correctness always takes priority.`,

	`If a request would execute dangerous or destructive actions, warn briefly and provide a safer alternative.`,
	`If output is very long, prefer a brief summary plus a copy-ready fenced block or offer a follow-up chunking strategy.`,

	`You can write and edit local files on disk using available tools, but you cannot execute shell commands, run code in the terminal, or read/write remote files.`,
	`If the user asks you to execute commands or run code, or deal with remote files say that these features aren't available yet AND make sure to say that they are coming soon (stay tuned for updates).`,
	`Instead, show them exactly what command or code they could copy-paste to run manually.`,

	`You have NO API access to widgets or Wave unless provided via an explicit tool.`,
}, " ")

Functions

func CombineConsecutiveSameRoleMessages

func CombineConsecutiveSameRoleMessages(uiChat *uctypes.UIChat) *uctypes.UIChat

CombineConsecutiveSameRoleMessages combines consecutive UIMessages with the same role by appending their Parts together. This is useful for APIs like OpenAI that may split assistant messages into separate messages (e.g., one for text and one for tool calls).

func ConvertAIChatToUIChat

func ConvertAIChatToUIChat(aiChat *uctypes.AIChat) (*uctypes.UIChat, error)

ConvertAIChatToUIChat converts an AIChat to a UIChat by routing to the appropriate provider-specific converter based on APIType, then combining consecutive same-role messages.

func CreateWriteTextFileDiff added in v0.12.2

func CreateWriteTextFileDiff(ctx context.Context, chatId string, toolCallId string) ([]byte, []byte, error)

CreateWriteTextFileDiff generates a diff for write_text_file or edit_text_file tool calls. Returns the original content, modified content, and any error. For Anthropic, this returns an unimplemented error.

func CurrentToolApprovalStatus

func CurrentToolApprovalStatus(toolCallId string) string

func EditTextFileDryRun added in v0.12.2

func EditTextFileDryRun(input any, fileOverride string) ([]byte, []byte, error)

EditTextFileDryRun applies edits to a file and returns the original and modified content without writing to disk. Takes the same input format as editTextFileCallback.

func GenerateCurrentTabStatePrompt

func GenerateCurrentTabStatePrompt(blocks []*waveobj.Block, widgetAccess bool) string

func GenerateTabStateAndTools

func GenerateTabStateAndTools(ctx context.Context, tabid string, widgetAccess bool) (string, []uctypes.ToolDefinition, error)

func GetAdderToolDefinition

func GetAdderToolDefinition() uctypes.ToolDefinition

Used for internal testing of tool loops

func GetBuilderEditAppFileToolDefinition added in v0.12.2

func GetBuilderEditAppFileToolDefinition(appId string, builderId string) uctypes.ToolDefinition

func GetBuilderListFilesToolDefinition added in v0.12.2

func GetBuilderListFilesToolDefinition(appId string) uctypes.ToolDefinition

func GetBuilderWriteAppFileToolDefinition added in v0.12.2

func GetBuilderWriteAppFileToolDefinition(appId string, builderId string) uctypes.ToolDefinition

func GetCaptureScreenshotToolDefinition

func GetCaptureScreenshotToolDefinition(tabId string) uctypes.ToolDefinition

func GetChatUsage

func GetChatUsage(chat *uctypes.AIChat) uctypes.AIUsage

func GetDeleteTextFileToolDefinition added in v0.12.2

func GetDeleteTextFileToolDefinition() uctypes.ToolDefinition

func GetEditTextFileToolDefinition added in v0.12.2

func GetEditTextFileToolDefinition() uctypes.ToolDefinition

func GetGlobalRateLimit

func GetGlobalRateLimit() *uctypes.RateLimitInfo

func GetReadDirToolDefinition

func GetReadDirToolDefinition() uctypes.ToolDefinition

func GetReadTextFileToolDefinition

func GetReadTextFileToolDefinition() uctypes.ToolDefinition

func GetTermCommandOutputToolDefinition added in v0.12.2

func GetTermCommandOutputToolDefinition(tabId string) uctypes.ToolDefinition

func GetTermGetScrollbackToolDefinition

func GetTermGetScrollbackToolDefinition(tabId string) uctypes.ToolDefinition

func GetWebNavigateToolDefinition

func GetWebNavigateToolDefinition(tabId string) uctypes.ToolDefinition

func GetWriteTextFileToolDefinition added in v0.12.2

func GetWriteTextFileToolDefinition() uctypes.ToolDefinition

func MakeBlockShortDesc

func MakeBlockShortDesc(block *waveobj.Block) string

func RegisterToolApproval

func RegisterToolApproval(toolCallId string)

func ResolveToolCall

func ResolveToolCall(toolDef *uctypes.ToolDefinition, toolCall uctypes.WaveToolCall, chatOpts uctypes.WaveChatOpts) (result uctypes.AIToolResult)

func RunAIChat

func RunAIChat(ctx context.Context, sseHandler *sse.SSEHandlerCh, backend UseChatBackend, chatOpts uctypes.WaveChatOpts) (*uctypes.AIMetrics, error)

func UpdateToolApproval

func UpdateToolApproval(toolCallId string, approval string, keepAlive bool) error

func WaitForToolApproval

func WaitForToolApproval(toolCallId string) string

func WaveAIGetChatHandler

func WaveAIGetChatHandler(w http.ResponseWriter, r *http.Request)

func WaveAIPostMessageHandler

func WaveAIPostMessageHandler(w http.ResponseWriter, r *http.Request)

func WaveAIPostMessageWrap

func WaveAIPostMessageWrap(ctx context.Context, sseHandler *sse.SSEHandlerCh, message *uctypes.AIMessage, chatOpts uctypes.WaveChatOpts) error

Types

type ApprovalRegistry

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

type ApprovalRequest

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

type CommandInfo added in v0.12.1

type CommandInfo struct {
	Command  string `json:"command"`
	Status   string `json:"status"`
	ExitCode *int   `json:"exitcode,omitempty"`
}

type PostMessageRequest

type PostMessageRequest struct {
	TabId        string            `json:"tabid,omitempty"`
	BuilderId    string            `json:"builderid,omitempty"`
	BuilderAppId string            `json:"builderappid,omitempty"`
	ChatID       string            `json:"chatid"`
	Msg          uctypes.AIMessage `json:"msg"`
	WidgetAccess bool              `json:"widgetaccess,omitempty"`
}

PostMessageRequest represents the request body for posting a message

type StaticFileInfo added in v0.12.4

type StaticFileInfo struct {
	Name         string `json:"name"`
	Size         int64  `json:"size"`
	Modified     string `json:"modified"`
	ModifiedTime string `json:"modified_time"`
}

type TermCommandOutputToolInput added in v0.12.2

type TermCommandOutputToolInput struct {
	WidgetId string `json:"widget_id"`
}

type TermGetScrollbackToolInput

type TermGetScrollbackToolInput struct {
	WidgetId  string `json:"widget_id"`
	LineStart int    `json:"line_start,omitempty"`
	Count     int    `json:"count,omitempty"`
}

type TermGetScrollbackToolOutput

type TermGetScrollbackToolOutput struct {
	TotalLines         int          `json:"totallines"`
	LineStart          int          `json:"linestart"`
	LineEnd            int          `json:"lineend"`
	ReturnedLines      int          `json:"returnedlines"`
	Content            string       `json:"content"`
	SinceLastOutputSec *int         `json:"sincelastoutputsec,omitempty"`
	HasMore            bool         `json:"hasmore"`
	NextStart          *int         `json:"nextstart"`
	LastCommand        *CommandInfo `json:"lastcommand,omitempty"`
}

type UseChatBackend added in v0.12.4

type UseChatBackend interface {
	// RunChatStep executes a single step in the chat conversation with the AI backend.
	// Returns the stop reason, native messages from the response, rate limit info, and any error.
	// The cont parameter allows continuing from a previous response (e.g., after rate limiting).
	RunChatStep(
		ctx context.Context,
		sseHandler *sse.SSEHandlerCh,
		chatOpts uctypes.WaveChatOpts,
		cont *uctypes.WaveContinueResponse,
	) (*uctypes.WaveStopReason, []uctypes.GenAIMessage, *uctypes.RateLimitInfo, error)

	// UpdateToolUseData updates the tool use data for a specific tool call in the chat.
	// This is used to update the UI state for tool execution (approval status, results, etc.)
	UpdateToolUseData(chatId string, toolCallId string, toolUseData *uctypes.UIMessageDataToolUse) error

	// ConvertToolResultsToNativeChatMessage converts tool execution results into native chat messages
	// that can be sent back to the AI backend. Returns a slice of messages (some backends may
	// require multiple messages per tool result).
	ConvertToolResultsToNativeChatMessage(toolResults []uctypes.AIToolResult) ([]uctypes.GenAIMessage, error)

	// ConvertAIMessageToNativeChatMessage converts a generic AIMessage (from the user)
	// into the backend's native message format for sending to the API.
	ConvertAIMessageToNativeChatMessage(message uctypes.AIMessage) (uctypes.GenAIMessage, error)

	// GetFunctionCallInputByToolCallId retrieves the function call input data for a specific
	// tool call ID from the chat history. Returns the function call structure
	// or nil if not found.
	GetFunctionCallInputByToolCallId(aiChat uctypes.AIChat, toolCallId string) *uctypes.AIFunctionCallInput

	// ConvertAIChatToUIChat converts a stored AIChat (with native backend messages) into
	// a UI-friendly UIChat format that can be displayed in the frontend.
	ConvertAIChatToUIChat(aiChat uctypes.AIChat) (*uctypes.UIChat, error)
}

UseChatBackend defines the interface for AI chat backend providers (OpenAI, Anthropic, etc.) This interface abstracts the provider-specific API calls needed by the usechat system.

func GetBackendByAPIType added in v0.12.4

func GetBackendByAPIType(apiType string) (UseChatBackend, error)

GetBackendByAPIType returns the appropriate UseChatBackend implementation for the given API type

type WebNavigateToolInput

type WebNavigateToolInput struct {
	WidgetId string `json:"widget_id"`
	Url      string `json:"url"`
}

Directories

Path Synopsis
Package google provides Google Generative AI integration for WaveTerm.
Package google provides Google Generative AI integration for WaveTerm.

Jump to

Keyboard shortcuts

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