Files
ai_academy/internal/application/service/sandbox_terminal_service.go
T
runny 9058149576
Build & Publish (dsh-academy) / End-to-end inside dsh (latest, advisory) (push) Skipped
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Frontend / Docker multi-stage image (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-academy) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-academy) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-academy) / Publish to npm (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Helm / chart (push) Canceled after 0s
refactor: 项目更名 WeKnora → Academy
- 全量替换代码/配置/文档中的项目名(保留上游 GitHub 链接、weixin 文档域名、Docker Hub 镜像名)
- 重命名 32 个含项目名的文件/目录;Go module 路径改为 academy(含 client/cli 子模块)
- docreader proto 描述符采用等长替换,保持序列化字节布局有效
- Dockerfile.app 构建网络修复: browserskill 离线产物通道、PyPI/apt 国内镜像
- 运行验证: go build ✓ docker compose up ✓ 健康检查 ✓
2026-11-13 20:52:51 +08:00

277 lines
9.8 KiB
Go

// Package service: session sandbox terminal.
//
// The interactive terminal is a lookup-only entry point into the sandbox
// bound to a session: it resolves the session's pinned config exactly like
// artifact collection does (never "whatever the agent points at today"),
// refuses to provision when no live sandbox exists, and hands a provider-
// neutral PTY handle to the WebSocket layer.
package service
import (
"context"
"errors"
"time"
"academy/internal/logger"
"academy/internal/sandbox"
"academy/internal/types"
)
// SessionTerminal bundles an opened PTY with the backend that serves it, so
// the WebSocket layer can include the backend in its ready frame.
type SessionTerminal struct {
Session sandbox.RemoteTerminalSession
Backend string
// IdleDisconnect is how long the bridge should wait without PTY
// activity before closing the socket. Always a positive duration.
IdleDisconnect time.Duration
}
// SandboxTerminalService opens interactive terminals on session sandboxes.
type SandboxTerminalService struct {
pinner *SessionSandboxPinner
resolver sandbox.TenantSandboxResolver
fallback sandbox.Manager
policy WorkspaceSandboxPolicy
// desktop is Lite: remote pins and configs are never resolved there.
desktop bool
}
// NewSandboxTerminalService wires the terminal service. All dependencies
// are optional individually; with no pinner the service reports "no live
// sandbox" for every session.
func NewSandboxTerminalService(
pinner *SessionSandboxPinner,
resolver sandbox.TenantSandboxResolver,
fallback sandbox.Manager,
policy WorkspaceSandboxPolicy,
host HostSandboxManager,
) *SandboxTerminalService {
return &SandboxTerminalService{
pinner: pinner,
resolver: resolver,
fallback: fallback,
policy: policy,
desktop: host.Desktop,
}
}
// OpenSessionTerminal attaches to the session's currently bound sandbox
// without ever creating or resuming one. This is the path a panel open and
// an automatic reconnect take: a running sandbox is attached, a bound
// sandbox that is not confirmed running reports ErrSandboxPaused, and a
// missing one reports ErrNoLiveSessionSandbox. Opening a panel must not
// conjure or wake a microVM.
//
// The WebSocket handler turns those errors into SANDBOX_PAUSED /
// SANDBOX_NOT_BOUND frames the UI answers with an explicit button. That
// confirmed click is what calls EnsureSessionTerminal.
//
// Error contract (the WebSocket handler maps these onto protocol error
// frames):
// - sandbox.ErrNoLiveSessionSandbox — the session has no bound sandbox.
// - sandbox.ErrSandboxPaused — the bound sandbox is paused; resume needs
// an explicit click (EnsureSessionTerminal with AllowResume).
// - ErrTerminalUnsupported — the resolved backend cannot stream PTYs
// (Docker, disabled manager).
// - any other error — resolution or provider failure.
func (s *SandboxTerminalService) OpenSessionTerminal(
ctx context.Context,
sessionID string,
opts sandbox.RemoteTerminalOptions,
) (*SessionTerminal, error) {
opts.AllowResume = false
mgr, _, err := s.resolveSessionManager(ctx, sessionID)
if err != nil {
return nil, err
}
return s.openOnManager(ctx, mgr, sessionID, opts)
}
// resolveSessionManager mirrors ArtifactCollector.sessionSource: pin first,
// never the agent's current choice.
func (s *SandboxTerminalService) resolveSessionManager(
ctx context.Context,
sessionID string,
) (sandbox.Manager, SandboxPin, error) {
if s.pinner == nil || s.desktop {
return nil, SandboxPin{}, sandbox.ErrNoLiveSessionSandbox
}
pin, err := s.pinner.Read(ctx, sessionID)
if err != nil {
return nil, SandboxPin{}, err
}
if pin.IsZero() {
return nil, SandboxPin{}, sandbox.ErrNoLiveSessionSandbox
}
// The workspace comes from the pin, not from the request: a shared agent's
// sandbox lives on its owner's config, and this call runs from a panel
// open, where the request tenant is the session owner.
sessionTenantID, _ := types.TenantIDFromContext(ctx)
mgr, err := resolveTenantSandboxForConfig(
ctx, s.resolver, s.fallback, pin.TenantOr(sessionTenantID), pin.ConfigID, s.policy,
)
if err != nil {
return nil, pin, err
}
if mgr == nil {
return nil, pin, sandbox.ErrNoLiveSessionSandbox
}
return mgr, pin, nil
}
// EnsureSessionTerminal opens a PTY on the session's sandbox, provisioning
// one when the session has none and the caller supplies a sandbox config ID.
//
// Only call this for a confirmed user action. It creates and bills real
// infrastructure, so the lookup-only OpenSessionTerminal is what a page load
// or a background reconnect must use.
//
// Provisioning reuses the exact chat-flow path — the resolved agent's sandbox
// config, the workspace kill switch, and the pin claim in
// resolveSandboxForExecution — so a terminal-created sandbox is
// indistinguishable from one created by a conversation turn. The WebSocket
// handler must resolve the agent the same way a chat turn does (own agent
// or shared agent from another workspace) and pass that agent's config AND
// the workspace that owns it here: a shared agent's config does not exist in
// the caller's own workspace.
// A no-op shell command drives the lazy creation, which also seeds the
// workspace layout.
//
// With a zero provision pin the call stays lookup-only and reports
// sandbox.ErrNoLiveSessionSandbox, which the WebSocket handler maps onto
// the SANDBOX_NOT_BOUND guidance frame.
func (s *SandboxTerminalService) EnsureSessionTerminal(
ctx context.Context,
sessionID string,
provision SandboxPin,
opts sandbox.RemoteTerminalOptions,
) (*SessionTerminal, error) {
opts.AllowResume = true
mgr, _, err := s.resolveSessionManager(ctx, sessionID)
if err == nil {
terminal, terr := s.openOnManager(ctx, mgr, sessionID, opts)
if terr == nil {
return terminal, nil
}
// The pin names the config but the sandbox itself is gone
// (reclaimed out of band). Resume of a paused instance already
// happened above via AllowResume. Rebuild only when there is
// nothing left to connect to.
if errors.Is(terr, sandbox.ErrNoLiveSessionSandbox) {
if perr := s.provisionOnManager(ctx, mgr, sessionID); perr == nil {
if terminal, retryErr := s.openOnManager(ctx, mgr, sessionID, opts); retryErr == nil {
return terminal, nil
} else {
terr = retryErr
}
}
}
return nil, terr
}
if !errors.Is(err, sandbox.ErrNoLiveSessionSandbox) || provision.IsZero() {
return nil, err
}
// provision.TenantID owns provision.ConfigID; for a shared agent that is
// the lending workspace, which the WebSocket handler resolved alongside the
// config. Falling back to the request tenant keeps own-agent callers (and
// any caller that has no agent context) on their own workspace.
sessionTenantID, _ := types.TenantIDFromContext(ctx)
mgr, _, err = resolveSandboxForExecution(
ctx, s.resolver, s.fallback, s.pinner,
provision.TenantOr(sessionTenantID), sessionID, provision.ConfigID, s.policy,
withLiteDesktop(s.desktop),
)
if err != nil {
return nil, err
}
if mgr == nil || mgr.GetType() == sandbox.SandboxTypeDisabled {
return nil, sandbox.ErrNoLiveSessionSandbox
}
// Drive the lazy session-sandbox creation with a no-op command. This
// provisions the sandbox AND pins it, exactly like the first agent turn
// would.
if err := s.provisionOnManager(ctx, mgr, sessionID); err != nil {
return nil, err
}
return s.openOnManager(ctx, mgr, sessionID, opts)
}
// provisionOnManager drives the manager's lazy session-sandbox creation with
// a no-op shell command. The command both provisions the sandbox and seeds the
// workspace layout, matching what the first agent turn does.
func (s *SandboxTerminalService) provisionOnManager(
ctx context.Context,
mgr sandbox.Manager,
sessionID string,
) error {
executor, ok := mgr.(sandbox.SessionShellExecutor)
if !ok {
// No shell executor means the backend cannot provision (Docker as a
// session backend, disabled manager): report "no live sandbox"
// rather than a confusing provisioning failure.
return sandbox.ErrNoLiveSessionSandbox
}
if _, err := executor.ExecShellCommand(ctx, sessionID, "true", "", 60*time.Second, nil); err != nil {
logger.Warnf(ctx, "[sandbox-terminal] provision sandbox for session %s failed: %v", sessionID, err)
return err
}
return nil
}
// openOnManager opens a terminal on an already-resolved manager.
func (s *SandboxTerminalService) openOnManager(
ctx context.Context,
mgr sandbox.Manager,
sessionID string,
opts sandbox.RemoteTerminalOptions,
) (*SessionTerminal, error) {
terminal, ok := terminalManagerFromManager(mgr)
if !ok {
logger.Warnf(ctx,
"[sandbox-terminal] backend %s does not support terminals (session %s)",
mgr.GetType(), sessionID)
return nil, ErrTerminalUnsupported
}
session, err := terminal.OpenSessionTerminal(ctx, sessionID, opts)
if err != nil {
return nil, err
}
return &SessionTerminal{
Session: session,
Backend: string(mgr.GetType()),
IdleDisconnect: terminalIdleDisconnectFromManager(mgr),
}, nil
}
func terminalIdleDisconnectFromManager(mgr sandbox.Manager) time.Duration {
type idleSource interface {
TerminalIdleDisconnect() time.Duration
}
if src, ok := mgr.(idleSource); ok {
return src.TerminalIdleDisconnect()
}
return sandbox.DefaultTerminalIdleDisconnect
}
// terminalManagerFromManager narrows a manager to its terminal capability.
func terminalManagerFromManager(mgr sandbox.Manager) (sandbox.SessionTerminalManager, bool) {
provider, ok := mgr.(sandbox.SessionTerminalProvider)
if !ok {
return nil, false
}
terminal := provider.SessionTerminalManager()
if terminal == nil {
return nil, false
}
return terminal, true
}
// ErrTerminalUnsupported reports that the session's sandbox backend cannot
// serve interactive terminals. Same sentinel as sandbox.ErrTerminalUnsupported
// so errors.Is matches either name.
var ErrTerminalUnsupported = sandbox.ErrTerminalUnsupported