store

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 72 Imported by: 0 modules, 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 (
	DirectoryRole = "role"
	DirectoryTeam = "team"
)
View Source
const (
	// NativeGitHubConnectorName is the built-in Harness connector package name
	// for GitHub and GitHub Enterprise Server accounts.
	NativeGitHubConnectorName = "github"

	// NativeSentryConnectorName is the built-in Harness connector package name
	// for Sentry SaaS and self-hosted Sentry accounts.
	NativeSentryConnectorName = "sentry"
)
View Source
const (
	// NativeScheduledTasksNamespace is the personal storage and dispatch
	// namespace shared by the native scheduled-tasks module and earlier
	// scheduled-tasks plugin versions.
	NativeScheduledTasksNamespace = "scheduled-tasks"

	// NativeRemindersNamespace is the personal storage and dispatch namespace
	// shared by the native reminders module and earlier reminders plugin
	// versions.
	NativeRemindersNamespace = "reminders"
)
View Source
const ChildTurnLimitSummary = "Stopped at its action limit before finishing; guide_agent can continue it."

ChildTurnLimitSummary is the fallback when a limited child has no response.

View Source
const DefaultMaxAutoCompactionTokens uint64 = 400_000

DefaultMaxAutoCompactionTokens caps percentage-based auto-compaction on large-window models (such as 1M-context models) so long-running sessions compact at whichever threshold is reached first: the percentage trigger or 400k tokens. Explicit per-model CompactionTokens overrides still take effect.

View Source
const (
	// DefaultModuleDailyTurnLimit bounds how many agent turns one native module
	// may initiate per UTC day when no override is saved.
	DefaultModuleDailyTurnLimit = 48
)
View Source
const KnowledgeStoragePageLimit = 16

KnowledgeStoragePageLimit bounds the plugin values of one source page.

View Source
const MaxKnowledgeCollections = 128

MaxKnowledgeCollections bounds the collections of one Node.

View Source
const (
	// NativeMemoryNamespace is the personal storage namespace shared by the
	// compile-time memory module and earlier memory plugin versions.
	NativeMemoryNamespace = "memory"
)
View Source
const PersonalInstructionsArea = "instructions"

PersonalInstructionsArea names the report item of the file the Node writes.

Variables

View Source
var ErrCommandHeld = errors.New("background command is held by a stop")

ErrCommandHeld reports that a command held by a user stop records no stall yet.

View Source
var ErrProviderRenewalNotSelected = errors.New("scheduled provider authorization is no longer selected")

ErrProviderRenewalNotSelected means the account stopped being eligible after the scheduler collected it.

View Source
var ErrSessionRemovalActive = errors.New("a turn of the session removal is active")

ErrSessionRemovalActive marks the removing transaction's busy fault when a turn of the removal runs. The Node stops and awaits such turns first, but the scheduler can still claim queued input after that; the Node then rolls the attempt back and stops that turn as well.

View Source
var KnowledgeSchema string
View Source
var NativeGitHubConnectorInfo = sync.OnceValue(func() protocol.PluginInfo {
	version := "1.0.0"
	origin := defaultGitHubAPIOrigin
	header := "Authorization"
	info := protocol.DefaultPluginInfo()
	info.Summary = protocol.DefaultPluginSummary()
	info.Summary.Name = NativeGitHubConnectorName
	info.Summary.Version = &version
	info.Summary.Digest = nativeGitHubConnectorDigest
	info.Summary.Enabled = true
	info.Summary.Compatibility = protocol.PluginCompatibility{Kind: "compatible"}

	cli := protocol.DefaultPluginConnectorAuthLocalCliPayload()
	cli.Command = "gh"
	cli.Status = protocol.PluginConnectorCliStatus{
		Argv:    []string{"auth", "status", "--active", "--hostname", "github.com", "--json", "hosts"},
		Account: "/hosts/github.com/0/login",
		Condition: &protocol.PluginModelAuthCondition{
			Pointer: "/hosts/github.com/0/active",
			Values:  []json.RawMessage{json.RawMessage("true")},
		},
	}
	cli.Token = protocol.PluginConnectorCliToken{
		Argv:  []string{"auth", "token", "--hostname", "github.com", "--user", "{account}"},
		Parse: protocol.PluginConnectorParse{Kind: "line"},
	}
	cli.TimeoutMs = 15000
	cli.MaxOutput = 65536

	decl := protocol.DefaultPluginConnectorDeclaration()
	decl.ID = NativeGitHubConnectorName
	decl.Display = protocol.PluginDesktopNavigation{Label: "GitHub", Icon: nativeConnectorIcon("github")}
	decl.Accounts = protocol.PluginConnectorAccountsSingle
	decl.Origins = []string{origin}
	decl.Auth = []protocol.PluginConnectorAuth{
		{Kind: string(protocol.PluginConnectorKindSecret), Data: protocol.PluginConnectorAuthSecretPayload{Fields: []string{"token"}}},
		{Kind: string(protocol.PluginConnectorKindLocalCli), Data: cli},
	}
	decl.Fields = []protocol.PluginConnectorField{
		{Name: "token", Title: "Token", Secret: true},
		{Name: "host", Title: "Enterprise API host", Secret: false, Optional: true},
	}
	decl.Inject = []protocol.PluginConnectorInjection{
		{Origin: &origin, Header: &header, Prefix: "Bearer "},
	}

	ext := protocol.DefaultPluginExtension()
	ext.ApiVersion = "v1"
	ext.Connectors = []protocol.PluginConnectorDeclaration{decl}
	info.Extension = &ext
	return info
})

NativeGitHubConnectorInfo returns the built-in GitHub connector declaration, supporting personal access tokens (with an optional enterprise API host) and local gh CLI binding.

View Source
var NativeMemoryStorageInfo = sync.OnceValue(func() protocol.PluginInfo {
	keySettings := "memory/settings"
	keyCatalog := "memory/catalog"
	prefixEntry := "memory/entry/"
	prefixBody := "memory/body/"
	version := "1.0.0"
	info := protocol.DefaultPluginInfo()
	info.Summary = protocol.DefaultPluginSummary()
	info.Summary.Name = NativeMemoryNamespace
	info.Summary.Version = &version
	info.Summary.Digest = nativeMemoryDigest
	info.Summary.Enabled = true
	info.Summary.Compatibility = protocol.PluginCompatibility{Kind: "compatible"}
	info.Extension = &protocol.PluginExtension{
		ApiVersion: "v1",
		Actions: []protocol.PluginAction{
			protocol.PluginActionReadStorage,
			protocol.PluginActionWriteStorage,
			protocol.PluginActionReadProjects,
		},
		Storage: &protocol.PluginStorageDeclaration{
			Collections: []protocol.PluginStorageCollection{
				{
					Scope: protocol.PluginStorageScopeNode,
					Key:   &keySettings,
					Schema: json.RawMessage(`{
						"type": "object",
						"required": ["v", "settings"],
						"properties": {
							"v": {"const": 1},
							"settings": {
								"type": "object",
								"properties": {
									"enabled": {"type": "boolean", "default": true},
									"auto_write": {"type": "boolean", "default": true},
									"context_bytes": {"type": "integer", "minimum": 2048, "maximum": 65536, "default": 8192},
									"review_after_days": {"type": "integer", "minimum": 1, "maximum": 3650, "default": 90}
								}
							}
						}
					}`),
				},
				{
					Scope: protocol.PluginStorageScopeNode,
					Key:   &keyCatalog,
					Schema: json.RawMessage(`{
						"type": "object",
						"required": ["v", "pages", "active", "archived", "next"],
						"properties": {
							"v": {"const": 1},
							"pages": {
								"type": "object",
								"propertyNames": {"pattern": "^(0|[1-9][0-9]*)$"},
								"additionalProperties": {"type": "integer", "minimum": 1, "maximum": 2}
							},
							"active": {"type": "integer", "minimum": 0},
							"archived": {"type": "integer", "minimum": 0},
							"next": {"type": "integer", "minimum": 0}
						}
					}`),
				},
				{
					Scope:  protocol.PluginStorageScopeNode,
					Prefix: &prefixEntry,
					Index:  &protocol.PluginStorageDeclarationIndex{Semantic: true},
					Schema: json.RawMessage(`{
						"type": "object",
						"required": ["v", "summary", "hash", "body_page", "body_revision"],
						"properties": {
							"v": {"const": 1},
							"hash": {"type": "string", "pattern": "^[0-9a-f]{16}$"},
							"body_page": {"type": "string", "pattern": "^(0|[1-9][0-9]*)$"},
							"body_revision": {"type": "integer", "minimum": 1},
							"summary": {
								"type": "object",
								"required": ["id", "project", "title", "kind", "archived", "revision", "updated_at_ms"],
								"properties": {
									"id": {"type": "string", "pattern": "^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"},
									"project": {"type": ["string", "null"]},
									"bot": {"type": ["string", "null"], "pattern": "^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"},
									"title": {"type": "string", "minLength": 1},
									"kind": {"enum": ["user", "feedback", "project", "reference"]},
									"archived": {"type": "boolean"},
									"revision": {"type": "integer", "minimum": 0},
									"updated_at_ms": {"type": "integer", "minimum": 0}
								}
							}
						}
					}`),
				},
				{
					Scope:  protocol.PluginStorageScopeNode,
					Prefix: &prefixBody,
					Schema: json.RawMessage(`{
						"type": "object",
						"required": ["v", "bodies"],
						"properties": {
							"v": {"const": 1},
							"bodies": {
								"type": "object",
								"maxProperties": 2,
								"additionalProperties": {
									"type": "object",
									"required": ["body", "revision"],
									"properties": {
										"body": {"type": "string"},
										"revision": {"type": "integer", "minimum": 1}
									}
								}
							}
						}
					}`),
				},
			},
		},
	}
	return info
})

NativeMemoryStorageInfo returns the built-in storage declaration for the native memory module, preserving the storage collections and semantic index of the original memory plugin.

View Source
var NativeRemindersStorageInfo = sync.OnceValue(func() protocol.PluginInfo {
	prefixReminder := "reminder/"
	version := "1.0.0"
	info := protocol.DefaultPluginInfo()
	info.Summary = protocol.DefaultPluginSummary()
	info.Summary.Name = NativeRemindersNamespace
	info.Summary.Version = &version
	info.Summary.Digest = nativeRemindersDigest
	info.Summary.Enabled = true
	info.Summary.Compatibility = protocol.PluginCompatibility{Kind: "compatible"}
	info.Extension = &protocol.PluginExtension{
		ApiVersion: "v1",
		Actions: []protocol.PluginAction{
			protocol.PluginActionReadStorage,
			protocol.PluginActionWriteStorage,
			protocol.PluginActionDispatch,
			protocol.PluginActionNotify,
			protocol.PluginActionReadProjects,
		},
		Storage: &protocol.PluginStorageDeclaration{
			Collections: []protocol.PluginStorageCollection{
				{
					Scope:  protocol.PluginStorageScopeNode,
					Prefix: &prefixReminder,
					Schema: json.RawMessage(`{
						"type": "object",
						"required": ["id", "project", "title"],
						"properties": {
							"id": {"type": "string", "pattern": "^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$"},
							"project": {"type": ["string", "null"], "default": null, "pattern": "^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$"},
							"title": {"type": "string", "minLength": 1, "maxLength": 512},
							"message": {"type": "string", "default": "", "maxLength": 4096},
							"completed": {"type": "boolean", "default": false},
							"due_ms": {"type": ["integer", "null"], "default": null, "minimum": 0},
							"notified_ms": {"type": ["integer", "null"], "default": null, "minimum": 0},
							"execution_node": {
								"type": ["array", "null"],
								"minItems": 32,
								"maxItems": 32,
								"items": {"type": "integer", "minimum": 0, "maximum": 255}
							}
						}
					}`),
				},
			},
		},
	}
	return info
})

NativeRemindersStorageInfo preserves the exact "reminder/" personal storage schema and dispatch/notification capabilities previously declared by plugins/reminders/plugin.json.

View Source
var NativeScheduledTasksStorageInfo = sync.OnceValue(func() protocol.PluginInfo {
	prefixTask := "task/"
	version := "1.0.0"
	info := protocol.DefaultPluginInfo()
	info.Summary = protocol.DefaultPluginSummary()
	info.Summary.Name = NativeScheduledTasksNamespace
	info.Summary.Version = &version
	info.Summary.Digest = nativeScheduledTasksDigest
	info.Summary.Enabled = true
	info.Summary.Compatibility = protocol.PluginCompatibility{Kind: "compatible"}
	info.Extension = &protocol.PluginExtension{
		ApiVersion: "v1",
		Actions: []protocol.PluginAction{
			protocol.PluginActionReadStorage,
			protocol.PluginActionWriteStorage,
			protocol.PluginActionDispatch,
			protocol.PluginActionStartSessions,
			protocol.PluginActionReadProjects,
			protocol.PluginActionReadModels,
			protocol.PluginActionReadTeams,
			protocol.PluginActionReadConversation,
		},
		Storage: &protocol.PluginStorageDeclaration{
			Collections: []protocol.PluginStorageCollection{
				{
					Scope:  protocol.PluginStorageScopeNode,
					Prefix: &prefixTask,
					Schema: json.RawMessage(`{
						"type": "object",
						"required": ["id", "name", "prompt", "config", "timing", "queue"],
						"properties": {
							"id": {"type": "string", "pattern": "^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$"},
							"name": {"type": "string", "minLength": 1, "maxLength": 256},
							"prompt": {"type": "string", "minLength": 1, "maxLength": 32768},
							"project": {"type": ["string", "null"], "default": null},
							"worktree": {"type": ["string", "null"], "default": null},
							"config": {"type": "object"},
							"enabled": {"type": "boolean", "default": true},
							"queue": {"type": "string", "pattern": "^[a-zA-Z0-9._-]{1,128}$"},
							"timing": {
								"oneOf": [
									{
										"type": "object",
										"required": ["kind", "data"],
										"properties": {
											"kind": {"const": "once"},
											"data": {
												"type": "object",
												"required": ["at_ms"],
												"properties": {
													"at_ms": {"type": "integer", "minimum": 0}
												}
											}
										}
									},
									{
										"type": "object",
										"required": ["kind", "data"],
										"properties": {
											"kind": {"const": "every"},
											"data": {
												"type": "object",
												"required": ["anchor_ms", "interval_ms"],
												"properties": {
													"anchor_ms": {"type": "integer", "minimum": 0},
													"interval_ms": {"type": "integer", "minimum": 1}
												}
											}
										}
									},
									{
										"type": "object",
										"required": ["kind", "data"],
										"properties": {
											"kind": {"const": "weekly"},
											"data": {
												"type": "object",
												"required": ["timezone", "weekdays", "hour", "minute"],
												"properties": {
													"timezone": {"type": "string", "minLength": 1},
													"weekdays": {
														"type": "array",
														"minItems": 1,
														"maxItems": 7,
														"uniqueItems": true,
														"items": {"type": "integer", "minimum": 1, "maximum": 7}
													},
													"hour": {"type": "integer", "minimum": 0, "maximum": 23},
													"minute": {"type": "integer", "minimum": 0, "maximum": 59}
												}
											}
										}
									}
								]
							},
							"execution": {"type": "string", "enum": ["model", "team"], "default": "team"},
							"team": {
								"type": ["object", "null"],
								"required": ["id"],
								"properties": {
									"id": {"type": "string", "pattern": "^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$"},
									"revision": {"type": ["string", "null"], "pattern": "^[1-9][0-9]*$", "default": null}
								},
								"default": null
							},
							"models": {"type": "object", "default": {}},
							"execution_node": {
								"type": ["array", "null"],
								"minItems": 32,
								"maxItems": 32,
								"items": {"type": "integer", "minimum": 0, "maximum": 255}
							}
						}
					}`),
				},
			},
		},
	}
	return info
})

NativeScheduledTasksStorageInfo preserves the exact "task/" personal storage schema and dispatch/session-start capabilities previously declared by plugins/scheduled-tasks/plugin.json.

View Source
var NativeSentryConnectorInfo = sync.OnceValue(func() protocol.PluginInfo {
	version := "1.0.0"
	origin := defaultSentryOrigin
	header := "Authorization"
	info := protocol.DefaultPluginInfo()
	info.Summary = protocol.DefaultPluginSummary()
	info.Summary.Name = NativeSentryConnectorName
	info.Summary.Version = &version
	info.Summary.Digest = nativeSentryConnectorDigest
	info.Summary.Enabled = true
	info.Summary.Compatibility = protocol.PluginCompatibility{Kind: "compatible"}

	decl := protocol.DefaultPluginConnectorDeclaration()
	decl.ID = NativeSentryConnectorName
	decl.Display = protocol.PluginDesktopNavigation{Label: "Sentry", Icon: nativeConnectorIcon("sentry")}
	decl.Accounts = protocol.PluginConnectorAccountsSingle
	decl.Origins = []string{origin}
	decl.Auth = []protocol.PluginConnectorAuth{
		{Kind: string(protocol.PluginConnectorKindSecret), Data: protocol.PluginConnectorAuthSecretPayload{Fields: []string{"token"}}},
	}
	decl.Fields = []protocol.PluginConnectorField{
		{Name: "token", Title: "Auth token", Secret: true},
		{Name: "host", Title: "Sentry host", Secret: false, Optional: true},
	}
	decl.Inject = []protocol.PluginConnectorInjection{
		{Origin: &origin, Header: &header, Prefix: "Bearer "},
	}

	ext := protocol.DefaultPluginExtension()
	ext.ApiVersion = "v1"
	ext.Connectors = []protocol.PluginConnectorDeclaration{decl}
	info.Extension = &ext
	return info
})

NativeSentryConnectorInfo returns the built-in Sentry connector declaration, supporting auth tokens with an optional regional or self-hosted instance host.

View Source
var NodeSchema string

Functions

func ActiveModuleDiscussion

func ActiveModuleDiscussion(ctx context.Context, db *sql.Conn, draft protocol.ConversationStart, associations []protocol.ConversationAssociation) (protocol.SessionID, error)

ActiveModuleDiscussion finds the current user's ongoing module discussion.

func ActiveSessionRemoval

func ActiveSessionRemoval(ctx context.Context, db *sql.Conn, command protocol.Command) ([]protocol.ConversationRun, error)

ActiveSessionRemoval validates a session removal and lists its turns that are still running or stopping.

func AgentCompactionBudget

func AgentCompactionBudget(selected protocol.ConversationModel, policy CompactionPolicy) *protocol.ConversationCompactionBudget

AgentCompactionBudget describes the same captured threshold used by execution.

func AgentStatisticsAffected added in v0.2.7

func AgentStatisticsAffected(ctx context.Context, db *sql.Conn, candidates []protocol.SessionID, turns []protocol.TurnID) ([]protocol.SessionID, error)

AgentStatisticsAffected finds other observed sessions selecting the changed turns, either as inherited history or as usage of a direct delegation.

func AgentTurnReviewed

func AgentTurnReviewed(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (bool, error)

AgentTurnReviewed follows explicit completion of a planning input. Nonempty feedback returns through the tool response so the model can revise its plan.

func AllowsRoutedTaskPermission

func AllowsRoutedTaskPermission(ceiling, requested protocol.Permission) bool

AllowsRoutedTaskPermission applies the same execution levels as local task turns.

func AppendCanonical

func AppendCanonical(ctx context.Context, db *sql.Conn, session protocol.SessionID, record canonical.Record) (protocol.ConversationEntry, []protocol.Event, error)

AppendCanonical preserves immutable record identity and updates only derived membership and materialized state in the caller's transaction.

func AppendCanonicalWithProvider added in v0.2.7

func AppendCanonicalWithProvider(ctx context.Context, db *sql.Conn, session protocol.SessionID, record canonical.Record, provider *protocol.ConversationProvider) (protocol.ConversationEntry, []protocol.Event, error)

AppendCanonicalWithProvider also prices reported usage from the provider that executed the request.

func ApplyIdentityDirectory

func ApplyIdentityDirectory(ctx context.Context, db *sql.Conn, source protocol.NodeID, revision uint64, addresses []link.EndpointAddress, metadata ...map[protocol.NodeID]string) error

func ApprovalActivityEvents

func ApprovalActivityEvents(ctx context.Context, db *sql.Conn, session protocol.SessionID) ([]protocol.Event, error)

ApprovalActivityEvents recomputes session activity events after an approval's state settles within the same transaction.

func ApproveProjectTaskPolicy

func ApproveProjectTaskPolicy(ctx context.Context, db *sql.Conn, value protocol.ConversationApproval) (protocol.ConversationApproval, error)

ApproveProjectTaskPolicy records the selected project's owner-configured authority on the same single-use approval as an interactive decision.

func ApprovedDiscussionDocumentRequest

func ApprovedDiscussionDocumentRequest(ctx context.Context, db *sql.Conn, turn protocol.TurnID, approval protocol.ApprovalID, request protocol.Request) error

ApprovedDiscussionDocumentRequest admits only a claimed write whose scope was bound by the native document tool. Other workspace commands stay unavailable.

func ApprovedRoutedTaskTurn

func ApprovedRoutedTaskTurn(ctx context.Context, db *sql.Conn, source protocol.SessionID, turn protocol.TurnID, approval protocol.ApprovalID, request protocol.RequestID, input protocol.StartProjectTaskInput) (protocol.QueuedTurn, error)

ApprovedRoutedTaskTurn supplies the frozen source selection only after the desktop validates the approval for this exact dispatch.

func ApprovedWorkspaceRequest

func ApprovedWorkspaceRequest(ctx context.Context, db *sql.Conn, turn protocol.TurnID, approval protocol.ApprovalID, request protocol.Request) error

ApprovedWorkspaceRequest keeps the exact durable identity already claimed by the loop; preparing an effect never creates another request after approval.

func AssignSessionMemberModel

func AssignSessionMemberModel(ctx context.Context, db *sql.Conn, node protocol.NodeID, previous protocol.RoleSnapshot, role protocol.RoleID, model *protocol.RoleModel) (protocol.RoleSnapshot, error)

func AuthorizeLocalModelRemoval

func AuthorizeLocalModelRemoval(ctx context.Context, db *sql.Conn, request protocol.Request) error

AuthorizeLocalModelRemoval admits a plugin's model removal only as the approved tool call that captured it. Controllers pass.

func AuthorizePluginRequest

func AuthorizePluginRequest(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, request protocol.Request, invocation *protocol.PluginInfo) (protocol.PluginInfo, error)

AuthorizePluginRequest keeps verified dispatch provenance inside the Node. Authored plugin contexts cannot grant themselves deferred session creation.

func AuthorizeProjectTaskBoard

func AuthorizeProjectTaskBoard(ctx context.Context, db *sql.Conn, source protocol.SessionID, turn protocol.TurnID, project protocol.ProjectID, owner *protocol.ProjectTaskOwnerSelection, requireOwner bool) (context.Context, error)

AuthorizeProjectTaskBoard confines the product's profile-local board to the authenticated local user and an active project. Board mutations require project management access; read access to a shared project is not sufficient.

func BackupPlan

func BackupPlan(ctx context.Context, db *sql.Conn, expected *uint64) (backup.Plan, error)

BackupPlan captures the configuration of one operation. A non-nil expected revision must match the stored one.

func BackupSource

func BackupSource(ctx context.Context, db *sql.Conn, node protocol.NodeID, profile string, revision uint64) (backup.Plan, []string, error)

BackupSource reads the plan and profile-relative content roots while the caller holds exclusive ownership through the database copy.

func BindTurnAttachments

func BindTurnAttachments(ctx context.Context, db *sql.Conn, turn protocol.TurnID, ids []protocol.AttachmentID) error

func BotRecipientRoster

func BotRecipientRoster(association *protocol.ConversationAssociation, roles protocol.RoleSnapshot) (*protocol.RoleProfile, bool)

BotRecipientRoster resolves an associated standalone role, or checks the associated team's capture. A changed or incomplete roster cannot turn a restricted recipient into a more powerful default Bot.

func BotRecipientRosterFor

func BotRecipientRosterFor(association *protocol.ConversationAssociation, silent bool, roles protocol.RoleSnapshot) (*protocol.RoleProfile, bool)

BotRecipientRosterFor resolves a Bot recipient roster, including silent internal module discussions when silent is true.

func CallerUser

func CallerUser(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID) (protocol.User, error)

CallerUser resolves only authenticated inbound device membership. A known outbound host does not become a controller by presenting its device identity.

func CancelQuestion added in v0.2.7

func CancelQueuedModuleTurns

func CancelQueuedModuleTurns(ctx context.Context, db *sql.Conn, session protocol.SessionID, moduleID string, now time.Time) (int, error)

CancelQueuedModuleTurns cancels unstarted queued module-origin turns on session (preserving ordinary user-queued turns).

func CanonicalEntry

func CanonicalEntry(record canonical.Record, sequence uint64) (protocol.ConversationEntry, error)

func CanonicalHTTPSOrigin

func CanonicalHTTPSOrigin(u *url.URL) (string, error)

CanonicalHTTPSOrigin canonicalizes an already-parsed HTTPS URL to its "https://host[:port]" origin (lowercased IDNA ASCII, stripping default :443).

func CaptureCanonicalPayload

func CaptureCanonicalPayload(ctx context.Context, db *sql.Conn, data json.RawMessage) (canonical.Payload, error)

CaptureCanonicalPayload externalizes only declared MIME-tagged binary fields.

func CaptureFileCheckpointsRequest

func CaptureFileCheckpointsRequest(ctx context.Context, db *sql.Conn, turn protocol.TurnID, approval protocol.ApprovalID, request protocol.Request, prepared *files.Prepared) error

CaptureFileCheckpointsRequest records what the approved request's prepared change replaces. Call it in the admission transaction before releasing the prepared filesystem effect.

func CaptureGroupSpeakerRoles

func CaptureGroupSpeakerRoles(ctx context.Context, db *sql.Conn, node protocol.NodeID, team *protocol.TeamSelection, models map[protocol.RoleID]protocol.RoleModel, speaker protocol.RoleID) (protocol.RoleSnapshot, error)

func CaptureProvider

CaptureProvider freezes current native declaration policy independently of the saved configuration. Inherited turns retain their existing captured binding.

func CaptureProviderAuthorization

func CaptureProviderAuthorization(ctx context.Context, db *sql.Conn, id protocol.ProviderID) (protocol.ConversationProvider, error)

CaptureProviderAuthorization also reads the unlisted provider a paired Node forwarded, which holds only a transferable authentication.

func CaptureSearchProvider

func CaptureSearchProvider(ctx context.Context, db *sql.Conn, selection protocol.SearchModelConfig) (protocol.ConversationProvider, error)

CaptureSearchProvider freezes public metadata while credentials remain current.

func CapturedUser

func CapturedUser(ctx context.Context, db *sql.Conn) (protocol.UserID, error)

func CapturedUserFromContext

func CapturedUserFromContext(ctx context.Context) (protocol.UserID, bool)

func CheckArtifactAccess

func CheckArtifactAccess(ctx context.Context, db *sql.Conn, id protocol.ArtifactID) error

func CheckChildAccess

func CheckChildAccess(ctx context.Context, db *sql.Conn, kind, id string) error

func CheckControllerLoginWait

func CheckControllerLoginWait(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, input protocol.CommandResumeControllerLoginPayload) (protocol.ConversationRun, error)

CheckControllerLoginWait is repeated before admission and in the effect transaction. A shared project's visibility alone never grants the right to change another controller's captured account.

func CheckDatabaseFiles

func CheckDatabaseFiles(path string) error

func CheckIdentityCreation added in v0.2.4

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

CheckIdentityCreation requires a fresh database family before a missing link.key can be created. Call it while holding the profile lock.

func CheckKnowledgeOutcome

func CheckKnowledgeOutcome(ctx context.Context, db *sql.Conn, request protocol.Request, output protocol.Output) error

CheckKnowledgeOutcome checks current collection access before a stored result can be disclosed again. A delete result has no remaining source to expose.

func CheckKnowledgeScope

func CheckKnowledgeScope(ctx context.Context, request protocol.Request) error

CheckKnowledgeScope checks a trusted runtime's declared knowledge action. Ordinary plugin requests keep using the main plugin authorization path.

func CheckNotificationAccess

func CheckNotificationAccess(ctx context.Context, db *sql.Conn, id protocol.NotificationID) error

func CheckPlanRunCommand

func CheckPlanRunCommand(input protocol.CommandRunCommandPayload, sandboxSupported, sandboxEnabled bool) error

CheckPlanRunCommand permits only foreground commands bound to the read-only workspace sandbox. Shell text cannot establish read-only authority. The launcher must enforce the OS sandbox or fail without starting the shell.

func CheckPluginCardRequest

func CheckPluginCardRequest(ctx context.Context, db *sql.Conn, node, _ protocol.NodeID, request protocol.Request) error

func CheckPluginConnectionRequest

func CheckPluginConnectionRequest(request protocol.Request, info protocol.PluginInfo) error

func CheckPluginConnectionTarget

func CheckPluginConnectionTarget(ctx context.Context, db *sql.Conn, scope protocol.PluginContext, target protocol.ConnectionResource) error

CheckPluginConnectionTarget applies the core sharing decision to the resource a plugin scope captured. A Node-wide controller surface manages every connection.

func CheckPluginPlanAction

func CheckPluginPlanAction(ctx context.Context, db *sql.Conn, request protocol.Request, action protocol.PluginAction) error

func CheckPluginRequest

func CheckPluginRequest(ctx context.Context, db *sql.Conn, request protocol.Request, info protocol.PluginInfo) error

func CheckProjectAccess

func CheckProjectAccess(ctx context.Context, db *sql.Conn, id protocol.ProjectID, manage bool) error

func CheckProjectTaskBoardApproval

func CheckProjectTaskBoardApproval(ctx context.Context, db *sql.Conn, turn protocol.TurnID, approval protocol.ApprovalID, request protocol.Request, create *protocol.CreateProjectTodoInput, assign *protocol.AssignProjectTaskOwnerInput) error

CheckProjectTaskBoardApproval binds the product board mutation to the exact tool arguments and request claimed by the engine.

func CheckProviderResource

func CheckProviderResource(ctx context.Context, db *sql.Conn, capture ProviderResourceCapture) error

func CheckResumeCursor

func CheckResumeCursor(ctx context.Context, db *sql.Conn, cursor, maxGap uint64) (head uint64, ok bool, err error)

CheckResumeCursor reports whether the event log still contains a contiguous sequence from cursor to the current head within maxGap events.

func CheckSessionAccess

func CheckSessionAccess(ctx context.Context, db *sql.Conn, id protocol.SessionID) error

func CheckTaskTurnPermission

func CheckTaskTurnPermission(ctx context.Context, db *sql.Conn, inv *AgentInvocation) error

CheckTaskTurnPermission runs before model creation. The product checks its current owner policy separately; Harness owns the live session ceiling.

func CheckTerminalAccess

func CheckTerminalAccess(ctx context.Context, db *sql.Conn, id protocol.TerminalID) error

func CheckTerminalSubscriptionAccess

func CheckTerminalSubscriptionAccess(ctx context.Context, db *sql.Conn, id protocol.TerminalID, attached bool) error

CheckTerminalSubscriptionAccess permits only an already attached stream to drain a finished terminal. The retained scope is not a retained grant.

func CheckTurnAccess

func CheckTurnAccess(ctx context.Context, db *sql.Conn, id protocol.TurnID) error

func CheckWorktreeAccess

func CheckWorktreeAccess(ctx context.Context, db *sql.Conn, id protocol.WorktreeID) error

func ChildTurnLimitNotice

func ChildTurnLimitNotice(response *string) string

ChildTurnLimitNotice includes a bounded preview for callers that only see the notice. The separate response retains its own delivery and truncation limits.

func ClaimHook

func ClaimHook(ctx context.Context, db *sql.Conn, turn protocol.TurnID, phase protocol.HooksPhase, ordinal uint64) error

func ClassifyPeer

func ClassifyPeer(ctx context.Context, db *sql.Conn, node, peer protocol.NodeID, hasNode bool) error

ClassifyPeer applies the authenticated device type to an existing pairing. It never adds trust, changes direction, or rewrites captured history owners.

func ClearConnectorCLIGrant

func ClearConnectorCLIGrant(ctx context.Context, db *sql.Conn, previous ConnectorRecord) error

ClearConnectorCLIGrant retains the chosen CLI identity so a later check can recover it when the user signs back in to the same account.

func ClearRefusedDelivery

func ClearRefusedDelivery(session protocol.SessionID)

ClearRefusedDelivery drops any remembered delivery refusal reason for session.

func CollectPlugins

func CollectPlugins(ctx context.Context, db *sql.Conn) (map[string]struct{}, error)

CollectPlugins deletes the package versions and settings revisions that no installation, queued callback, admitted turn, bound provider or assistant, or document revision refers to, and returns the digests still in use so their directories can be kept. A removed package keeps its latest settings revision: reinstalling it restores that configuration. The caller runs this only while nothing can install or capture a package.

func CommandBackgroundPending added in v0.2.4

func CommandBackgroundPending(ctx context.Context, db *sql.Conn, snapshot protocol.ProcessSnapshot) (bool, error)

CommandBackgroundPending checks for committed evidence. A process with a failed completion write exposes its retained output without another write.

func CommandFollowUpAllowed added in v0.2.4

func CommandFollowUpAllowed(ctx context.Context, db *sql.Conn, session protocol.SessionID) (bool, error)

CommandFollowUpAllowed gates automatic delivery from commands owned by a conversation. A delegated session polls its commands within the child turn.

func CompleteProjectTaskTurn

func CompleteProjectTaskTurn(ctx context.Context, db *sql.Conn, session protocol.SessionID, run protocol.ConversationRun, replyText, commit string, now time.Time) (*protocol.ProjectTaskWork, []protocol.Event, error)

CompleteProjectTaskTurn records a completed execution turn on the linked project_task_work row automatically from the turn lifecycle event, without requiring the executor model to invoke a separate reporting tool.

func CompleteProviderLogin

func CompleteProviderLogin(ctx context.Context, db *sql.Conn, node protocol.NodeID, capture ProviderLoginCapture, grant providers.AccountGrant) ([]protocol.Event, error)

func CompleteProviderModelDiscovery

func CompleteProviderModelDiscovery(ctx context.Context, db *sql.Conn, node protocol.NodeID, captured protocol.ConversationProvider, catalog protocol.ConversationDiscoveryCatalog) ([]protocol.Event, error)

CompleteProviderModelDiscovery adds an account's discovered models after sign-in. The captured revision keeps a late result from replacing edits or a new login. Existing models keep their configuration and adopt current native capabilities.

func CompleteProviderRenewal

func CompleteProviderRenewal(ctx context.Context, db *sql.Conn, node protocol.NodeID, renewal ProviderRenewal, grant providers.AccountGrant) ([]protocol.Event, error)

func ComputeRoleSkillDigest

func ComputeRoleSkillDigest(skill protocol.RoleSkill) string

ComputeRoleSkillDigest returns a deterministic sha256 digest over a Bot-private skill.

func ConfigurationReplica

func ConfigurationReplica(ctx context.Context, db *sql.Conn) (bool, error)

ConfigurationReplica reports whether the acting user's configuration is supplied by a paired desktop. The local account of a dual-role desktop stays independent.

func ConfigureWorkspaceApproval

func ConfigureWorkspaceApproval(ctx context.Context, db *sql.Conn, turn protocol.TurnID, value protocol.ConversationApproval, operation protocol.ToolOperation, command protocol.Command, changes *protocol.ChangePreview) (protocol.ConversationApproval, error)

ConfigureWorkspaceApproval applies the captured native operation's source permission policy before its approval is committed and shown to controllers.

func ConnectionBound

func ConnectionBound(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (*protocol.ConnectionResource, error)

ConnectionBound returns the resource the turn's captured configuration is bound to, if any.

func ConnectionCommand

ConnectionCommand translates a captured tool request into the shared command the Node workers execute, after checking the turn may reach its target.

func ConnectionCreated

func ConnectionCreated(ctx context.Context, db *sql.Conn, turn protocol.TurnID, owner protocol.PluginReference, target protocol.ConnectionResource) (bool, error)

ConnectionCreated reports whether this turn's package created the target through its own approved and completed save. The proof is valid in that turn while the connection still exists with the sharing of the approved creation.

func ConnectionOwner

func ConnectionOwner(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (protocol.ConversationRun, error)

ConnectionOwner returns the running turn that owns a connection operation.

func ConnectionPermits

func ConnectionPermits(config protocol.SessionConfig, project *protocol.ProjectID, target protocol.ConnectionResource, sharing *protocol.ConnectionSharing) bool

ConnectionPermits is the execution Node's sharing decision. Native resource sessions stay on their bound connection. Only a legacy SSH assistant treats its binding as a default. Unbound conversations use explicit sharing.

func ConnectionToolAllowed

func ConnectionToolAllowed(config protocol.SessionConfig, operation protocol.ToolOperation) bool

ConnectionToolAllowed limits the connection catalog of a native SSH session to operations on its bound profile. Other sessions keep their existing tools.

func ConnectionTrust

func ConnectionTrust(ctx context.Context, db *sql.Conn, turn protocol.TurnID, owner protocol.PluginReference, inspection ConnectionInspection, captured []protocol.ConnectionResource) (protocol.SshTrust, error)

ConnectionTrust builds the host-key consent an approval presents for a captured SSH operation.

func ConnectorAllowedHosts

func ConnectorAllowedHosts(pkg protocol.PluginReference, record ConnectorRecord, declaration protocol.PluginConnectorDeclaration) []string

ConnectorAllowedHosts returns the normalized host[:port] list derived from ConnectorAllowedOrigins (or an empty slice when none are valid).

func ConnectorAllowedOrigins

func ConnectorAllowedOrigins(pkg protocol.PluginReference, record ConnectorRecord, declaration protocol.PluginConnectorDeclaration) ([]string, error)

ConnectorAllowedOrigins returns the sorted, deduplicated canonical HTTPS origins permitted for outbound HTTP calls on this connector account.

Precedence:

  1. For configurable built-in Harness declarations (identified by IsNativeConnectorReference(pkg)) with an explicit non-empty "host" field: only token-authenticated ("secret") connections may use a custom host (local_cli is bound to github.com and fails closed if a custom host is set). When set, public cloud defaults are NOT added so private instance tokens can never be sent to public endpoints, and a malformed host fails closed.
  2. Valid canonical HTTPS origins declared on declaration.Origins (third-party plugin connectors remain strictly bound to their declared origins).
  3. Default cloud origin for legacy GitHub/Sentry declarations that omitted origins.
  4. Otherwise fail closed with ErrorCodePermissionDenied.

func ConnectorHasCustomHost

func ConnectorHasCustomHost(pkg protocol.PluginReference, record ConnectorRecord, declaration protocol.PluginConnectorDeclaration) bool

ConnectorHasCustomHost reports whether a built-in token connector explicitly overrides its target host via its "host" field.

func ConnectorKindFor

func ConnectorKindFor(record ConnectorRecord, declaration protocol.PluginConnectorDeclaration) protocol.ConnectorKind

ConnectorKindFor classifies a connector record into a canonical ConnectorKind.

func ConnectorRenewalAt

func ConnectorRenewalAt(record ConnectorRecord) *uint64

func ConnectorTypes

func ConnectorTypes(ctx context.Context, db *sql.Conn) ([]protocol.PluginConnectorType, error)

func ConsumeChildBackground

func ConsumeChildBackground(ctx context.Context, db *sql.Conn, parent protocol.TurnID, child protocol.SessionID, exact *protocol.TurnID) ([]protocol.Event, error)

func ConsumeCommandBackground

func ConsumeCommandBackground(ctx context.Context, db *sql.Conn, parent protocol.TurnID, snapshot protocol.ProcessSnapshot, now time.Time) ([]protocol.Event, error)

func ConsumeStoppedChildren

func ConsumeStoppedChildren(ctx context.Context, db *sql.Conn, parent protocol.TurnID, children []protocol.TurnID) ([]protocol.Event, error)

ConsumeStoppedChildren consumes the completion records of the child turns a stopped or failed parent turn cancelled. The parent's history already holds their cancellation, so the records never join a later message or start a notice turn.

func ControllerLoginReplacementAvailable

func ControllerLoginReplacementAvailable(ctx context.Context, db *sql.Conn, node protocol.NodeID, input protocol.CommandResumeControllerLoginPayload) (bool, error)

ControllerLoginReplacementAvailable checks retained controller credentials before admitting a durable recovery. Local credentials are checked at admission.

func CreateProjectTodo

func CreateProjectTodo(ctx context.Context, db *sql.Conn, source protocol.SessionID, parent protocol.TurnID, approval protocol.ApprovalID, requestID protocol.RequestID, input protocol.StartProjectTaskInput, now time.Time) (protocol.ProjectTaskWork, []protocol.Event, error)

CreateProjectTodo records the approved brief for generic native modules without creating a conversation, scheduling a turn, or resolving a model. The Code Bot records new cards on its product board instead.

func CreateStandingApproval

func CreateStandingApproval(ctx context.Context, db *sql.Conn, draft protocol.StandingApprovalDraft, now time.Time) (protocol.StandingApproval, []protocol.Event, error)

CreateStandingApproval persists a new scoped standing approval grant for the local user and emits standing_approvals_changed.

func CreateUser

func CreateUser(ctx context.Context, db *sql.Conn, name string) (protocol.User, error)

func CurrentController

func CurrentController(ctx context.Context, db *sql.Conn, node protocol.NodeID) (protocol.NodeID, error)

CurrentController resolves the Node identity used by captured controller credentials. A user without a recorded controller resolves to this Node.

func CurrentUser

func CurrentUser(ctx context.Context, db *sql.Conn) (protocol.User, error)

CurrentUser defaults only trusted internal maintenance to the local user. Public Node entry points resolve CallerUser before they call a service.

func DelegationAvailable added in v0.2.1

func DelegationAvailable(session protocol.Session, turn protocol.QueuedTurn) bool

DelegationAvailable uses the captured turn. Any non-child conversation turn can delegate to subagents automatically under the unified adaptive workflow.

func DelegationAvailableFor

func DelegationAvailableFor(session protocol.Session, turn protocol.QueuedTurn, fullConversationDiscussion bool) bool

DelegationAvailableFor extends DelegationAvailable to opted-in FullConversationTools Bot/Group discussions (excluding read-only observers).

func DeliverBackground added in v0.2.3

func DeliverBackground(ctx context.Context, db *sql.Conn, turn protocol.TurnID, initialNotice bool, now time.Time) (*protocol.ConversationEntry, []protocol.Event, error)

DeliverBackground appends one hidden callback and settles its evidence in the caller's write. An initial notice takes only the queued turn's reservation. It may produce queue events without an entry if the evidence was collected.

func DeliverInputBackground added in v0.2.3

func DeliverInputBackground(ctx context.Context, db *sql.Conn, turn protocol.TurnID, now time.Time) (*protocol.ConversationEntry, []protocol.Event, error)

DeliverInputBackground preserves waiting results, including held and non-follow-up commands, at an initial user or package input boundary only.

func DetachChildren added in v0.2.4

func DetachChildren(ctx context.Context, db *sql.Conn, parent protocol.TurnID, children []protocol.TurnID) ([]protocol.Event, error)

DetachChildren hands a turn's foreground children to background delivery when the turn makes no further model call. Their completion records then follow up like a background child's: as a notice, or with the next input.

func DiscardAttachment

func DiscardAttachment(ctx context.Context, db *sql.Conn, caller protocol.NodeID, worktree protocol.WorktreeID, id protocol.AttachmentID) error

func DiscardDraftAttachment

func DiscardDraftAttachment(ctx context.Context, db *sql.Conn, caller protocol.NodeID, id protocol.AttachmentID) error

func DiscussionOnly

func DiscussionOnly(session protocol.Session) bool

DiscussionOnly retains the existing group policy and also covers native Bot conversations that are not group chats. It does not route recipients.

func DiscussionTaskOwner

DiscussionTaskOwner applies the declaring product's policy to the same live personal directory entry at preparation and approval validation.

func DiscussionTurnTaskOwner

DiscussionTurnTaskOwner applies the declaring product's policy with an optional turn speaker when preparing a tool call in a coordinator-led group.

func DispatchJobContext

func DispatchJobContext(ctx context.Context, db *sql.Conn, identity protocol.JobID) (context.Context, error)

DispatchJobContext restores a trusted scheduled operation's canonical actor separately from the immutable settings principal retained at enqueue time.

func DispatchSettingsChanged

func DispatchSettingsChanged(ctx context.Context, db *sql.Conn, reference protocol.PluginReference, timestamp int64) ([]protocol.Event, error)

func DispatchTick

func DispatchTick(ctx context.Context, db *sql.Conn, node protocol.NodeID, timestamp int64, recovering bool) (dispatcher.Batch, []protocol.Event, error)

func EffectiveTurnCredential

func EffectiveTurnCredential(ctx context.Context, db *sql.Conn, turn protocol.TurnID, captured protocol.CredentialRef) (protocol.CredentialRef, error)

EffectiveTurnCredential leaves the admission capture immutable. Only this run's future model steps consult the latest explicitly accepted recovery.

func EnsureDefaultRoster

func EnsureDefaultRoster(ctx context.Context, db *sql.Conn) error

EnsureDefaultRoster seeds a single starter Bot once on a brand-new profile. Existing profiles or profiles where the user later deleted the starter Bot are left untouched.

func EventCursor

func EventCursor(ctx context.Context, db *sql.Conn) (uint64, error)

func EventPage

func EventPage(ctx context.Context, db *sql.Conn, node protocol.NodeID, after, through uint64) (uint64, []protocol.EventEnvelope, error)

EventPage bounds each read while preserving the committed cursor watermark.

func ExecuteAgentCommand

func ExecuteAgentCommand(ctx context.Context, db *sql.Conn, node protocol.NodeID, profile string, caller protocol.NodeID, request protocol.Request, now time.Time) (protocol.Output, []protocol.Event, error)

func ExecuteBackgroundCommand

func ExecuteBackgroundCommand(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, request protocol.Request, now time.Time) (protocol.Output, []protocol.Event, error)

func ExecuteCommand

func ExecuteCommand(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, profile string, request protocol.Request, prepared PreparedPaths) (protocol.Output, []protocol.Event, error)

func ExecuteConnectorCommand

func ExecuteConnectorCommand(ctx context.Context, db *sql.Conn, command protocol.Command, consent *ConnectorLoginCapture) (protocol.Output, error)

func ExecuteDatabaseCommand

func ExecuteDatabaseCommand(ctx context.Context, db *sql.Conn, command protocol.Command) (protocol.Output, []protocol.Event, error)

ExecuteDatabaseCommand owns the profile configuration commands. Passwords stay in their own column and never enter an output, event or fault.

func ExecuteDispatch

func ExecuteDispatch(ctx context.Context, db *sql.Conn, node protocol.NodeID, reference protocol.PluginReference, action protocol.DispatchCommand, timestamp int64) (protocol.Output, []protocol.Event, error)

func ExecuteDispatchAdmitted

func ExecuteDispatchAdmitted(ctx context.Context, db *sql.Conn, node protocol.NodeID, reference protocol.PluginReference, action protocol.DispatchCommand, timestamp int64) (protocol.Output, []protocol.Event, error)

func ExecuteIdentityCommand

func ExecuteIdentityCommand(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, request protocol.Request) (protocol.Output, []protocol.Event, error)

func ExecuteKnowledge

func ExecuteKnowledge(ctx context.Context, db *sql.Conn, request protocol.Request) (protocol.Output, []protocol.Event, error)

ExecuteKnowledge applies one collection mutation.

func ExecutePluginStorageCommand

func ExecutePluginStorageCommand(ctx context.Context, db *sql.Conn, node protocol.NodeID, profile string, caller protocol.NodeID, request protocol.Request) (protocol.Output, []protocol.Event, error)

func ExecuteProviderCommand

func ExecuteProviderCommand(ctx context.Context, db *sql.Conn, node protocol.NodeID, request protocol.Request, prepared *providers.Prepared) (protocol.Output, []protocol.Event, error)

func ExecuteSshCommand

func ExecuteSshCommand(ctx context.Context, db *sql.Conn, command protocol.Command) (protocol.Output, []protocol.Event, error)

func ExecuteTeamCommand

func ExecuteTeamCommand(ctx context.Context, db *sql.Conn, command protocol.Command) (protocol.Output, []protocol.Event, error)

func ExecuteTeamCommandAt

func ExecuteTeamCommandAt(ctx context.Context, db *sql.Conn, command protocol.Command, now time.Time) (protocol.Output, []protocol.Event, error)

ExecuteTeamCommandAt applies a command and its discussion cancellations at the same Node time.

func FilterPluginDatabases

func FilterPluginDatabases(ctx context.Context, db *sql.Conn, scope protocol.PluginContext, profiles []protocol.DatabaseProfile) ([]protocol.DatabaseProfile, error)

FilterPluginDatabases keeps the profiles a plugin scope may reach.

func FilterPluginSsh

func FilterPluginSsh(ctx context.Context, db *sql.Conn, scope protocol.PluginContext, profiles []protocol.SshProfile) ([]protocol.SshProfile, error)

FilterPluginSsh keeps the profiles a plugin scope may reach.

func FinishChildBackground

func FinishChildBackground(ctx context.Context, db *sql.Conn, child protocol.ConversationRun, now time.Time) ([]protocol.Event, error)

func FinishCommand

func FinishCommand(ctx context.Context, db *sql.Conn, finished process.Finished, now time.Time) ([]protocol.Event, error)

func FinishDispatch

func FinishDispatch(ctx context.Context, db *sql.Conn, identity protocol.JobID, result error, timestamp int64) ([]protocol.Event, error)

func FinishFilesCommand

func FinishFilesCommand(ctx context.Context, db *sql.Conn, caller protocol.NodeID, request protocol.Request, output protocol.Output, effectErr error) ([]protocol.Event, error)

func FinishHook

func FinishHook(ctx context.Context, db *sql.Conn, turn protocol.TurnID, phase protocol.HooksPhase, ordinal uint64, outcome protocol.ProcessOutcome, resultErr error) error

func FinishQueuedChild

func FinishQueuedChild(ctx context.Context, db *sql.Conn, turn protocol.TurnID, status protocol.ConversationStatus, failure *protocol.Fault, now time.Time) ([]protocol.Event, error)

func FinishRemovedWorktree

func FinishRemovedWorktree(ctx context.Context, db *sql.Conn, id protocol.WorktreeID) ([]protocol.Event, error)

func FitConversationPage

func FitConversationPage(page *protocol.ConversationPage, extraBytes int) ([]protocol.TurnID, error)

func FollowUpExecution

FollowUpExecution checks the local authority again on both sides of the network round trip. No writer is held while waiting for the controller.

func FollowUpExecutor

func FollowUpExecutor(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, b protocol.ProjectTaskFollowUpBinding, queue bool, request protocol.Request) (protocol.TurnID, []protocol.Event, error)

FollowUpExecutor resolves the authenticated peer to its own user and the founding turn, not to an owner declared by the sender. All queue checks and insertion use one write transaction.

func ForgetLocalModel

func ForgetLocalModel(ctx context.Context, db *sql.Conn, id string) (bool, error)

ForgetLocalModel deletes the registration of a model whose files were removed and reports whether it did. A model the settings select or a knowledge collection names stays registered, so that the choice keeps its name and the collection its model. A pinned model has no registration and stays listed.

func ForkPluginConversation

func ForkPluginConversation(ctx context.Context, db *sql.Conn, source, target protocol.SessionID, through protocol.TurnID, preserveCurrent bool) error

func FrozenHooks

func FrozenHooks(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (protocol.HooksSettings, error)

func FullConversationDiscussion

func FullConversationDiscussion(ctx context.Context, a *protocol.ConversationAssociation) bool

FullConversationDiscussion checks whether ctx carries a DirectoryDiscussion registration enabling full conversation tools for association a.

func GetBlob

func GetBlob(ctx context.Context, connection *sql.Conn, digest string) ([]byte, error)

func GetTurnAttachment

func GetTurnAttachment(ctx context.Context, db *sql.Conn, turn protocol.TurnID, id protocol.AttachmentID) (protocol.Attachment, error)

func GrantConfigurationSync

func GrantConfigurationSync(ctx context.Context, db *sql.Conn, node, peer protocol.NodeID, direction link.PeerDirection) error

A previous execution relationship alone does not authorize a configuration download. The new role-bearing pairing records both direction and user.

func GroupChatOperation

func GroupChatOperation(operation protocol.ToolOperation) bool

GroupChatOperation is the native scoped operation allowlist for discussion.

func GuideChild

func GuideChild(ctx context.Context, db *sql.Conn, node protocol.NodeID, parent protocol.TurnID, identity canonical.ToolIdentity, arguments json.RawMessage, overlap bool, now time.Time) (ChildState, *AgentInvocation, []protocol.Event, error)

GuideChild guides or resumes a child of the parent turn. identity is the recorded call, guide_agent or a package tool bound to agents.guide, and locates it in the conversation; arguments are the ones that execute, which such a package tool prepares.

func GuideTaskModuleTurn

func GuideTaskModuleTurn(ctx context.Context, db *sql.Conn, node protocol.NodeID, moduleID string, sessionID protocol.SessionID, message protocol.ConversationInput, origin protocol.TurnOrigin, key string, permission protocol.Permission, now time.Time) (turnID, recipient protocol.TurnID, guided bool, queue protocol.ConversationQueue, runs []protocol.ConversationRun, events []protocol.Event, err error)

GuideTaskModuleTurn delivers mid-flight guidance to the active running task turn of sessionID under the provider's permission ceiling. If no task turn is currently running, it falls back to queueing a policy-bound follow-up turn.

func HasConfigurationSource

func HasConfigurationSource(ctx context.Context, db *sql.Conn, user protocol.User) (bool, error)

HasConfigurationSource reports whether this user's settings belong to a desktop.

func HoldStoppedCommands added in v0.2.4

func HoldStoppedCommands(ctx context.Context, db *sql.Conn, session protocol.SessionID) error

HoldStoppedCommands keeps a user stop from being undone by command evidence: the session's running and undelivered command results start no notice turn and join the user's next message instead. The Node stops the non-service commands after the stop commits; their completion finds a held record.

func HostRemovals

func HostRemovals(ctx context.Context, db *sql.Conn) ([]link.HostRemovalAttempt, error)

func HydrateCanonicalPayload

func HydrateCanonicalPayload(ctx context.Context, db *sql.Conn, payload canonical.Payload) (json.RawMessage, error)

func IdentityPeerRelationships

func IdentityPeerRelationships(ctx context.Context, db *sql.Conn) ([]link.PeerRelationship, error)

func InitializeConfigurationUsers

func InitializeConfigurationUsers(ctx context.Context, db *sql.Conn) error

InitializeConfigurationUsers runs after the local user exists in the same rehearsed schema transaction. Legacy configuration remains private to it.

func InitializeIdentity

func InitializeIdentity(ctx context.Context, db *sql.Conn) error

InitializeIdentity fixes the owner of legacy unprefixed storage namespaces. Its identity stays stable when the local administrator flag moves in a merge.

func InsertAttachment

func InsertAttachment(ctx context.Context, db *sql.Conn, caller protocol.NodeID, attachment protocol.Attachment) error

func InsertDraftAttachment

func InsertDraftAttachment(ctx context.Context, db *sql.Conn, caller protocol.NodeID, value protocol.Attachment, now time.Time) error

InsertDraftAttachment records a file published in the profile's attachment store before its controller has created a conversation or worktree.

func InstallCatalogPlugin

func InstallCatalogPlugin(ctx context.Context, db *sql.Conn, info protocol.PluginInfo, expectedRevision uint64, mode protocol.PluginInstallMode, declared protocol.PluginMcpConfiguration) (protocol.PluginInfo, error)

func InstallMarketBot

func InstallMarketBot(
	ctx context.Context,
	db *sql.Conn,
	entry protocol.BotCatalogEntry,
	repository string,
	locale string,
	targetRole *protocol.RoleID,
	expectedRevision uint64,
	now time.Time,
) (protocol.RoleProfile, []protocol.Event, error)

InstallMarketBot atomically creates or updates a Bot profile and its private skills from a validated BotCatalogEntry.

func InstallPlugin

func InstallPlugin(ctx context.Context, db *sql.Conn, info protocol.PluginInfo, expectedRevision uint64, enabled bool) (protocol.PluginInfo, error)

func InstallStandaloneMCP added in v0.2.5

func InstallStandaloneMCP(ctx context.Context, db *sql.Conn, info protocol.PluginInfo, input protocol.CommandInstallMcpPayload, configuration protocol.PluginMcpConfiguration, retainStdioEnv bool) (protocol.PluginInfo, error)

InstallStandaloneMCP saves the generated package and its credentials in the caller's transaction.

func IsDiscussionDocumentBinding

func IsDiscussionDocumentBinding(binding *ApprovalBinding) bool

IsDiscussionDocumentBinding distinguishes the native, current-session document path from workspace or package tools with the same operation.

func IsDiscussionSession

func IsDiscussionSession(ctx context.Context, db *sql.Conn, session protocol.SessionID) (bool, error)

IsDiscussionSession checks the persisted scope before an operation executes.

func IsDiscussionTurn

func IsDiscussionTurn(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (bool, error)

IsDiscussionTurn uses the turn's saved revision, not the current draft.

func IsNativeConnectorReference

func IsNativeConnectorReference(ref protocol.PluginReference) bool

IsNativeConnectorReference reports whether ref identifies a built-in Harness connector declaration.

func IsNativeStorageReference

func IsNativeStorageReference(ref protocol.PluginReference) bool

IsNativeStorageReference reports whether ref is one of the built-in synthetic native storage references.

func IsRestrictedDiscussionTurn

func IsRestrictedDiscussionTurn(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (bool, error)

IsRestrictedDiscussionTurn reports whether the turn belongs to a discussion that does not opt into full conversation tools (shell commands, plugins, etc.).

func IsStorageFull added in v0.2.4

func IsStorageFull(err error) bool

IsStorageFull reports when the storage engine could not write for lack of space.

func IsTeamBotDiscussion

func IsTeamBotDiscussion(session protocol.Session) bool

IsTeamBotDiscussion reports a projectless Sailry Bot discussion bound to a specific team (association ID "team:<id>" or a project lead with a captured team roster).

func KnowledgeExecutionContext

func KnowledgeExecutionContext(ctx context.Context, db *sql.Conn, stored KnowledgeStored) (context.Context, error)

KnowledgeExecutionContext restores the owner of a trusted indexing capture. Public queries select allowed collections before the indexing service uses it.

func KnowledgeModuleChanged

func KnowledgeModuleChanged(ctx context.Context, db *sql.Conn, name string) (bool, error)

KnowledgeModuleChanged updates automatic semantic collections after personal module KV values change outside a plugin storage command (such as executor configuration sync).

func KnowledgePackageFromContext

func KnowledgePackageFromContext(ctx context.Context) (protocol.PluginInfo, bool)

KnowledgePackageFromContext reads only the package installed by the verified resource-call entry point, never a package declared in model arguments.

func KnowledgeStorageChanged

func KnowledgeStorageChanged(ctx context.Context, db *sql.Conn, request protocol.Request) (bool, error)

KnowledgeStorageChanged follows a committed storage write of a plugin: it registers a collection that gained its first source and restarts the indexing of the package's automatic collections. It runs in the transaction of the write.

func KnowledgeStorageCommand

func KnowledgeStorageCommand(command protocol.Command) bool

KnowledgeStorageCommand reports a command that may change the plugin values a storage collection indexes.

func KnowledgeStorageUnchanged

func KnowledgeStorageUnchanged(ctx context.Context, db *sql.Conn, stored KnowledgeStored, record KnowledgeStorageRecord) (bool, error)

KnowledgeStorageUnchanged rechecks a captured record before its chunks are published or its citation is returned.

func LatestAgentPlan added in v0.2.4

func LatestAgentPlan(records []canonical.Record) *protocol.ConversationProgress

LatestAgentPlan returns the last successful plan in chronological session history unless all its steps are completed or skipped.

func LatestDirectorySession

func LatestDirectorySession(ctx context.Context, db *sql.Conn, namespace, kind, identity string) (protocol.SessionID, error)

LatestDirectorySession returns the newest active owner session bound to (namespace, kind, identity), or zero if no active discussion exists yet.

func LegacyStorageUser

func LegacyStorageUser(ctx context.Context, db *sql.Conn) (protocol.UserID, error)

func LinkAddresses

func LinkAddresses(ctx context.Context, db *sql.Conn) ([]link.EndpointAddress, error)

func LinkDirections

func LinkDirections(ctx context.Context, db *sql.Conn) ([]link.PeerTrust, error)

LinkDirections loads persisted direction independently of reachability.

func LinkPeers

func LinkPeers(ctx context.Context, db *sql.Conn) ([]protocol.NodeID, error)

func ListArtifactRevisions

func ListArtifactRevisions(ctx context.Context, db *sql.Conn, id protocol.ArtifactID, before *uint32, limit uint16, session protocol.SessionID) (protocol.ArtifactRevisionPage, error)

func ListArtifacts

func ListArtifacts(ctx context.Context, db *sql.Conn, session protocol.SessionID, after *protocol.ArtifactID, limit uint16) (protocol.ArtifactPage, error)

func ListAssociatedSessions

func ListAssociatedSessions(ctx context.Context, db *sql.Conn, request protocol.Request) (protocol.ConversationAssociationAssociatedSessions, error)

ListAssociatedSessions pages the sessions a package associated with one business identity, newest first. A worktree scope confines the page.

func ListConnectorAccounts

func ListConnectorAccounts(ctx context.Context, db *sql.Conn) ([]protocol.ConnectorAccountSummary, error)

ListConnectorAccounts returns secret-free summaries of all connector accounts visible to the authenticated user in ctx.

func ListConversationAssets

ListConversationAssets derives bounded inventory pages from canonical history. It does not index workspace writes or inspect the filesystem.

func ListDatabases

func ListDatabases(ctx context.Context, db *sql.Conn) ([]protocol.DatabaseProfile, error)

func ListDiscussionDocuments

func ListDiscussionDocuments(ctx context.Context, db *sql.Conn, session protocol.SessionID, after *protocol.ArtifactID, limit uint16) (protocol.ArtifactPage, error)

func ListDispatchJobs

func ListDispatchJobs(ctx context.Context, db *sql.Conn, packageName string, before *uint64, limit uint16) (protocol.DispatchPage, error)

ListDispatchJobs returns one history page of dispatch jobs (including native module wake jobs) for packageName.

func ListKnowledgeCollections

func ListKnowledgeCollections(ctx context.Context, db *sql.Conn, request protocol.Request) ([]protocol.KnowledgeCollection, error)

ListKnowledgeCollections lists the collections a request may read.

func ListPluginKeys

func ListPluginKeys(ctx context.Context, db *sql.Conn, reference protocol.PluginReference, prefix string, after *string, limit uint16) (protocol.PluginStoragePage, error)

func ListProjectTaskProposals

func ListProjectTaskProposals(ctx context.Context, db *sql.Conn, module string, project protocol.ProjectID) ([]protocol.ProjectTaskProposal, error)

ListProjectTaskProposals projects the original, still undecided tool requests. The source conversation and the destination project both belong to the audience.

func ListProjectTaskWork

ListProjectTaskWork never lists another user's work, even in a shared project. A Bot supplies its exact source and is further restricted to its own receipts.

func ListProjectTasks

func ListProjectTasks(ctx context.Context, db *sql.Conn, source protocol.SessionID, current protocol.TurnID, input protocol.ReadProjectTaskInput) (protocol.ProjectTaskPage, error)

ListProjectTasks pages the persisted receipts, independent of request-ledger retention or which source turn is currently running.

func ListSsh

func ListSsh(ctx context.Context, db *sql.Conn) ([]protocol.SshProfile, error)

func ListSshTerminals

func ListSshTerminals(ctx context.Context, db *sql.Conn, profile protocol.SshID, caller protocol.NodeID) ([]protocol.TerminalInfo, error)

ListSshTerminals returns the caller's open terminals of one SSH profile.

func ListStandingApprovals

ListStandingApprovals returns the local user's standing approvals matching filter. When filter.Project is set, both grants scoped to that project and all-project grants (project IS NULL) are returned because both apply to it.

func ListTurnAttachments

func ListTurnAttachments(ctx context.Context, db *sql.Conn, turn protocol.TurnID) ([]protocol.Attachment, error)

func ListUsers

func ListUsers(ctx context.Context, db *sql.Conn) ([]protocol.User, error)

func LoadAgentContext

func LoadAgentContext(ctx context.Context, db *sql.Conn, session protocol.SessionID) (canonical.Context, []string, error)

LoadAgentContext reads a session's materialized context and loaded tools without its history. Captured is derived from history and stays unset.

func LocalModelDefinition

func LocalModelDefinition(ctx context.Context, db *sql.Conn, id string) (*protocol.ModelsDefinition, error)

LocalModelDefinition reads one pinned or registered definition.

func LocalUser

func LocalUser(ctx context.Context, db *sql.Conn) (protocol.User, error)

func MCPFormSpec

func MCPFormSpec(message string, schema json.RawMessage) (protocol.ConversationQuestionSpec, error)

func MCPSettingsTargets

func MCPSettingsTargets(schema *protocol.PluginSettingsSchema, configuration protocol.PluginMcpConfiguration) map[string]string

func MarkCheckpointRestored

func MarkCheckpointRestored(ctx context.Context, db *sql.Conn, id protocol.CheckpointID) error

MarkCheckpointRestored records that a checkpoint's change was undone, in the transaction that stores the restore's receipt, so the fact survives a restart and reaches every controller with the checkpoint list.

func MarkProviderRenewalUncertain

func MarkProviderRenewalUncertain(ctx context.Context, db *sql.Conn, provider protocol.ConversationProvider, id protocol.CredentialID) error

func MaterializeSemanticSearch

func MaterializeSemanticSearch(ctx context.Context, db *sql.Conn, request protocol.Request, plan SemanticPlan, selection SemanticSelection) (page protocol.PluginStorageSearchPage, stale bool, err error)

MaterializeSemanticSearch reads the selected values of a plan. A result whose source, tags, grants or embedding choice moved since the plan falls back to the keyword page and reports it stale.

func MediaConfig

func MediaConfig(provider protocol.ProviderID, name string) protocol.SessionConfig

MediaConfig selects one assigned model outside any session.

func MediaModels

func MediaModels(ctx context.Context, db *sql.Conn) ([]protocol.MediaCandidate, error)

MediaModels lists, per purpose, the enabled models whose capability tags include it and whose channel has a driver for it.

func MediaProvider

func MediaProvider(ctx context.Context, db *sql.Conn, kind protocol.MediaKind, binding protocol.MediaBinding) (captured *protocol.ConversationProvider, present bool, err error)

MediaProvider captures the bound provider. present reports that the enabled provider still lists the model; the provider is returned only when that model can also run the purpose.

func MigrateHeadlessPeers

func MigrateHeadlessPeers(ctx context.Context, db *sql.Conn) error

MigrateHeadlessPeers preserves inbound access without treating legacy Host controllers as outbound execution services.

func MigrateRetiredMemoryEnabled

func MigrateRetiredMemoryEnabled(ctx context.Context, db *sql.Conn, enabled bool) error

MigrateRetiredMemoryEnabled preserves a user's disabled choice when retiring the bundled memory plugin if native memory/settings has not been written yet.

func NarrowLegacyController

func NarrowLegacyController(ctx context.Context, db *sql.Conn, peer protocol.NodeID) error

func NativeConnectorBaseURL

func NativeConnectorBaseURL(pkg protocol.PluginReference, record ConnectorRecord) string

NativeConnectorBaseURL returns the API base on the configured installation, preserving reverse proxy prefixes separately from the credential origin.

func NativeConnectorInfo

func NativeConnectorInfo(name string) (protocol.PluginInfo, bool)

NativeConnectorInfo returns the built-in connector definition for name, if one is defined.

func NativeConnectorInfos

func NativeConnectorInfos() []protocol.PluginInfo

NativeConnectorInfos returns all built-in Harness connector definitions in deterministic order.

func NativeGitHubConnectorReference

func NativeGitHubConnectorReference() protocol.PluginReference

NativeGitHubConnectorReference returns the synthetic package reference for the built-in GitHub connector.

func NativeMemoryReference

func NativeMemoryReference() protocol.PluginReference

NativeMemoryReference identifies the built-in native memory storage declaration so personal memory entries, FTS indexes and automatic semantic knowledge collections keep working after plugins/memory is retired.

func NativeRemindersReference

func NativeRemindersReference() protocol.PluginReference

NativeRemindersReference identifies the built-in native reminders storage and dispatch declaration.

func NativeScheduledTasksReference

func NativeScheduledTasksReference() protocol.PluginReference

NativeScheduledTasksReference identifies the built-in native scheduled-tasks storage and dispatch declaration.

func NativeSentryConnectorReference

func NativeSentryConnectorReference() protocol.PluginReference

NativeSentryConnectorReference returns the synthetic package reference for the built-in Sentry connector.

func NativeStorageInfo

func NativeStorageInfo(namespace string) (protocol.PluginInfo, bool)

NativeStorageInfo returns the built-in storage and dispatch declaration for one native module namespace.

func NativeStorageInfoForReference

func NativeStorageInfoForReference(ref protocol.PluginReference) (protocol.PluginInfo, bool)

NativeStorageInfoForReference returns the built-in declaration matching ref when ref is a synthetic native storage reference.

func NativeStorageReference

func NativeStorageReference(namespace string) (protocol.PluginReference, bool)

NativeStorageReference returns the built-in synthetic package reference for a native storage namespace, if one is defined.

func NextChildGuidance

func NextChildGuidance(ctx context.Context, db *sql.Conn, recipient protocol.TurnID) (*protocol.ConversationRun, []protocol.Event, error)

func NextCounter

func NextCounter(ctx context.Context, connection *sql.Conn, namespace Counter) (uint64, error)

NextCounter advances a watermark inside the caller's existing write transaction.

func NextEvent added in v0.2.7

func NextEvent(ctx context.Context, db *sql.Conn, node protocol.NodeID, after, through uint64) (uint64, *protocol.EventEnvelope, error)

NextEvent pins only a cursor watermark across deliveries. The next row and its current audience are read together in the caller's fresh transaction.

func NextEvents

func NextEvents(ctx context.Context, db *sql.Conn, node protocol.NodeID, after, through uint64, limit int) (uint64, []protocol.EventEnvelope, error)

NextEvents reads up to limit contiguous events after cursor in a single read transaction, filtering each against the caller's current access scope.

func NormalizeConnectorHostOrigin

func NormalizeConnectorHostOrigin(raw string) (string, error)

NormalizeConnectorHostOrigin parses a host or HTTPS URL (such as "github.corp.example", "github.corp.example:8443", or "https://github.corp.example/api/v3") into a canonical "https://host[:port]" origin. Non-HTTPS schemes, userinfo, queries, fragments, wildcards, and invalid hostnames are rejected.

func NormalizeProjectTaskArguments

func NormalizeProjectTaskArguments(raw json.RawMessage) json.RawMessage

NormalizeProjectTaskArguments strips optional "role:" / "team:" prefixes from role.id and team.id so callers forwarding board owner tokens (such as "role:<uuid>") decode cleanly as bare UUIDs, and strips product-layer orchestration extension keys so strict Harness decoding stays clean.

func OAuthHost

func OAuthHost(ctx context.Context, db *sql.Conn) (string, error)

func OAuthRegistration

func OAuthRegistration(ctx context.Context, db *sql.Conn, key string) (*string, error)

func ObserveCommandStop added in v0.2.4

func ObserveCommandStop(ctx context.Context, db *sql.Conn, parent protocol.TurnID, snapshot protocol.ProcessSnapshot, now time.Time) ([]protocol.Event, error)

ObserveCommandStop records a stop acknowledged by a tool turn. Only a confirmed stopped outcome is consumed by that acknowledgment.

func OriginalTurnUser

func OriginalTurnUser(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (protocol.User, error)

OriginalTurnUser does not follow merged_into: immutable settings revisions with the same number can contain different credentials for different users.

func OrphanedKnowledge

func OrphanedKnowledge(ctx context.Context, db *sql.Conn, catalog []KnowledgeStored) (bool, error)

OrphanedKnowledge reports whether any collection of a catalog lost its owner.

func PairIdentityMember

func PairIdentityMember(ctx context.Context, db *sql.Conn, node, peer protocol.NodeID, direction link.PeerDirection, inviter *protocol.UserID, myDevice bool) error

PairIdentityMember receives only the sharing endpoint's captured invitation scope. A repeated pairing never transfers an existing device to another user.

func PairIdentityPeer

func PairIdentityPeer(ctx context.Context, db *sql.Conn, node, peer protocol.NodeID, direction link.PeerDirection, scope link.InvitationScope) error

func PairLinkPeer

func PairLinkPeer(ctx context.Context, db *sql.Conn, peer protocol.NodeID, direction link.PeerDirection) error

PairLinkPeer unions two explicit pairings without moving a device between users. Only a newly admitted controller creates a new local user.

func PairPeerIdentity

func PairPeerIdentity(ctx context.Context, db *sql.Conn, node, peer protocol.NodeID, direction link.PeerDirection, hasNode bool) error

PairPeerIdentity records fresh membership and its authenticated device type in one transaction. A shell joins the local user without creating an orphan user.

func PendingGuidance

func PendingGuidance(ctx context.Context, db *sql.Conn, recipient protocol.TurnID) (bool, error)

func PluginConnectionAction

func PluginConnectionAction(ctx context.Context, db *sql.Conn, request protocol.Request) (protocol.PluginAction, bool, error)

PluginConnectionAction maps a database or SSH command to the software action its package must declare and checks that the captured plugin scope may reach the command's connection. It reports false for every command outside the two families, including terminals that are not SSH terminals.

func PluginModels

func PluginModels(ctx context.Context, db *sql.Conn) (protocol.PluginModelsCatalog, error)

func PluginRecorded

func PluginRecorded(ctx context.Context, db *sql.Conn, name string) (bool, error)

func PluginRequestPackage

func PluginRequestPackage(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, request protocol.Request, invocation *protocol.PluginInfo) (protocol.PluginInfo, error)

func PluginSearchDefinition

func PluginSearchDefinition(name string) string

func PluginSearchDefinitions

func PluginSearchDefinitions(ctx context.Context, db *sql.Conn) ([]string, error)

func PluginSettingsBody

func PluginSettingsBody(ctx context.Context, db *sql.Conn, name string, revision uint64) (json.RawMessage, error)

func PluginStorageRequestContext

func PluginStorageRequestContext(ctx context.Context, db *sql.Conn, request protocol.Request) (context.Context, error)

PluginStorageRequestContext resolves the requested namespace through the captured resource. The personal namespace remains the default for old SDKs.

func PluginTransactionProviders

func PluginTransactionProviders(ctx context.Context, db *sql.Conn, request protocol.Request) ([]protocol.ProviderID, error)

func PostTaskDelivery

PostTaskDelivery persists a signed assistant delivery message into an existing conversation and deduplicates durably by (session, DedupKey). It never queues a turn or calls any model.

func PowerFailed

func PowerFailed(ctx context.Context, db *sql.Conn, code int64) ([]protocol.Event, error)

PowerFailed records the system's refusal of the idle-sleep request as an error notice carrying its code.

func PrepareBackup

func PrepareBackup(ctx context.Context, db *sql.Conn, profile string, command protocol.Command) error

PrepareBackup refuses a durable backup command before it is admitted.

func PrepareCheckpointRestore

PrepareCheckpointRestore captures a checkpoint's content for a restore and the versions that already count as restored: what the file held before this change or before an earlier change of the same turn to the same file.

func PrepareHostRemoval

func PrepareHostRemoval(ctx context.Context, db *sql.Conn, host protocol.NodeID, request protocol.Request) (link.HostRemovalAttempt, error)

func PrepareProjectTaskApproval

func PrepareProjectTaskApproval(ctx context.Context, db *sql.Conn, approval protocol.ConversationApproval, input protocol.StartProjectTaskInput) error

PrepareProjectTaskApproval freezes the displayed request and resolves the selected worktree before a user can approve the operation.

func PrepareProviderCommand

func PrepareProviderCommand(ctx context.Context, db *sql.Conn, node protocol.NodeID, request protocol.Request) (*providers.Work, error)

func PrepareRestored

func PrepareRestored(ctx context.Context, staging string, node protocol.NodeID, original, target string) ([]string, error)

PrepareRestored validates an unpacked profile in private staging, upgrades its Node database to the current schema and rewrites the paths that pointed into the original profile. It returns the staging-relative files of the pre-upgrade database copy, which the restored profile retains.

func PrepareSessionForward

func PrepareSessionForward(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, request protocol.Request) (protocol.Request, error)

PrepareSessionForward keeps exact replays of already admitted operations, but a new session must be created by the Node that owns its selected model.

func ProbeConnector

func ProbeConnector(ctx context.Context, db *sql.Conn, previous ConnectorRecord, identity *protocol.PluginConnectorIdentity, checked uint64, failure *protocol.Fault) (protocol.PluginConnectorConnection, error)

func ProjectExecutorPermission

func ProjectExecutorPermission(ctx context.Context) *protocol.Permission

ProjectExecutorPermission returns the native module's selected task policy.

func ProjectMainWorktreeID

func ProjectMainWorktreeID(ctx context.Context, db *sql.Conn, project protocol.ProjectID) (protocol.WorktreeID, error)

func ProjectMentionName

func ProjectMentionName(ctx context.Context, db *sql.Conn, peer *protocol.NodeID, id protocol.ProjectID) (string, error)

Project mention labels are resolved from the authenticated user's current catalog. A remote ID has meaning only together with its paired executor.

func ProjectTaskReportNotice

func ProjectTaskReportNotice(ctx context.Context, db *sql.Conn, work protocol.ProjectTaskWork, now time.Time) ([]protocol.Event, error)

ProjectTaskReportNotice records a durable fallback notification when an executing task explicitly requests user input or submits a formal delivery and no product-level board observer claimed notification delivery.

func ProviderRecoveryIdentity

func ProviderRecoveryIdentity(ctx context.Context, db *sql.Conn, node protocol.NodeID, provider protocol.ConversationProvider, reference protocol.CredentialRef) (string, string, error)

ProviderRecoveryIdentity reads account identity even after expiry, without treating an expired token or an unresolved refresh as usable authorization.

func PruneDraftAttachments

func PruneDraftAttachments(ctx context.Context, db *sql.Conn, now time.Time) error

PruneDraftAttachments keeps abandoned uploads for the same retry window as their finish receipts. A later collection removes the unreferenced files.

func PruneResourceCatalogSources

func PruneResourceCatalogSources(ctx context.Context, db *sql.Conn, entry protocol.NodeID, allowed []protocol.NodeID) ([]protocol.NodeID, error)

PruneResourceCatalogSources follows explicit relationship removal, including removals made while this Node was stopped. A failed peer listing must not call this with an empty list.

func PublishArtifactWrite

func PublishArtifactWrite(ctx context.Context, db *sql.Conn, capture ArtifactWrite, digest string) (protocol.Output, error)

func PublishModuleNotification

func PublishModuleNotification(ctx context.Context, db *sql.Conn, moduleID string, draft protocol.NotificationDraft, now time.Time) (protocol.NotificationNotice, protocol.Event, error)

PublishModuleNotification stores or updates (when draft.Key is set) one durable user-scoped notification scoped to moduleID and returns its notification_changed event.

func PublishNativeWake

func PublishNativeWake(ctx context.Context, db *sql.Conn, namespace, topic string, payload json.RawMessage, dedupeKey string, timestamp int64) (protocol.EventID, []protocol.Event, error)

PublishNativeWake enqueues a topic event for a registered WakeProvider. A non-empty dedupeKey collapses duplicate publishes while a matching job is still queued, returning the pending job's existing EventID.

func PublishSystemNotification

func PublishSystemNotification(ctx context.Context, db *sql.Conn, draft protocol.NotificationDraft, now time.Time) (protocol.NotificationNotice, protocol.Event, error)

PublishSystemNotification stores one durable user-scoped notification inside the caller's transaction and returns its notification_changed event.

func PutBlob

func PutBlob(ctx context.Context, connection *sql.Conn, data []byte) (string, error)

PutBlob stores binary content once per digest in the current transaction.

func QuarantineFollowUp

func QuarantineFollowUp(ctx context.Context, db *sql.Conn, run protocol.ConversationRun) error

Quarantine removes unconsumed input so queue resume, send-now and edits cannot repurpose a refusal.

func QueueModuleTurn

func QueueModuleTurn(ctx context.Context, db *sql.Conn, node protocol.NodeID, moduleID string, sessionID protocol.SessionID, message protocol.ConversationInput, origin protocol.TurnOrigin, idempotencyKey string, autoStart bool, now time.Time) (protocol.TurnID, []protocol.Event, error)

QueueModuleTurn admits a turn into an existing session on a native module's behalf, enforcing access checks, 7-day idempotency, daily turn budgets, and non-spoofable TurnOrigin metadata.

func QueueModuleTurnWithPermission

func QueueModuleTurnWithPermission(ctx context.Context, db *sql.Conn, node protocol.NodeID, moduleID string, sessionID protocol.SessionID, message protocol.ConversationInput, origin protocol.TurnOrigin, idempotencyKey string, autoStart bool, permission *protocol.Permission, now time.Time) (protocol.TurnID, []protocol.Event, error)

QueueModuleTurnWithPermission behaves like QueueModuleTurn and, when permission is non-nil on a non-discussion session, updates the session's execution permission before capturing turn settings.

func QueueRejection added in v0.2.5

func QueueRejection(kind string, failure *protocol.Fault) (reason string, race bool)

QueueRejection identifies the store's exact refusals after a command result has crossed the durable request ledger. The bool distinguishes a queue race from an invalid recipient or execution scope. Unknown faults stay unclassified.

func QueueTaskModuleTurn

func QueueTaskModuleTurn(ctx context.Context, db *sql.Conn, node protocol.NodeID, moduleID string, sessionID protocol.SessionID, message protocol.ConversationInput, origin protocol.TurnOrigin, key string, autoStart bool, permission protocol.Permission, now time.Time) (protocol.TurnID, []protocol.Event, error)

func QueueTaskRouteStop

func QueueTaskRouteStop(ctx context.Context, db *sql.Conn, task protocol.RequestID, session protocol.SessionID) (protocol.NodeID, error)

QueueTaskRouteStop persists one receipt ID for all deliveries of this stop.

func QueuedModuleTurns

func QueuedModuleTurns(ctx context.Context, db *sql.Conn, session protocol.SessionID, moduleID string) ([]protocol.TurnID, error)

QueuedModuleTurns lists unstarted queued turns in session created by a native module (filtered to moduleID when non-empty).

func ReadActivityCatalog

func ReadActivityCatalog(ctx context.Context, db *sql.Conn, node protocol.NodeID) (protocol.ActivityCatalog, error)

func ReadActivityPreviews

func ReadActivityPreviews(ctx context.Context, db *sql.Conn, sessions []protocol.SessionID) ([]protocol.ActivityPreview, error)

func ReadAgentCommand

func ReadAgentCommand(ctx context.Context, db *sql.Conn, node protocol.NodeID, command protocol.Command) (protocol.Output, error)

func ReadAgentCommandForCaller

func ReadAgentCommandForCaller(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, command protocol.Command) (protocol.Output, error)

func ReadAgentProjectReferenceName

func ReadAgentProjectReferenceName(ctx context.Context, db *sql.Conn, id protocol.ProjectID) (string, error)

ReadAgentProjectReferenceName resolves only mention metadata; the project's worktree and filesystem path are not part of a conversation reference.

func ReadAgentReference

func ReadAgentReference(ctx context.Context, db *sql.Conn, node protocol.NodeID, source AgentHistorySource, kind string, arguments json.RawMessage) (json.RawMessage, error)

func ReadAgentRun

func ReadAgentRun(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (protocol.ConversationRun, error)

func ReadAgentStatistics

func ReadAgentStatistics(ctx context.Context, db *sql.Conn, session protocol.SessionID) (protocol.ConversationStatistics, error)

ReadAgentStatistics derives session totals from canonical turn membership. The caller's transaction keeps usage, observation and policy reads consistent.

func ReadArtifactCommand

func ReadArtifactCommand(ctx context.Context, db *sql.Conn, request protocol.Request) (protocol.Output, error)

func ReadAssistantDeclaration

ReadAssistantDeclaration returns the declaration in an exact package capture.

func ReadAttachment

func ReadAttachment(ctx context.Context, db *sql.Conn, worktree protocol.WorktreeID, id protocol.AttachmentID) (protocol.Attachment, error)

func ReadBackgroundTasks

func ReadBackgroundTasks(ctx context.Context, db *sql.Conn, session protocol.SessionID) ([]protocol.ConversationBackgroundTask, error)

func ReadBackupSettings

func ReadBackupSettings(ctx context.Context, db *sql.Conn) (protocol.BackupSettings, error)

ReadBackupSettings returns the settings without any credential value.

func ReadCanonicalImage

func ReadCanonicalImage(ctx context.Context, db *sql.Conn, session protocol.SessionID, image protocol.ConversationImage) ([]byte, error)

func ReadChildRole

func ReadChildRole(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (*protocol.RoleProfile, error)

func ReadComputerSettings

func ReadComputerSettings(ctx context.Context, db *sql.Conn) (protocol.ComputerSettings, error)

ReadComputerSettings returns the machine-wide Computer Use setting stored under the local Node owner row in user_personal_settings (avoiding a new singleton table while sharing one setting across all machine administrators and agent turns).

func ReadConfigurationCache

func ReadConfigurationCache(ctx context.Context, db *sql.Conn, category, id string) (json.RawMessage, bool, error)

func ReadConfigurationFollow

func ReadConfigurationFollow(ctx context.Context, db *sql.Conn) (protocol.ConfigurationFollowStatus, error)

func ReadConnectorPlugin

func ReadConnectorPlugin(ctx context.Context, db *sql.Conn, name string) (*protocol.PluginInfo, error)

ReadConnectorPlugin resolves a connector's owning plugin info, preferring any installed package and falling back to built-in Harness connectors.

func ReadConversation

func ReadConversation(ctx context.Context, db *sql.Conn, session protocol.SessionID, before *protocol.TurnID, limit uint16) (protocol.ConversationHistory, error)

func ReadConversationChild added in v0.2.5

func ReadConversationChild(ctx context.Context, db *sql.Conn, parent protocol.SessionID, turn protocol.TurnID) (protocol.ConversationChild, bool, error)

ReadConversationChild reads one delegated run whose origin still belongs to the parent, even when the call does not fit on its newest history page.

func ReadConversationSnapshot added in v0.2.7

func ReadConversationSnapshot(ctx context.Context, db *sql.Conn, session protocol.SessionID, limit uint16, drafts []protocol.ConversationDraft) (protocol.ConversationSnapshot, error)

ReadConversationSnapshot fits the history and the enclosing subscription on the same snapshot. The second fit uses the sizes of the entries it kept.

func ReadConversationTurn

func ReadConversationTurn(ctx context.Context, db *sql.Conn, session protocol.SessionID, turn protocol.TurnID, revision uint64, before *uint64, limit uint16) (protocol.ConversationTurnHistory, error)

func ReadDatabase

func ReadDatabase(ctx context.Context, db *sql.Conn, id protocol.DatabaseID) (*protocol.DatabaseProfile, error)

ReadDatabase returns nil when the profile is not saved on this Node.

func ReadDefaults

func ReadDefaults(ctx context.Context, db *sql.Conn) (protocol.Defaults, error)

func ReadDelegatedTools

func ReadDelegatedTools(ctx context.Context, db *sql.Conn, session protocol.SessionID) ([]byte, error)

ReadDelegatedTools loads the persisted inherited tool boundary for session.

func ReadDispatchJob

func ReadDispatchJob(ctx context.Context, db *sql.Conn, packageName string, id protocol.JobID) (protocol.DispatchJob, error)

ReadDispatchJob returns one stored dispatch job (including native module wake jobs) by ID in packageName.

func ReadDispatchTurn

func ReadDispatchTurn(ctx context.Context, db *sql.Conn, node protocol.NodeID, packageName string, identity protocol.JobID) (protocol.TurnID, error)

func ReadDraftAttachment

func ReadDraftAttachment(ctx context.Context, db *sql.Conn, caller protocol.NodeID, id protocol.AttachmentID) (protocol.Attachment, error)

func ReadExternalBrowserSettings

func ReadExternalBrowserSettings(ctx context.Context, db *sql.Conn) (protocol.ExternalBrowserSettings, error)

func ReadFilesCommand

func ReadFilesCommand(ctx context.Context, db *sql.Conn, caller protocol.NodeID, request protocol.Request) (protocol.Output, error)

func ReadHooks

func ReadHooks(ctx context.Context, db *sql.Conn) (protocol.HooksSettings, error)

func ReadIdentity

func ReadIdentity(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID) (protocol.IdentityState, error)

func ReadIdentityCommand

func ReadIdentityCommand(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, command protocol.Command) (protocol.Output, error)

func ReadIdentityDirectory

func ReadIdentityDirectory(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID) (protocol.HostDirectory, error)

func ReadLocalModelSettings

func ReadLocalModelSettings(ctx context.Context, db *sql.Conn) (protocol.ModelsLocalSettings, error)

ReadLocalModelSettings reads the saved choices and mirror.

func ReadMediaSettings

func ReadMediaSettings(ctx context.Context, db *sql.Conn) (protocol.MediaSettings, error)

ReadMediaSettings returns the saved bindings and names every bound purpose whose model cannot run now.

func ReadMemoryRevision

func ReadMemoryRevision(ctx context.Context, db *sql.Conn) (uint64, error)

ReadMemoryRevision returns the highest stored revision across the current user's native memory catalog and settings rows so Snapshots detect offline memory mutations across reconnects.

func ReadModuleTurnLimit

func ReadModuleTurnLimit(ctx context.Context, db *sql.Conn) (int, error)

ReadModuleTurnLimit returns the per-module daily turn limit stored under the local user in user_personal_settings, falling back to DefaultModuleDailyTurnLimit.

func ReadNetworkSelection

func ReadNetworkSelection(ctx context.Context, db *sql.Conn) (uint64, *protocol.NetworkSelection, error)

func ReadNotifications

func ReadNotifications(ctx context.Context, db *sql.Conn) ([]protocol.NotificationNotice, error)

func ReadPlugin

func ReadPlugin(ctx context.Context, db *sql.Conn, name string) (*protocol.PluginInfo, error)

func ReadPluginCommand

func ReadPluginCommand(ctx context.Context, db *sql.Conn, request protocol.Request) (protocol.Output, error)

func ReadPluginConnection

func ReadPluginConnection(ctx context.Context, db *sql.Conn, profile string, reference protocol.PluginReference, card string) (protocol.PluginConnectionStatus, error)

func ReadPluginConnectionAdmitted

func ReadPluginConnectionAdmitted(ctx context.Context, db *sql.Conn, profile string, info protocol.PluginInfo, card string) (protocol.PluginConnectionStatus, error)

func ReadPluginInfos

func ReadPluginInfos(ctx context.Context, db *sql.Conn) ([]protocol.PluginInfo, error)

func ReadPluginSettings

func ReadPluginSettings(ctx context.Context, db *sql.Conn, reference protocol.PluginReference, targets ...map[string]string) (protocol.PluginSettingsState, error)

func ReadPluginStatusPackages

func ReadPluginStatusPackages(ctx context.Context, db *sql.Conn, scope protocol.PluginUiStatusScope) ([]protocol.PluginInfo, error)

func ReadPluginValue

func ReadPluginValue(ctx context.Context, db *sql.Conn, reference protocol.PluginReference, key string) (protocol.PluginStorageEntry, error)

func ReadPluginVersion

func ReadPluginVersion(ctx context.Context, db *sql.Conn, reference protocol.PluginReference) (protocol.PluginInfo, error)

ReadPluginVersion reads an immutable package capture independently of its live installation. It never creates inventory or substitutes a newer package.

func ReadPlugins

func ReadPlugins(ctx context.Context, db *sql.Conn) ([]protocol.PluginSummary, error)

func ReadPower

func ReadPower(ctx context.Context, db *sql.Conn) (protocol.PowerSettings, error)

func ReadProjectTask

func ReadProjectTask(ctx context.Context, db *sql.Conn, source protocol.SessionID, current protocol.TurnID, target protocol.SessionID) (protocol.ProjectTaskProgress, error)

func ReadProjectTaskWork

func ReadProjectTaskWork(ctx context.Context, db *sql.Conn, source protocol.SessionID, current protocol.TurnID, input protocol.ReadProjectTaskInput) (any, error)

ReadProjectTaskWork is the stable-ID view of work created by this discussion.

func ReadProjects

func ReadProjects(ctx context.Context, db *sql.Conn) ([]protocol.Project, error)

func ReadProviderAuthorization

func ReadProviderAuthorization(ctx context.Context, db *sql.Conn, node protocol.NodeID, provider protocol.ConversationProvider, reference protocol.CredentialRef) (*protocol.Secret, error)

func ReadProviderCatalogStatus

func ReadProviderCatalogStatus(ctx context.Context, db *sql.Conn) (protocol.ConversationCatalogStatus, error)

func ReadProviderCommand

func ReadProviderCommand(ctx context.Context, db *sql.Conn, node protocol.NodeID, command protocol.Command) (protocol.Output, error)

func ReadProviderSnapshot

ReadProviderSnapshot exposes only the current user's providers. Authentication material is absent from both returned public projections.

func ReadPythonSettings

func ReadPythonSettings(ctx context.Context, db *sql.Conn) (protocol.PythonSettings, error)

func ReadQueue

func ReadQueue(ctx context.Context, db *sql.Conn, session protocol.SessionID) (protocol.ConversationQueue, error)

func ReadResourceCatalogSources

func ReadResourceCatalogSources(ctx context.Context, db *sql.Conn, entry protocol.NodeID) ([]protocol.ResourceSource, error)

Resource catalogs are projections of the current user's authenticated direct routes. They deliberately cannot store a full Snapshot, credentials, session history, file content or knowledge indexes.

func ReadRoleContextWindow

func ReadRoleContextWindow(ctx context.Context, db *sql.Conn, roleRef protocol.RoleReference) (uint32, error)

ReadRoleContextWindow resolves the effective context window (in tokens) for a role's configured model, falling back to the node's default model. Returns 0 when unknown.

func ReadRoleSkill

func ReadRoleSkill(ctx context.Context, db *sql.Conn, roleID protocol.RoleID, skillID string) (*protocol.RoleSkill, error)

ReadRoleSkill returns a single private skill belonging strictly to roleID.

func ReadRoleSkillSummaries

func ReadRoleSkillSummaries(ctx context.Context, db *sql.Conn, roleIDs []protocol.RoleID) (map[protocol.RoleID][]protocol.RoleSkillSummary, error)

ReadRoleSkillSummaries loads lightweight private skill summaries for a batch of roles in one SQL query, sorted deterministically by skill_id.

func ReadRoleSkills

func ReadRoleSkills(ctx context.Context, db *sql.Conn, roleID protocol.RoleID) ([]protocol.RoleSkill, error)

ReadRoleSkills returns all private skills belonging to roleID in deterministic skill_id order.

func ReadRoles

func ReadRoles(ctx context.Context, db *sql.Conn) ([]protocol.RoleProfile, error)

func ReadRuntimeProviderCredential

func ReadRuntimeProviderCredential(ctx context.Context, db *sql.Conn, node protocol.NodeID, provider protocol.ConversationProvider, reference protocol.CredentialRef) (*protocol.Secret, error)

func ReadSandboxSettings

func ReadSandboxSettings(ctx context.Context, db *sql.Conn) (protocol.SandboxSettings, error)

func ReadSchemaObjects

func ReadSchemaObjects(ctx context.Context, connection *sql.Conn) (map[SchemaObject]string, error)

func ReadSearchSettings

func ReadSearchSettings(ctx context.Context, db *sql.Conn) (protocol.SearchSettings, error)

func ReadSession

func ReadSession(ctx context.Context, db *sql.Conn, id protocol.SessionID) (protocol.Session, error)

func ReadSessions

func ReadSessions(ctx context.Context, db *sql.Conn) ([]protocol.Session, error)

func ReadStandingApprovalsRevision

func ReadStandingApprovalsRevision(ctx context.Context, db *sql.Conn) (uint64, error)

ReadStandingApprovalsRevision returns a monotonic revision counter for the current user's standing approvals. It advances on every create, consume, and revocation.

func ReadSuggestionSettings

func ReadSuggestionSettings(ctx context.Context, db *sql.Conn) (protocol.ConversationSuggestionSettings, error)

ReadSuggestionSettings returns the current user's follow-up suggestion settings. Suggestions are on until the user saves otherwise.

func ReadSyncTargets

func ReadSyncTargets(ctx context.Context, db *sql.Conn, user protocol.UserID) ([]protocol.ConfigurationFollowTarget, error)

ReadSyncTargets returns reports belonging to the selected desktop user.

func ReadTeam

func ReadTeam(ctx context.Context, db *sql.Conn, id protocol.TeamID) (*protocol.TeamProfile, error)

func ReadTeamCommand

func ReadTeamCommand(ctx context.Context, db *sql.Conn, command protocol.Command) (protocol.Output, error)

func ReadTeamSettings

func ReadTeamSettings(ctx context.Context, db *sql.Conn) (protocol.TeamSettings, error)

func ReadTeams

func ReadTeams(ctx context.Context, db *sql.Conn) ([]protocol.TeamProfile, error)

func ReadTelemetry

func ReadTelemetry(ctx context.Context, db *sql.Conn) (protocol.TelemetrySettings, error)

func ReadTerminal

func ReadTerminal(ctx context.Context, db *sql.Conn, id protocol.TerminalID) (protocol.TerminalInfo, error)

func ReadTerminalSettings

func ReadTerminalSettings(ctx context.Context, db *sql.Conn) (protocol.TerminalSettings, error)

func ReadTerminals

func ReadTerminals(ctx context.Context, db *sql.Conn) ([]protocol.TerminalInfo, error)

func ReadTurnReply

func ReadTurnReply(ctx context.Context, db *sql.Conn, session protocol.SessionID, turn protocol.TurnID) (string, error)

ReadTurnReply returns the last visible assistant text from the originating turn, even when newer group messages have moved it off the live history page.

func ReadWebSearchPlan

func ReadWebSearchPlan(ctx context.Context, db *sql.Conn) (web.SearchPlan, error)

ReadWebSearchPlan copies private credentials into a Node-owned execution capture. The caller binds the frozen model callback before leaving its admission owner.

func ReadWorkspaceRoot

func ReadWorkspaceRoot(ctx context.Context, db *sql.Conn, worktree protocol.WorktreeID, internal bool) (string, error)

ReadWorkspaceRoot captures database ownership only. Filesystem work follows after the caller closes its read lease.

func ReadWorktrees

func ReadWorktrees(ctx context.Context, db *sql.Conn) ([]protocol.Worktree, error)

func ReconcileProviderQuotas

func ReconcileProviderQuotas(ctx context.Context, db *sql.Conn, node protocol.NodeID) ([]protocol.Event, error)

func RecordBackupOutcome

func RecordBackupOutcome(ctx context.Context, db *sql.Conn, outcome protocol.BackupOutcome) error

RecordBackupOutcome keeps how the most recent backup ended, for the Backup page. It is not a settings change: the revision stays.

func RecordConnectionSave

func RecordConnectionSave(ctx context.Context, db *sql.Conn, request protocol.Request) error

RecordConnectionSave keeps an authorized turn's save without its secret. Call it after authorization in the save's writer transaction, so a failed save rolls back its proof. Controller saves have no turn proof to record. The request ledger holds only the digest; ConnectionCreated reads this row.

func RecordEvents

func RecordEvents(ctx context.Context, db *sql.Conn, node protocol.NodeID, changes []protocol.Event) ([]protocol.EventEnvelope, error)

func RecordHostRemoval

func RecordHostRemoval(ctx context.Context, db *sql.Conn, host protocol.NodeID, request protocol.RequestID, state string, failure *protocol.Fault) error

func RecordKnowledgeProgress

func RecordKnowledgeProgress(ctx context.Context, db *sql.Conn, id protocol.KnowledgeID, generation uint64, progress protocol.KnowledgeProgress) (bool, error)

RecordKnowledgeProgress stores the worker's progress for the generation it indexed. It reports whether the collection changed.

func RecordPluginStatusDiagnostic

func RecordPluginStatusDiagnostic(ctx context.Context, db *sql.Conn, report protocol.NotificationSystemSystemDiagnostic, timestamp int64) ([]protocol.Event, error)

func RecordedPluginNames

func RecordedPluginNames(ctx context.Context, db *sql.Conn) (map[string]bool, error)

func RecoverCommands

func RecoverCommands(ctx context.Context, db *sql.Conn, now time.Time) ([]protocol.Event, error)

func RecoverConnectorLogins

func RecoverConnectorLogins(ctx context.Context, db *sql.Conn) error

func RecoverCredentialRenewals

func RecoverCredentialRenewals(ctx context.Context, db *sql.Conn, node protocol.NodeID) error

RecoverCredentialRenewals never repeats an exchange whose response may have been lost. Its access token remains usable until expiry; explicit sign-in is needed afterward. Publish a new revision for the changed execution state.

func RecoverRuns

func RecoverRuns(ctx context.Context, db *sql.Conn, now time.Time) ([]protocol.Event, error)

func RecoverTerminals

func RecoverTerminals(ctx context.Context, db *sql.Conn) error

func RefreshEventAccess

func RefreshEventAccess(ctx context.Context, db *sql.Conn, event protocol.EventEnvelope) (protocol.EventEnvelope, error)

RefreshEventAccess reads the canonical row by cursor and filters it for the current recipient.

func RefreshTurnRoles

func RefreshTurnRoles(ctx context.Context, db *sql.Conn, node protocol.NodeID, snapshot *protocol.RoleSnapshot) error

func RegisterChildBackground

func RegisterChildBackground(ctx context.Context, db *sql.Conn, parent, child protocol.ConversationRun, title string, now time.Time) ([]protocol.Event, error)

func RegisterCommand

func RegisterCommand(ctx context.Context, db *sql.Conn, request protocol.Request, now time.Time) ([]protocol.Event, error)

func RegisterCreatedWorktree

func RegisterCreatedWorktree(ctx context.Context, db *sql.Conn, value protocol.Worktree, adopt bool) (protocol.Worktree, []protocol.Event, error)

RegisterCreatedWorktree commits a verified external checkout. No filesystem action or native Git command runs on the storage writer.

func RegisterKnowledgeSemantic

func RegisterKnowledgeSemantic(ctx context.Context, db *sql.Conn) (bool, error)

RegisterKnowledgeSemantic registers the semantic collections of every enabled package. It runs when the Node starts and after a package changes.

func RegisterLocalModel

func RegisterLocalModel(ctx context.Context, db *sql.Conn, capabilities localmodels.Capabilities, definition protocol.ModelsDefinition) (protocol.Output, []protocol.Event, error)

RegisterLocalModel stores a validated definition under its content identity and returns that identity. Registering a known definition changes nothing.

func RegisterPromotedCommand

func RegisterPromotedCommand(ctx context.Context, db *sql.Conn, request protocol.Request, now time.Time) ([]protocol.Event, error)

func ReleaseBackground

func ReleaseBackground(ctx context.Context, db *sql.Conn, turn protocol.TurnID, hold *protocol.ConversationBackgroundHold, suppress bool) ([]protocol.Event, error)

ReleaseBackground returns the results reserved for a turn that did not take them. The hold is why the turn did not. With suppress they are suppressed: they start no notice turn and join the user's next message, and the hold tells clients why. Without it only the results that were already suppressed take the hold, so none is left held without a reason.

func ReleaseChildren

func ReleaseChildren(ctx context.Context, db *sql.Conn, parent protocol.TurnID, children []protocol.TurnID) ([]protocol.Event, error)

func RelocateProfile

func RelocateProfile(ctx context.Context, db *sql.Conn, original, target string) error

RelocateProfile rewrites the stored paths that point into the profile at original so they point into target, for a profile that is about to move.

func RememberIdentityPeerName

func RememberIdentityPeerName(ctx context.Context, db *sql.Conn, peer protocol.NodeID, name string) error

func RememberLinkPeer

func RememberLinkPeer(ctx context.Context, db *sql.Conn, address link.EndpointAddress) error

func RemoveNativeWakeSchedule

func RemoveNativeWakeSchedule(ctx context.Context, db *sql.Conn, namespace, key string, expectedRevision uint64) ([]protocol.Event, error)

RemoveNativeWakeSchedule deletes one module-owned wake schedule when its revision matches expectedRevision.

func RemovePlugin

func RemovePlugin(ctx context.Context, db *sql.Conn, name string, expectedRevision uint64) (protocol.PluginSummary, error)

func RemovePluginValue

func RemovePluginValue(ctx context.Context, db *sql.Conn, reference protocol.PluginReference, key string, expectedRevision uint64) (protocol.PluginStorageEntry, error)

func RemoveResourceCatalogSource

func RemoveResourceCatalogSource(ctx context.Context, db *sql.Conn, source protocol.NodeID) error

func RemovedArtifactOwners

func RemovedArtifactOwners(ctx context.Context, db *sql.Conn) ([]protocol.SessionID, error)

RemovedArtifactOwners lists the removed sessions that keep no artifact; their artifact directories hold nothing a conversation can read.

func ReplaceRoleSkills

func ReplaceRoleSkills(ctx context.Context, db *sql.Conn, roleID protocol.RoleID, skills []protocol.RoleSkill, now time.Time) error

ReplaceRoleSkills replaces every private skill of roleID atomically within the caller's active write transaction.

func ReplaceWriterConnectionForTesting

func ReplaceWriterConnectionForTesting(ctx context.Context, handle *Handle, connection *sql.Conn) (func() error, error)

func ReportProjectTaskWork

func ReportProjectTaskWork(ctx context.Context, db *sql.Conn, session protocol.SessionID, turn protocol.TurnID, input protocol.ReportProjectTaskInput, commit string, now time.Time) (*protocol.ProjectTaskWork, []protocol.Event, error)

ReportProjectTaskWork accepts a report only from an active task turn of the exact dispatched session in the selected worktree. The model cannot supply a task ID, nor can a normal turn completion call this state transition.

func ResolveApproval

ResolveApproval applies an approval decision inside a write transaction.

func ResolveBotCatalogLocale

func ResolveBotCatalogLocale(locales map[string]protocol.BotCatalogLocale, preferred string) protocol.BotCatalogLocale

ResolveBotCatalogLocale selects the best localized copy for a Bot catalog entry.

func ResolveMediaBinding

func ResolveMediaBinding(ctx context.Context, db *sql.Conn, node protocol.NodeID, provider protocol.ConversationProvider, name string, session protocol.SessionID) (model.Binding, error)

ResolveMediaBinding binds a captured API-key provider to its current key.

func ResolveMentionedTaskProject

func ResolveMentionedTaskProject(input *protocol.StartProjectTaskInput, refs []protocol.ConversationReference) error

ResolveMentionedTaskProject preserves the user's selected route throughout tool preparation and approval, even if the model supplies only a project ID.

func ResolveModuleNotification

func ResolveModuleNotification(ctx context.Context, db *sql.Conn, moduleID, key string) ([]protocol.Event, error)

ResolveModuleNotification removes any durable notification matching (localUser, moduleID, key) and returns notifications_dismissed when any were deleted. Resolving a missing key is a no-op.

func ResolvePluginInfo

func ResolvePluginInfo(ctx context.Context, db *sql.Conn, reference protocol.PluginReference) (protocol.PluginInfo, error)

func ResolvePluginMessageCommand

func ResolvePluginMessageCommand(ctx context.Context, db *sql.Conn, node protocol.NodeID, request protocol.Request) (*protocol.Request, error)

func ResolvePluginViewInfo

func ResolvePluginViewInfo(ctx context.Context, db *sql.Conn, reference protocol.PluginReference, surface protocol.PluginDesktopSurface) (protocol.PluginInfo, error)

func ResolveRoleSkillLocale

func ResolveRoleSkillLocale(skill protocol.RoleSkill, preferred string) protocol.RoleSkill

ResolveRoleSkillLocale selects the localized name, description, and SKILL.md content for a Bot-private skill, falling back cleanly to the canonical fields.

func ResolveSearchBinding

func ResolveSearchBinding(ctx context.Context, db *sql.Conn, node protocol.NodeID, provider protocol.ConversationProvider, name string, session protocol.SessionID) (model.Binding, error)

func ResolveToolCommandStream

ResolveToolCommandStream verifies the current invocation and exact visible canonical result. The Node pages the existing Process owner after this read.

func ResolveTurnAttachment

func ResolveTurnAttachment(ctx context.Context, db *sql.Conn, turn protocol.TurnID, id protocol.AttachmentID) (protocol.Attachment, error)

func ResolveUser

func ResolveUser(ctx context.Context, db *sql.Conn, id protocol.UserID) (protocol.User, error)

ResolveUser follows only stored merge relationships; request bodies cannot supply a principal or select another user's resource namespace.

func RestorePluginConversation

func RestorePluginConversation(ctx context.Context, db *sql.Conn, session protocol.SessionID) error

func RetainedAttachments

func RetainedAttachments(ctx context.Context, db *sql.Conn) (map[protocol.AttachmentID]bool, error)

func RetireImportedPeerRoutes

func RetireImportedPeerRoutes(ctx context.Context, db *sql.Conn) error

RetireImportedPeerRoutes removes only outbound access inherited from an old directory. Explicit pairing directions and provenance records remain intact.

func RetryChildTurn

func RetryChildTurn(ctx context.Context, db *sql.Conn, node protocol.NodeID, caller protocol.NodeID, request protocol.Request, targetTurn protocol.TurnID, now time.Time) (protocol.Output, []protocol.Event, error)

RetryChildTurn admits a recovery turn on a delegated child session whose latest turn ended failed or interrupted. It preserves the child's frozen permissions, role, worktree, and inherited tool boundary, unpauses the child queue, and schedules background delivery of the completed result to the parent.

func RevokeIdentityDevice

func RevokeIdentityDevice(ctx context.Context, db *sql.Conn, node, caller protocol.NodeID, input protocol.RevokeDevice) error

func RevokeStandingApproval

func RevokeStandingApproval(ctx context.Context, db *sql.Conn, id protocol.StandingApprovalID, expectedRevision uint64, now time.Time) (protocol.StandingApproval, []protocol.Event, error)

RevokeStandingApproval immediately revokes an active standing approval grant, requiring a matching expected revision.

func RewindPluginConversation

func RewindPluginConversation(ctx context.Context, db *sql.Conn, session protocol.SessionID, through *protocol.TurnID) error

func RoutedFollowUpTurn

func RoutedFollowUpTurn(run protocol.ConversationRun) bool

An origin is only an isolation marker. The immutable request, local task and pairing authorize the turn.

func RoutedTaskDelivery

func RoutedTaskDelivery(ctx context.Context, db *sql.Conn, node protocol.NodeID, task protocol.RequestID, revision uint64) (protocol.ProjectTaskWork, error)

RoutedTaskDelivery resolves a local owner's receipt to the paired executor and session. Older revisions may be presented for exact admission replay.

func RoutedTaskSession

func RoutedTaskSession(ctx context.Context, db *sql.Conn, node protocol.NodeID, task protocol.RequestID, session protocol.SessionID) (protocol.NodeID, error)

RoutedTaskSession resolves the saved execution session on its current pairing. A stop request ends execution without removing the owner's access to history.

func RunningSessionTurns

func RunningSessionTurns(ctx context.Context, db *sql.Conn, session protocol.SessionID) ([]protocol.TurnID, error)

RunningSessionTurns lists the session's turns that are running.

func RuntimeCredentialEvent

func RuntimeCredentialEvent(event string) bool

func SameKnowledgeStored

func SameKnowledgeStored(left, right KnowledgeStored) bool

SameKnowledgeStored compares the identity an indexing pass or a citation read captured with the current collection.

func SaveBackupSettings

func SaveBackupSettings(ctx context.Context, db *sql.Conn, input protocol.BackupUpdate, timestamp int64) (protocol.BackupSettings, []protocol.Event, error)

SaveBackupSettings stores the destinations, credentials and schedule, and registers the Node's own scheduled export.

func SaveConfigurationSyncState

func SaveConfigurationSyncState(ctx context.Context, db *sql.Conn, p ConfigurationSyncPeer) error

func SaveDefaults

func SaveDefaults(ctx context.Context, db *sql.Conn, node protocol.NodeID, input protocol.Defaults) (protocol.Defaults, error)

SaveDefaults replaces only the active user's default session configuration.

func SaveDelegatedTools

func SaveDelegatedTools(ctx context.Context, db *sql.Conn, session protocol.SessionID, body []byte) error

SaveDelegatedTools persists a child session's inherited parent tool boundary so a failed child turn can be retried safely without enlarging its permissions.

func SaveHooks

func SaveHooks(ctx context.Context, db *sql.Conn, input protocol.HooksSettings, expected uint64) (protocol.HooksSettings, error)

func SaveLocalModelSettings

func SaveLocalModelSettings(ctx context.Context, db *sql.Conn, settings protocol.ModelsLocalSettings) (protocol.Output, []protocol.Event, error)

SaveLocalModelSettings replaces the settings at their expected revision. Every selected model must be registered for its kind.

func SaveModuleTurnLimit

func SaveModuleTurnLimit(ctx context.Context, db *sql.Conn, limit int) error

SaveModuleTurnLimit persists the per-module daily turn limit for the local user.

func SaveNetworkSelection

func SaveNetworkSelection(ctx context.Context, db *sql.Conn, expected uint64, selection protocol.NetworkSelection) (uint64, error)

func SaveOAuthRegistration

func SaveOAuthRegistration(ctx context.Context, db *sql.Conn, key, client string) error

func SavePythonSettings

func SavePythonSettings(ctx context.Context, db *sql.Conn, input protocol.PythonSettings) (protocol.Output, []protocol.Event, error)

func SaveResourceCatalogSource

func SaveResourceCatalogSource(ctx context.Context, db *sql.Conn, entry protocol.NodeID, source protocol.ResourceSource) error

SaveResourceCatalogSource publishes a complete directory version. Callers retain the previous version while snapshot pages are incomplete or a source is temporarily unavailable; absence means deletion only in a complete read.

func SaveRoutedWork

Keep the desktop's recipient references and the executor's receipt and last report. An old or repeated report cannot replace a newer acknowledgement.

func SaveSandboxSettings

func SaveSandboxSettings(ctx context.Context, db *sql.Conn, input protocol.SandboxSettings) (protocol.SandboxSettings, error)

func SaveSearchSettings

func SaveSearchSettings(ctx context.Context, db *sql.Conn, request protocol.Request, update protocol.SearchUpdate) (protocol.Output, []protocol.Event, error)

func SaveTerminal

func SaveTerminal(ctx context.Context, db *sql.Conn, value protocol.TerminalInfo, event bool) ([]protocol.Event, error)

func SaveTerminalSettings

func SaveTerminalSettings(ctx context.Context, db *sql.Conn, input protocol.TerminalSettings) (protocol.TerminalSettings, []protocol.Event, error)

SaveTerminalSettings stores the default shell and environment of new terminals. The shell is resolved on this Node, so it must be absolute here.

func SaveTurnSuggestions

func SaveTurnSuggestions(ctx context.Context, db *sql.Conn, turn protocol.TurnID, suggestions []string) (protocol.ConversationRun, bool, error)

SaveTurnSuggestions records follow-up prompts on a completed task turn that is still the latest run of an active session: guidance it joined does not count as later. ok is false, and nothing is written, otherwise.

func ScheduleBackground

func ScheduleBackground(ctx context.Context, db *sql.Conn, node protocol.NodeID, session protocol.SessionID, now time.Time) (*protocol.QueuedTurn, []protocol.Event, error)

func SearchSettingsController

func SearchSettingsController(request protocol.Request) bool

func SeedDemoProjectTaskWork

func SeedDemoProjectTaskWork(ctx context.Context, db *sql.Conn, spec DemoTaskWork) (protocol.ProjectTaskWork, error)

SeedDemoProjectTaskWork persists a synthetic ProjectTaskWork record in SQLite for an isolated demo profile so Node work queries match seeded Kanban cards.

func SeedDemoSession

func SeedDemoSession(ctx context.Context, db *sql.Conn, nodeID protocol.NodeID, profile string, spec DemoSession) (protocol.Session, protocol.TurnID, error)

SeedDemoSession inserts a real persisted session and completed synthetic turns into db using canonical tables so Desktop renders them natively.

func SelectSessionRoles

func SelectSessionRoles(ctx context.Context, db *sql.Conn, node protocol.NodeID, previous protocol.RoleSnapshot, references []protocol.RoleReference) (protocol.RoleSnapshot, error)

func SetIdentityPeerDirection

func SetIdentityPeerDirection(ctx context.Context, db *sql.Conn, peer protocol.NodeID, direction link.PeerDirection) error

func SetLinkDirection

func SetLinkDirection(ctx context.Context, db *sql.Conn, peer protocol.NodeID, direction link.PeerDirection) error

func SetLinkTrust

func SetLinkTrust(ctx context.Context, db *sql.Conn, peer protocol.NodeID, trusted bool) error

func SetPluginEnabled

func SetPluginEnabled(ctx context.Context, db *sql.Conn, name string, expectedRevision uint64, enabled bool) (protocol.PluginInfo, error)

func SetPluginPinned

func SetPluginPinned(ctx context.Context, db *sql.Conn, name string, expectedRevision uint64, pinned bool) (protocol.PluginInfo, error)

func SetRunCredentialWait

func SetRunCredentialWait(ctx context.Context, db *sql.Conn, node protocol.NodeID, turn protocol.TurnID, waiting *protocol.ConversationRunWaiting) ([]protocol.Event, error)

SetRunCredentialWait changes only the running turn's projection; its capture, canonical records and already completed effects remain untouched.

func SettleStoppedChildren

func SettleStoppedChildren(ctx context.Context, db *sql.Conn, now time.Time) ([]protocol.Event, error)

SettleStoppedChildren finishes the queued children a controller stopped. stop_turn leaves such a run cancelled without a finish time; finishing it here closes its completion record and refreshes its parent. The store is the source, so a stopped child is settled whether or not the Runtime still holds its owner.

func Snapshot

func Snapshot(ctx context.Context, db *sql.Conn, node protocol.NodeID) (protocol.Snapshot, error)

Snapshot reads all fields from the caller's pinned read transaction.

func StallCommand

func StallCommand(ctx context.Context, db *sql.Conn, stalled process.Stalled, now time.Time) ([]protocol.Event, bool, error)

StallCommand records at most one silent period for a follow-up command. The command itself stays running until it finishes.

func StartConnectorLogin

func StartConnectorLogin(ctx context.Context, db *sql.Conn, capture ConnectorLoginCapture) error

func StartModuleSession

func StartModuleSession(ctx context.Context, db *sql.Conn, node protocol.NodeID, profile string, moduleID string, draft protocol.ConversationStart, idempotencyKey string, now time.Time) (protocol.SessionID, []protocol.Event, error)

StartModuleSession creates a session on a native module's behalf under the local user's authority. Empty messages create the session without admitting a turn; non-empty messages admit the first turn through the normal path.

func StartProjectTask

StartProjectTask admits a normal project conversation and its first turn in the caller's write transaction. The claimed approval supplies the request ID.

func StartProjectTaskBound

func StartProjectTaskBound(ctx context.Context, db *sql.Conn, node protocol.NodeID, profile string, source protocol.SessionID, parent protocol.TurnID, approval protocol.ApprovalID, requestID protocol.RequestID, input protocol.StartProjectTaskInput, resolveBound func() (protocol.RequestID, error)) (protocol.ProjectTaskProgress, []protocol.Event, error)

StartProjectTaskBound is StartProjectTask with an optional board resolver invoked only for newly admitted starts (never on idempotent admission replays) to validate a board card and supply any already-reserved work ID.

func StartSessionProvider

func StartSessionProvider(ctx context.Context, db *sql.Conn, draft protocol.ConversationStart) (protocol.ProviderID, error)

func StopChild added in v0.2.4

StopChild stops the current execution of a child the parent turn's conversation owns, on the same path as a controller's stop_turn: the request is recorded for stop_reason. A child that is not queued or running is returned unchanged.

func StopSessionRemoval

func StopSessionRemoval(ctx context.Context, db *sql.Conn, command protocol.Command, now time.Time) ([]protocol.ConversationRun, []protocol.Event, error)

StopSessionRemoval validates a session removal and stops its running turns on the same path as stop_turn. It returns the turns it stopped, which the caller hands to the runtime after the commit. A stale or invalid removal stops nothing.

func SuggestionBinding

func SuggestionBinding(ctx context.Context, db *sql.Conn, node protocol.NodeID, choice protocol.ConversationSuggestionModel, session protocol.SessionID) (binding model.Binding, ok bool, err error)

SuggestionBinding binds the configured suggestion model to its current credential. ok is false when that model can no longer run.

func SupportsAgentCommand

func SupportsAgentCommand(kind string) bool

func SupportsFilesCommand

func SupportsFilesCommand(kind string) bool

func SupportsProviderCommand

func SupportsProviderCommand(kind string) bool

func SupportsTeamCommand

func SupportsTeamCommand(kind string) bool

func SupportsTeamRead

func SupportsTeamRead(kind string) bool

func SwitchModuleSessionBot

func SwitchModuleSessionBot(ctx context.Context, db *sql.Conn, node protocol.NodeID, moduleID string, req SessionBotSwitch) (protocol.Session, []protocol.Event, error)

SwitchModuleSessionBot switches an idle session's active Bot role in-place, upgrading mode from plan to a writable mode when moving to a writable role, and optionally switching the session's worktree within the same project.

func TaskInputProvider

func TaskInputProvider(ctx context.Context, db *sql.Conn, session protocol.Session, input protocol.ConversationInput) (protocol.ProviderID, error)

TaskInputProvider resolves the recipient's provider for native command login preflight. Turn admission rechecks the recipient against the same catalogue.

func TaskRouteOwnerKeys

func TaskRouteOwnerKeys(ctx context.Context, db *sql.Conn, input protocol.StartProjectTaskInput) (role, team, group string, err error)

func TaskWorktreeRegistrationEvents

func TaskWorktreeRegistrationEvents(ctx context.Context, id protocol.WorktreeID, changes []protocol.Event) []protocol.Event

func TryConsumeStandingApproval

func TryConsumeStandingApproval(ctx context.Context, db *sql.Conn, value protocol.ConversationApproval, binding *ApprovalBinding, now time.Time) (protocol.ConversationApproval, []protocol.Event, bool, error)

TryConsumeStandingApproval attempts to satisfy a Pending approval using an active user-created standing approval grant inside the caller's active SQLite write transaction. Standing approvals are opt-in per tool invocation: the binding must set AllowStandingApproval to true. If AllowStandingApproval is false, the turn is ineligible (WorkModePlan, non-local user, plugin tool, missing module/operation, SSH trust), or no active grant matches, it leaves value untouched (Pending) and returns matched=false.

func TurnIsPlanMode

func TurnIsPlanMode(ctx context.Context, db *sql.Conn, turn protocol.TurnID) (bool, error)

TurnIsPlanMode reports whether turn was captured in planning mode (which also includes read-only delegated child turns).

func UserFromContext

func UserFromContext(ctx context.Context) (protocol.User, bool)

UserFromContext returns only the principal already verified by Node.

func ValidAgentProgress

func ValidAgentProgress(value protocol.ConversationProgress) bool

ValidAgentProgress reports whether a progress snapshot is non-empty and within the 64 KiB text budget.

func ValidateConnectionTrust

func ValidateConnectionTrust(ctx context.Context, db *sql.Conn, turn protocol.TurnID, binding *ApprovalBinding, trust protocol.SshTrust) error

ValidateConnectionTrust accepts host-key consent only inside an approval of a captured SSH run or transfer, for the profile exactly as saved now and a key it does not already trust.

func ValidateCountersForTesting

func ValidateCountersForTesting(ctx context.Context, connection *sql.Conn) error

func ValidateDispatchName

func ValidateDispatchName(value string) error

ValidateDispatchName checks that a dispatch namespace or topic uses the standard dispatch identifier characters and length limit.

func ValidateMCPElicitation

func ValidateMCPElicitation(ctx context.Context, db *sql.Conn, record canonical.Record) error

func ValidatePluginStatusStates

func ValidatePluginStatusStates(info protocol.PluginInfo, value json.RawMessage) ([]protocol.PluginUiState, error)

func ValidateProjectDraft

func ValidateProjectDraft(value protocol.ProjectsDraft) error

ValidateProjectDraft checks the request before native clone effects begin.

func ValidateRole

func ValidateRole(role protocol.RoleProfile) error

ValidateRole reports what a role definition alone makes invalid. A caller that asks for approval of a definition checks it first.

func ValidateRoleSkill

func ValidateRoleSkill(skill protocol.RoleSkill) (protocol.RoleSkill, error)

ValidateRoleSkill enforces size, UTF-8, path hygiene, and identifier bounds on a Bot-private skill before storage.

func ValidateTeam

func ValidateTeam(team protocol.TeamProfile) error

ValidateTeam reports what a team definition alone makes invalid, before its members and model are resolved against the catalog.

func WithCapturedUser

func WithCapturedUser(ctx context.Context, user protocol.UserID) context.Context

WithCapturedUser retains the immutable storage principal of admitted work. CurrentUser remains the canonical actor for authorization after a user merge.

func WithConversationHistory

func WithConversationHistory(ctx context.Context, history func(protocol.ConversationAssociation) bool) context.Context

WithConversationHistory attaches the native product's history-only associations to Node admission. Existing request receipts and admitted runs remain valid.

func WithDirectoryDiscussions

func WithDirectoryDiscussions(ctx context.Context, rules DirectoryDiscussions) context.Context

func WithKnowledgePackage

func WithKnowledgePackage(ctx context.Context, info protocol.PluginInfo) context.Context

WithKnowledgePackage retains a package after the trusted resource entry point checked its origin. Its Turn and Session belong to the execution Node, so the storage Node reads the captured package instead of resolving foreign IDs.

func WithKnowledgeScope

func WithKnowledgeScope(ctx context.Context, scope *protocol.ResourceScope) (context.Context, error)

WithKnowledgeScope checks the captured package identity before making it available to a local resource operation. Link caller and user verification belongs to the resource entry point and cannot be supplied in this payload.

func WithNativeDispatch

func WithNativeDispatch(ctx context.Context, namespaces []string) context.Context

WithNativeDispatch binds the namespaces owned by assembled native Node modules (such as scheduled-tasks and reminders) so existing dispatch schedules, handlers and jobs keep running when the legacy plugins are retired.

func WithNativeSkills

func WithNativeSkills(ctx context.Context, lookup NativeSkillsLookup) context.Context

WithNativeSkills attaches a per-Node native skills lookup to ctx for turn-reference admission and snapshot projection.

func WithNativeWakeNamespaces

func WithNativeWakeNamespaces(ctx context.Context, namespaces []string) context.Context

WithNativeWakeNamespaces binds the dispatch namespaces owned by assembled WakeProvider modules. Unlisted namespaces remain stored in SQLite without firing schedules or claiming jobs.

func WithPluginAvailability

func WithPluginAvailability(ctx context.Context, check func(protocol.PluginReference) error) context.Context

func WithProjectExecutorMode

func WithProjectExecutorMode(ctx context.Context, mode protocol.WorkMode, options map[string]map[string]json.RawMessage) context.Context

WithProjectExecutorMode carries an explicit work mode (and optional plugin mode options) for project work started under ctx.

func WithProjectExecutorModel

func WithProjectExecutorModel(ctx context.Context, model *protocol.RoleModel) context.Context

WithProjectExecutorModel carries a project's default executor model to the project work started under ctx. A nil model keeps the Node default.

func WithProjectExecutorPermission

func WithProjectExecutorPermission(ctx context.Context, perm *protocol.Permission) context.Context

WithProjectExecutorPermission carries an explicit execution permission for project work started under ctx. A nil value keeps the default policy.

func WithProjectTaskIsolatedWorktree

func WithProjectTaskIsolatedWorktree(ctx context.Context, value ProjectTaskIsolatedWorktree) context.Context

func WithToolPresentation

func WithToolPresentation(ctx context.Context, lookup ToolPresentationLookup) context.Context

WithToolPresentation attaches a per-Node native module presentation resolver to ctx for canonical record preparation.

func WithUser

func WithUser(ctx context.Context, user protocol.User) context.Context

WithUser carries a Node-verified principal through admitted asynchronous work. A peer never supplies this value in its request body.

func WorkspaceDirectory

func WorkspaceDirectory(path string) (string, error)

func WritePluginConversationValue

func WritePluginConversationValue(ctx context.Context, db *sql.Conn, reference protocol.PluginReference, session protocol.SessionID, turn *protocol.TurnID, key string, value json.RawMessage, expectedRevision uint64) (protocol.PluginStorageConversationEntry, error)

func WritePluginValue

func WritePluginValue(ctx context.Context, db *sql.Conn, reference protocol.PluginReference, key string, value json.RawMessage, expectedRevision uint64, index *protocol.PluginStorageIndex) (protocol.PluginStorageEntry, error)

Types

type AgentGuidance

type AgentGuidance struct {
	Turn    protocol.QueuedTurn
	Message protocol.ConversationInput
}

func TakeGuidance

func TakeGuidance(ctx context.Context, db *sql.Conn, recipient protocol.TurnID, selected ...protocol.TurnID) ([]AgentGuidance, []protocol.Event, error)

type AgentHistorySource

type AgentHistorySource struct {
	Caller  protocol.NodeID
	Session protocol.SessionID
	Turn    protocol.TurnID
}

type AgentInstruction

type AgentInstruction struct {
	Text     string   `json:"text"`
	AnyTools []string `json:"any_tools"`
}

type AgentInvocation

type AgentInvocation struct {
	User                 protocol.User
	StorageUser          protocol.UserID
	ChildRole            *protocol.RoleProfile
	Hooks                protocol.HooksSettings
	Session              protocol.Session
	Worktree             protocol.Worktree
	Run                  protocol.ConversationRun
	Turn                 protocol.QueuedTurn
	Caller               protocol.NodeID
	Message              protocol.ConversationInput
	Provider             *protocol.ConversationProvider
	Secret               *protocol.Secret
	EffectiveCredential  *protocol.CredentialRef
	AuthorizationFailure *protocol.Fault
	Instructions         []AgentInstruction
	Compaction           CompactionPolicy
	// Media holds the per-purpose model assignments frozen at admission.
	Media MediaCapture
	// Assistant is the declaration frozen by the turn's assistant binding.
	Assistant *protocol.PluginConversationDeclaration
	// ProjectTask is present only for the owner of the dispatched work session.
	ProjectTask *protocol.ProjectTaskWork
	// ConnectionTargets bounds the existing profiles reachable by this turn.
	// A delegated turn starts with its parent's capture, including an empty one.
	ConnectionTargets []protocol.ConnectionResource
	// FullConversationTools is true when the session's DirectoryDiscussion
	// registration opted into the full ordinary conversation toolset.
	FullConversationTools bool
}

func ClaimChild

func ClaimChild(ctx context.Context, db *sql.Conn, turn protocol.TurnID, now time.Time) (*AgentInvocation, []protocol.Event, error)

func ClaimNext

func ClaimNext(ctx context.Context, db *sql.Conn, now time.Time, held ...protocol.SessionID) (*AgentInvocation, []protocol.Event, error)

func ClaimRetriedChild

func ClaimRetriedChild(ctx context.Context, db *sql.Conn, now time.Time) (*AgentInvocation, []protocol.Event, error)

ClaimRetriedChild claims the next queued controller-retried child turn while respecting the parent conversation's ChildConcurrency cap.

func DelegateAgent

func DelegateAgent(ctx context.Context, db *sql.Conn, node protocol.NodeID, parent protocol.TurnID, identity canonical.ToolIdentity, selected *protocol.ConversationInput, ready bool, now time.Time) (AgentInvocation, []protocol.Event, error)

func DelegatePrepared

func DelegatePrepared(ctx context.Context, db *sql.Conn, node protocol.NodeID, parent protocol.TurnID, identity canonical.ToolIdentity, arguments json.RawMessage, selected *protocol.ConversationInput, ready, overlap bool, now time.Time) (AgentInvocation, []protocol.Event, error)

DelegatePrepared admits a child for a call whose executing arguments differ from the ones the model sent: a package tool bound to agents.delegate or agents.guide prepares them. identity stays the recorded call, which locates it in the conversation; arguments describe the child. overlap records the effective foreground mode, which a default can choose without an argument.

func (*AgentInvocation) AddressedRole

func (inv *AgentInvocation) AddressedRole() *protocol.RoleReference

func (*AgentInvocation) DiscussionRole

func (inv *AgentInvocation) DiscussionRole() (*protocol.RoleProfile, bool)

func (*AgentInvocation) ExecutingBot

func (inv *AgentInvocation) ExecutingBot() protocol.RoleID

ExecutingBot returns the captured identity of the actor performing this turn. A roster describes candidates. Only a selected actor owns private Bot data.

func (*AgentInvocation) GroupChatReplyRole

func (inv *AgentInvocation) GroupChatReplyRole() *protocol.RoleProfile

GroupChatReplyRole returns the addressed or selected member role replying in a group chat, team Bot discussion, or coordinator-led group directory.

func (*AgentInvocation) ProjectTaskRole

func (inv *AgentInvocation) ProjectTaskRole() *protocol.RoleProfile

type AgentReviewChange

type AgentReviewChange struct {
	Session protocol.SessionID
	Change  protocol.ConversationChange
}

func ApplyReviewCommand

func ApplyReviewCommand(ctx context.Context, db *sql.Conn, request protocol.Request, output protocol.Output, now time.Time) ([]AgentReviewChange, []protocol.Event, error)

ApplyReviewCommand runs inside the command transaction and returns feed effects to publish after COMMIT. It never owns another command or event ledger.

type AgentState

type AgentState struct {
	Session protocol.Session
	// Records are shared with every state extended from this one: read-only.
	Records     []canonical.Record
	Context     canonical.Context
	LoadedTools []string
	Reviewed    bool
	// contains filtered or unexported fields
}

func ExtendAgentState

func ExtendAgentState(ctx context.Context, db *sql.Conn, session protocol.SessionID, previous AgentState) (AgentState, int, error)

ExtendAgentState loads a session's state, decoding only the records appended after previous, and reports how many leading records it shares with it. History only grows within one history revision; after a rewind, or for another session, everything is loaded again.

func LoadAgentState

func LoadAgentState(ctx context.Context, db *sql.Conn, session protocol.SessionID) (AgentState, error)

type AgentStatisticsHistory added in v0.2.7

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

AgentStatisticsHistory is a completed, read-only projection for one session. It retains aggregates and their dependencies, not canonical records.

func ReadAgentStatisticsReusing added in v0.2.7

func ReadAgentStatisticsReusing(ctx context.Context, db *sql.Conn, session protocol.SessionID, previous *AgentStatisticsHistory) (protocol.ConversationStatistics, *AgentStatisticsHistory, error)

ReadAgentStatisticsReusing validates and extends the historical segments in the caller's snapshot. Keep previous and the returned projection read-only; do not retain a new projection from an unsuccessful transaction.

func (*AgentStatisticsHistory) Weight added in v0.2.7

func (h *AgentStatisticsHistory) Weight() int

Weight charges the retained projection and its dependency keys against the Runtime cache, including the variable-size policy and observation fields.

type ApprovalBinding

type ApprovalBinding struct {
	Owner                 protocol.PluginReference  `json:"owner"`
	Module                string                    `json:"module,omitempty"`
	Tool                  string                    `json:"tool"`
	Operation             *protocol.ToolOperation   `json:"operation"`
	ArtifactPackage       *protocol.PluginReference `json:"artifact_package,omitempty"`
	DiscussionDocument    bool                      `json:"discussion_document,omitempty"`
	DiscussionProject     bool                      `json:"discussion_project,omitempty"`
	DiscussionAllowed     bool                      `json:"discussion_allowed,omitempty"`
	ProjectTaskPolicy     bool                      `json:"project_task_policy,omitempty"`
	AllowStandingApproval bool                      `json:"allow_standing_approval,omitempty"`
	// StandingOperation and StandingProject let a module's custom write tool
	// (no Operation of its own) match the module's standing grant for that
	// operation in that fixed project.
	StandingOperation *protocol.ToolOperation `json:"standing_operation,omitempty"`
	StandingProject   *protocol.ProjectID     `json:"standing_project,omitempty"`
}

func (*ApprovalBinding) UnmarshalJSON

func (v *ApprovalBinding) UnmarshalJSON(data []byte) error

type ArtifactRead

type ArtifactRead struct {
	Content protocol.ArtifactContent
	Digest  string
}

ArtifactRead captures immutable metadata for a resource-worker read. It owns no database connection and must be rechecked against the session after IO.

func CaptureArtifactRead

func CaptureArtifactRead(ctx context.Context, db *sql.Conn, request protocol.Request) (ArtifactRead, error)

func CaptureDiscussionDocumentRead

func CaptureDiscussionDocumentRead(ctx context.Context, db *sql.Conn, request protocol.Request) (ArtifactRead, error)

type ArtifactWrite

type ArtifactWrite struct {
	Artifact protocol.ArtifactSummary
	Previous *protocol.ArtifactSummary
	HTML     string
	Warnings []string
	Digest   string
	Request  protocol.Request
	// contains filtered or unexported fields
}

func CaptureArtifactWrite

func CaptureArtifactWrite(ctx context.Context, db *sql.Conn, request protocol.Request, allowedClasses []string, now time.Time) (ArtifactWrite, error)

func CaptureDiscussionDocumentWrite

func CaptureDiscussionDocumentWrite(ctx context.Context, db *sql.Conn, request protocol.Request, allowedClasses []string, now time.Time) (ArtifactWrite, error)

type AutomaticChain

type AutomaticChain struct {
	Count int
	Limit int
}

AutomaticChain is a session's run of automatic turns since its last user input and the limit that run is held to.

func ReadAutomaticChain

func ReadAutomaticChain(ctx context.Context, db *sql.Conn, session protocol.SessionID) (AutomaticChain, error)

ReadAutomaticChain counts the notice turns and package continuations that started since the session's last user input. Automatic turns that never started neither count nor reset; joined guidance is user input, and so is the request behind a continuation the user asked for, which is the first turn of its chain. The limit is the one the chain's latest continuation declared, or the default.

type BackgroundRecord

type BackgroundRecord struct {
	Task            protocol.ConversationBackgroundTask `json:"task"`
	FollowUp        bool                                `json:"follow_up"`
	StopObserved    bool                                `json:"stop_observed,omitempty"`
	Stdout          *string                             `json:"stdout"`
	Stderr          *string                             `json:"stderr"`
	StdoutBytes     *uint64                             `json:"stdout_bytes,omitempty"`
	StderrBytes     *uint64                             `json:"stderr_bytes,omitempty"`
	StdoutTruncated bool                                `json:"stdout_truncated,omitempty"`
	StderrTruncated bool                                `json:"stderr_truncated,omitempty"`
	Response        *string                             `json:"response"`
	ResponseBytes   *uint64                             `json:"response_bytes,omitempty"`
	ElapsedMs       *uint64                             `json:"elapsed_ms"`
	SilenceMs       *uint64                             `json:"silence_ms,omitempty"`
	Sequence        uint64                              `json:"sequence"`
}

BackgroundRecord retains completion evidence independently of process handles. Background delivery consumes its follow-up flag through the same authoritative writer.

func (*BackgroundRecord) UnmarshalJSON

func (record *BackgroundRecord) UnmarshalJSON(data []byte) error

type ChildState

type ChildState struct {
	Run         protocol.ConversationRun
	Response    *string
	Speaker     string
	SpeakerRole *protocol.RoleID
	Recipient   *protocol.TurnID
	Paused      bool
	Ready       bool
	// TurnLimit reports that the child's role action limit ended the run.
	TurnLimit bool
	// FileRevisions records the latest revision of each file mutated by this
	// child turn (empty string indicates deletion or unknown state).
	FileRevisions map[string]string
}

func ReadChildState

func ReadChildState(ctx context.Context, db *sql.Conn, parent protocol.TurnID, child protocol.SessionID, exact *protocol.TurnID) (ChildState, error)

type Closed

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

Closed retains exclusive maintenance ownership until Reopen or Close.

func (*Closed) Close

func (closed *Closed) Close() error

func (*Closed) Copy

func (closed *Closed) Copy(ctx context.Context, target string) error

Copy keeps every source connection closed while copying the native family. Reopen and Close wait for the copy to finish or return its cancellation.

func (*Closed) Path

func (closed *Closed) Path() string

func (*Closed) Reopen

func (closed *Closed) Reopen(ctx context.Context) error

type CompactionPolicy added in v0.2.7

type CompactionPolicy struct {
	Percent    uint8
	UseDefault bool
}

func (CompactionPolicy) WindowTrigger added in v0.2.7

func (policy CompactionPolicy) WindowTrigger(contextLimit uint32) uint64

type ConfigurationConnection

type ConfigurationConnection struct {
	Method      protocol.PluginConnectorKind            `json:"method"`
	Access      *protocol.Secret                        `json:"access,omitempty"`
	ExpiresAtMs *uint64                                 `json:"expires_at_ms,omitempty"`
	Targets     map[string]protocol.PluginMcpDefinition `json:"targets,omitempty"`
	ID          protocol.PluginConnectorID              `json:"id"`
	Plugin      string                                  `json:"plugin"`
	Digest      string                                  `json:"digest"`
	Connector   string                                  `json:"connector"`
	Enabled     bool                                    `json:"enabled"`
	Connected   bool                                    `json:"connected"`
	Fields      map[string]string                       `json:"fields,omitempty"`
	Secrets     map[string]protocol.Secret              `json:"secrets,omitempty"`
	Identity    *protocol.PluginConnectorIdentity       `json:"identity,omitempty"`
}

ConfigurationConnection carries a configured account and its explicitly provisioned fields. Only the execution access token crosses the pairing.

type ConfigurationDocument added in v0.2.5

type ConfigurationDocument struct {
	Connections  []ConfigurationConnection                `json:"connections,omitempty"`
	Modules      map[string]json.RawMessage               `json:"modules,omitempty"`
	Mirror       bool                                     `json:"mirror,omitempty"`
	Format       string                                   `json:"format"`
	Version      int                                      `json:"version"`
	ExportedAt   string                                   `json:"exported_at"`
	Node         protocol.NodeID                          `json:"node"`
	Providers    []ConfigurationProvider                  `json:"providers,omitempty"`
	Defaults     *protocol.SessionConfig                  `json:"defaults,omitempty"`
	Search       *ConfigurationSearch                     `json:"search,omitempty"`
	Media        *protocol.MediaSettings                  `json:"media,omitempty"`
	Compaction   *protocol.ConversationCompactionSettings `json:"compaction,omitempty"`
	Team         *protocol.TeamSettings                   `json:"team,omitempty"`
	Roles        []protocol.RoleProfile                   `json:"roles,omitempty"`
	Teams        []protocol.TeamProfile                   `json:"teams,omitempty"`
	Sandbox      *protocol.SandboxSettings                `json:"sandbox,omitempty"`
	Power        *protocol.PowerSettings                  `json:"power,omitempty"`
	Python       *protocol.PythonSettings                 `json:"python,omitempty"`
	Instructions *string                                  `json:"instructions,omitempty"`
	Plugins      []ConfigurationPlugin                    `json:"plugins,omitempty"`
}

ConfigurationDocument carries one user's configuration. A manual import merges the supplied sections. A desktop mirror replaces the user's personal configuration, including model defaults and execution grants. Only an administrator's manual export can include machine settings.

func ExportConfiguration added in v0.2.5

func ExportConfiguration(ctx context.Context, db *sql.Conn, node protocol.NodeID, exportedAt time.Time, instructions *string) (ConfigurationDocument, error)

ExportConfiguration builds the current user's document. instructions is the profile's personal instructions text, which the Node reads. Lists are sorted by ID or name and maps encode in key order, so the same configuration and time give the same bytes.

func ExportConfigurationSync

func ExportConfigurationSync(ctx context.Context, db *sql.Conn, node protocol.NodeID) (ConfigurationDocument, error)

func ParseConfiguration added in v0.2.5

func ParseConfiguration(document json.RawMessage) (ConfigurationDocument, error)

ParseConfiguration accepts only this Node's document format and version.

func (ConfigurationDocument) PluginNames added in v0.2.5

func (document ConfigurationDocument) PluginNames() []string

PluginNames lists the packages the document configures, in document order.

func (ConfigurationDocument) SyncFingerprints

func (doc ConfigurationDocument) SyncFingerprints() (string, string, error)

type ConfigurationImport added in v0.2.5

type ConfigurationImport struct {
	Items        []protocol.ConfigurationImportItem
	Events       []protocol.Event
	Instructions *string
	Python       *protocol.PythonSettings
}

ConfigurationImport is the outcome of one import inside the caller's transaction. The Node writes Instructions to the profile after the commit and configures Python with Python.

func ApplyConfigurationSync

func ApplyConfigurationSync(ctx context.Context, db *sql.Conn, node protocol.NodeID, doc ConfigurationDocument, targets ConfigurationTargets) (ConfigurationImport, error)

The caller owns the transaction and commits only after module participants and installation records have also succeeded.

func ImportConfiguration added in v0.2.5

func ImportConfiguration(ctx context.Context, db *sql.Conn, node protocol.NodeID, document ConfigurationDocument, targets ConfigurationTargets) (ConfigurationImport, error)

ImportConfiguration merges a document into the current user's configuration: entries with the same ID are replaced, new entries are added and entries only on this Node are kept. Areas run in an order where references (media and roles to providers, teams to roles) are already imported.

type ConfigurationPlugin added in v0.2.5

type ConfigurationPlugin struct {
	Signature       []byte                                 `json:"signature,omitempty"`
	Registry        *protocol.PluginSkillsRegistryResolved `json:"registry,omitempty"`
	Repository      *protocol.PluginOriginOnlinePayload    `json:"repository,omitempty"`
	RepositorySkill bool                                   `json:"repository_skill,omitempty"`
	Market          bool                                   `json:"market,omitempty"`
	MCPSource       *protocol.PluginMcpDefinition          `json:"mcp_source,omitempty"`
	MCP             json.RawMessage                        `json:"mcp,omitempty"`
	MCPAllowed      map[string]bool                        `json:"mcp_allowed,omitempty"`
	Name            string                                 `json:"name"`
	Digest          string                                 `json:"digest"`
	Version         *string                                `json:"version,omitempty"`
	Enabled         bool                                   `json:"enabled"`
	Pinned          bool                                   `json:"pinned,omitempty"`
	Values          map[string]json.RawMessage             `json:"values,omitempty"`
	Secrets         map[string]protocol.Secret             `json:"secrets,omitempty"`
}

ConfigurationPlugin is an installed package's choices and settings. The package itself is not carried: an import configures only packages that the target already has.

type ConfigurationProvider added in v0.2.5

type ConfigurationProvider struct {
	Account  *protocol.RuntimeCredential   `json:"account,omitempty"`
	Provider protocol.ConversationProvider `json:"provider"`
	Key      *protocol.Secret              `json:"key,omitempty"`
}

ConfigurationProvider is a provider with its API key. Credential, owner, origin and revision are bound to the exporting Node and are left out; the ID is kept so that roles, teams, media and sessions still refer to it.

type ConfigurationSearch added in v0.2.5

type ConfigurationSearch struct {
	Settings    protocol.SearchSettings              `json:"settings"`
	Credentials map[protocol.SearchDriver]searchAuth `json:"credentials,omitempty"`
}

ConfigurationSearch is the search settings with each driver's credentials.

type ConfigurationSyncPeer

type ConfigurationSyncPeer struct {
	Peer                              protocol.NodeID
	Side                              string
	User                              protocol.User
	Config, Packages, Status, Failure string
	Cached                            int
}

func SyncPeer

func SyncPeer(ctx context.Context, db *sql.Conn, node, peer protocol.NodeID, side string) (ConfigurationSyncPeer, error)

type ConfigurationTargets added in v0.2.5

type ConfigurationTargets struct {
	Instructions *string
	Plugins      map[string]map[string]string
	// A mirror can install these verified packages before binding model presets.
	Packages map[string]protocol.PluginInfo
}

ConfigurationTargets are the inputs an import needs from outside SQL: the profile's personal instructions text and, per installed package, the MCP settings destinations the Node resolves.

type ConnectionAction

type ConnectionAction struct {
	Kind ConnectionActionKind
	// SaveDatabase and SaveSsh.
	DatabaseInput ConnectionDatabaseInput
	SshInput      ConnectionSshInput
	// Browse and Query.
	Database *string
	ReadOnly bool
	Sql      string
	RowLimit uint32
	// Run and Transfer. Run defaults to 120 seconds; Query and Transfer
	// require a value.
	Command    string
	TimeoutMs  *uint64
	Path       string
	RemotePath string
	Direction  protocol.SshDirection
}

ConnectionAction is one captured tool request. Only the fields of its kind are read.

type ConnectionActionKind

type ConnectionActionKind uint8
const (
	ConnectionListDatabases ConnectionActionKind = iota
	ConnectionListSsh
	ConnectionSaveDatabase
	ConnectionSaveSsh
	ConnectionBrowse
	ConnectionQuery
	ConnectionRun
	ConnectionTransfer
)

type ConnectionCatalog

type ConnectionCatalog struct {
	Bound     *protocol.ConnectionResource
	Databases []protocol.DatabaseProfile
	Ssh       []protocol.SshProfile
}

ConnectionCatalog is what one conversation may see of the saved database and SSH profiles. Credentials stay behind the Node workers.

func ReadConnectionCatalog

func ReadConnectionCatalog(ctx context.Context, db *sql.Conn, id protocol.SessionID) (ConnectionCatalog, error)

func (ConnectionCatalog) Resources

func (catalog ConnectionCatalog) Resources() []protocol.ConnectionResource

func (*ConnectionCatalog) Restrict

func (catalog *ConnectionCatalog) Restrict(targets []protocol.ConnectionResource)

type ConnectionDatabaseInput

type ConnectionDatabaseInput struct {
	Connection       *protocol.DatabaseID     `json:"connection"`
	ExpectedRevision *uint64                  `json:"expected_revision"`
	Name             *string                  `json:"name"`
	Engine           *protocol.DatabaseEngine `json:"engine"`
	Path             *string                  `json:"path"`
	Host             *string                  `json:"host"`
	Port             *uint16                  `json:"port"`
	Username         *string                  `json:"username"`
	Database         *string                  `json:"database"`
	ReadOnly         *bool                    `json:"read_only"`
}

ConnectionDatabaseInput is a conversation's edit of a database connection. It carries public configuration only; a stored password is preserved.

func (*ConnectionDatabaseInput) UnmarshalJSON

func (value *ConnectionDatabaseInput) UnmarshalJSON(data []byte) error

type ConnectionInspection

type ConnectionInspection struct {
	Profile          protocol.SshID
	ExpectedRevision uint64
	Key              protocol.SshHostKey
	Changed          bool
}

ConnectionInspection is an unverified host key observed while a captured SSH operation connected.

type ConnectionSshInput

type ConnectionSshInput struct {
	Connection       *protocol.SshID             `json:"connection"`
	ExpectedRevision *uint64                     `json:"expected_revision"`
	Name             *string                     `json:"name"`
	Host             *string                     `json:"host"`
	Port             *uint16                     `json:"port"`
	Username         *string                     `json:"username"`
	Authentication   *protocol.SshAuthentication `json:"authentication"`
	Credential       *protocol.SshCredential     `json:"credential"`
	KeyPath          *string                     `json:"key_path"`
}

ConnectionSshInput is a conversation's edit of an SSH connection.

func (*ConnectionSshInput) UnmarshalJSON

func (value *ConnectionSshInput) UnmarshalJSON(data []byte) error

type ConnectionStatus

type ConnectionStatus struct {
	Target          protocol.ConnectionResource
	MissingPassword bool
}

ConnectionStatus is one reachable target and whether its network database password is still missing.

func ConnectionStatuses

func ConnectionStatuses(ctx context.Context, db *sql.Conn, turn protocol.TurnID, owner protocol.PluginReference, targets, captured []protocol.ConnectionResource) ([]ConnectionStatus, error)

ConnectionStatuses reports the targets the turn may reach, in request order. Targets outside the turn are omitted, not reported as faults.

type ConnectorBound

type ConnectorBound struct {
	Origin  *protocol.PluginOrigin                  `json:"origin"`
	Auth    protocol.PluginConnectorAuth            `json:"auth"`
	Origins []string                                `json:"origins"`
	Inject  []protocol.PluginConnectorInjection     `json:"inject"`
	Targets map[string]protocol.PluginMcpDefinition `json:"targets"`
}

type ConnectorLoginCapture

type ConnectorLoginCapture struct {
	Attempt     protocol.PluginConnectorAttempt
	Package     protocol.PluginInfo
	Declaration protocol.PluginConnectorDeclaration
	Previous    uint64
	Record      ConnectorRecord
	Input       protocol.PluginConnectorInput
	CLIIdentity *protocol.PluginConnectorIdentity // verified before the mutation is admitted
}

func PrepareConnectorConsent

func PrepareConnectorConsent(ctx context.Context, db *sql.Conn, id protocol.PluginConnectorID, expected uint64) (ConnectorLoginCapture, error)

type ConnectorRecord

type ConnectorRecord struct {
	ID            protocol.PluginConnectorID        `json:"id"`
	Plugin        string                            `json:"plugin"`
	Connector     string                            `json:"connector"`
	Revision      uint64                            `json:"revision"`
	AuthRevision  uint64                            `json:"auth_revision"`
	Method        protocol.PluginConnectorKind      `json:"method"`
	Enabled       bool                              `json:"enabled"`
	Fields        map[string]string                 `json:"fields"`
	Secrets       map[string]protocol.Secret        `json:"secrets"`
	Grant         *authorization.Issued             `json:"grant"`
	GrantRevision uint64                            `json:"grant_revision"`
	Identity      *protocol.PluginConnectorIdentity `json:"identity"`
	Bound         *ConnectorBound                   `json:"bound"`
	State         protocol.PluginConnectorState     `json:"state"`
	CheckedAtMs   *uint64                           `json:"checked_at_ms"`
	Login         *protocol.RequestID               `json:"login"`
}

func ReadConnectorRecord

func ReadConnectorRecord(ctx context.Context, db *sql.Conn, id protocol.PluginConnectorID) (ConnectorRecord, error)

func ResolveConnectorAccount

ResolveConnectorAccount loads and validates a user-scoped connector account for outbound credentialed HTTP execution.

func SaveConnectorGrant

func SaveConnectorGrant(ctx context.Context, db *sql.Conn, previous ConnectorRecord, grant authorization.Issued) (ConnectorRecord, error)

func SyncCLIAccounts

func SyncCLIAccounts(ctx context.Context, db *sql.Conn) ([]ConnectorRecord, error)

SyncCLIAccounts returns the desktop user's bound CLI accounts. Their actual tokens are checked outside the read transaction on a peer's manifest request.

type ConversationActivity added in v0.2.7

type ConversationActivity struct {
	Runs       []protocol.ConversationRun
	Queue      protocol.ConversationQueue
	Approvals  []protocol.ConversationApproval
	Questions  []protocol.ConversationQuestion
	Children   []protocol.ConversationChild
	Background []protocol.ConversationBackgroundTask
}

func ReadConversationActivity added in v0.2.7

func ReadConversationActivity(ctx context.Context, db *sql.Conn, session protocol.SessionID, limit uint16, changedChildren ...protocol.TurnID) (ConversationActivity, error)

ReadConversationActivity reads the live head's independently published metadata on the caller's pinned snapshot. Its anchors follow the stored head bounds, not the transport budget of a page containing entry bodies.

type ConversationAssetReads added in v0.2.7

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

ConversationAssetReads belongs to one Node. A checkpoint certifies the dependencies of a range already delivered to the caller. It holds no bodies, target collections or database leases. Eviction falls back to ordinary paging.

func (*ConversationAssetReads) List added in v0.2.7

type Counter

type Counter string
const (
	CounterEvents         Counter = "events"
	CounterPluginRecords  Counter = "plugin_conversation_records"
	CounterAgentEvents    Counter = "agent_events"
	CounterDispatchEvents Counter = "dispatch_events"
	CounterDispatchJobs   Counter = "dispatch_jobs"
	CounterNotifications  Counter = "notifications"
	CounterSessions       Counter = "sessions"
	CounterTurns          Counter = "turns"
	CounterCheckpoints    Counter = "file_checkpoints"
	CounterArtifacts      Counter = "artifacts"
	CounterBackground     Counter = "agent_background"
)

type CredentialRenewal

type CredentialRenewal struct {
	User        protocol.User
	Provider    *protocol.ConversationProvider
	Credential  protocol.CredentialRef
	Connection  *ConnectorRecord
	Declaration protocol.PluginConnectorDeclaration
	Revision    uint64
	DueMs       uint64
}

func ReadCredentialRenewals

func ReadCredentialRenewals(ctx context.Context, db *sql.Conn, node protocol.NodeID) ([]CredentialRenewal, error)

ReadCredentialRenewals schedules currently used accounts owned here. A turn that has retained another account can renew it at its next model step.

type DatabaseBrowse

type DatabaseBrowse struct {
	Database *string
}

type DatabaseOperation

type DatabaseOperation struct {
	Profile  protocol.DatabaseProfile
	Password protocol.Secret
	// Ssh is set only for an SSH-tunnelled profile.
	Ssh   *DatabaseTunnel
	Query *DatabaseQuery
	// Browse is set only for browse_database.
	Browse *DatabaseBrowse
	// Storage is the Node profile directory external SQLite must not access.
	Storage string
}

DatabaseOperation is everything an external database operation needs after the storage lease is released. It carries secrets: never log, encode or return it to a controller.

func PrepareDatabase

func PrepareDatabase(ctx context.Context, db *sql.Conn, storage string, command protocol.Command) (DatabaseOperation, error)

PrepareDatabase validates test_database, check_database, browse_database or query_database against the saved profile and reads its secret and tunnel material. Execute the returned operation outside the storage lease.

type DatabaseQuery

type DatabaseQuery struct {
	Sql       string
	RowLimit  int
	TimeoutMs uint64
}

type DatabaseTunnel

type DatabaseTunnel struct {
	Profile    protocol.SshProfile
	Credential protocol.SshCredential
}

type DemoSession

type DemoSession struct {
	Project     *protocol.ProjectID
	Title       string
	Association *protocol.ConversationAssociation
	Execution   protocol.ConversationExecution
	Team        *protocol.TeamSelection
	Role        *protocol.RoleReference
	Turns       []DemoTurn
}

DemoSession describes a synthetic conversation seeded into an isolated --demo Node profile so products can showcase realistic transcripts and Kanban links.

type DemoTaskWork

type DemoTaskWork struct {
	ID                  protocol.RequestID
	Project             protocol.ProjectID
	Worktree            protocol.WorktreeID
	Source              *protocol.SessionID
	SourceTurn          *protocol.TurnID
	Session             *protocol.SessionID
	Turn                *protocol.TurnID
	ReportTurn          *protocol.TurnID
	ReportTurnStartedAt int64
	Team                *protocol.TeamSelection
	Role                *protocol.RoleReference
	Title               string
	Message             string
	State               protocol.ProjectTaskWorkState
	Detail              string
	Revision            uint64
	CreatedAt           int64
	UpdatedAt           int64
}

DemoTaskWork binds a synthetic ProjectTaskWork record in SQLite to already seeded demo sessions so list_project_task_work and board cards stay canonical.

type DemoTurn

type DemoTurn struct {
	User       string
	Assistant  string
	Speaker    string // Optional speaker label for team/role turns.
	References []protocol.ConversationReference
	StartedAt  time.Time
	FinishedAt time.Time
}

DemoTurn describes one synthetic completed user/assistant turn inserted into an isolated demo workspace without making any model or network call.

type DirectoryDiscussion

type DirectoryDiscussion struct {
	Namespace string
	Kind      string
	Directory string
	// FullConversationTools opts this directory discussion into the ordinary
	// conversation toolset (shell/command tools, HTML documents & previews,
	// web-search, browser, memory, reminders, scheduled tasks, builtins, MCP,
	// and plugins) alongside the module's own DiscussionToolProvider tools.
	FullConversationTools bool
	ResolveTaskOwner      func(participant, requested protocol.ProjectTaskOwnerSelection) (protocol.ProjectTaskOwnerSelection, error)
	ResolveGroupTaskOwner func(GroupTaskAssignment) (protocol.ProjectTaskOwnerSelection, error)
}

DirectoryDiscussion binds a product's private native association to one personal directory. ResolveTaskOwner is a pure module policy, called on both preparation and use of an approval with the live participant revision. ResolveGroupTaskOwner handles coordinator-led team directories when set.

type DirectoryDiscussionRegistration

type DirectoryDiscussionRegistration struct {
	DirectoryDiscussion
	Module string
}

type DirectoryDiscussions

type DirectoryDiscussions map[[2]string]DirectoryDiscussionRegistration

func (DirectoryDiscussions) FullConversation

func (rules DirectoryDiscussions) FullConversation(a *protocol.ConversationAssociation) bool

FullConversation reports whether association a is registered with FullConversationTools enabled.

func (DirectoryDiscussions) Lookup

type Exclusive

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

Exclusive drains existing reads and admitted writes and blocks new leases.

func (*Exclusive) Close

func (exclusive *Exclusive) Close() error

func (*Exclusive) Connection

func (exclusive *Exclusive) Connection() *sql.Conn

Connection is the writer's connection, which is idle while every lease is held.

func (*Exclusive) Pause

func (exclusive *Exclusive) Pause(ctx context.Context) (*Closed, error)

Pause checkpoints and closes the database without releasing ownership between a read of its metadata and a copy of its files.

func (*Exclusive) Pin

func (exclusive *Exclusive) Pin(ctx context.Context) (*Pinned, error)

Pin begins a read transaction on the database exactly as it is under the exclusive lease. The transaction keeps its share of the lease when the exclusive owner closes, so reads and writes continue while the pinned state is read.

type GroupTaskAssignment

type GroupTaskAssignment struct {
	Team      protocol.TeamSelection
	Lead      protocol.RoleID
	Members   []protocol.RoleReference
	Speaker   *protocol.RoleReference
	Requested protocol.ProjectTaskOwnerSelection
}

GroupTaskAssignment describes the live group team, coordinator, members, and optional turn speaker when preparing or approving a task assignment.

type Handle

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

Handle owns one file's writer and its independent read-only connection pool.

func OpenHandle

func OpenHandle(ctx context.Context, path string) (*Handle, error)

func (*Handle) Close

func (handle *Handle) Close() error

func (*Handle) Exclusive

func (handle *Handle) Exclusive(ctx context.Context) (*Exclusive, error)

func (*Handle) Path

func (handle *Handle) Path() string

func (*Handle) Pause

func (handle *Handle) Pause(ctx context.Context) (*Closed, error)

func (*Handle) Read

func (handle *Handle) Read(ctx context.Context, callback func(*sql.Conn) error) error

Read pins the snapshot before invoking its callback exactly once.

func (*Handle) Write

func (handle *Handle) Write(ctx context.Context, callback func(*sql.Conn) error) error

Write submits related SQL without external effects or transaction controls. An admitted callback is not replayed, and its caller waits for the commit result. A callback returns its first SQL error so that the writer can roll its work back.

func (*Handle) WriteSequence

func (handle *Handle) WriteSequence() uint64

WriteSequence returns the current cache generation, or zero while a commit or exclusive maintenance is in progress. Both writers and exclusive leases advance the sequence on entry and exit; only odd generations are stable.

type KnowledgeCapture

type KnowledgeCapture struct {
	ExternalPackage bool                      `json:"external_package,omitempty"`
	Package         *protocol.PluginReference `json:"package"`
	Worktree        *protocol.WorktreeID      `json:"worktree"`
	Session         *protocol.SessionID       `json:"session"`
	User            *protocol.UserID          `json:"user,omitempty"`
	Space           string                    `json:"space,omitempty"`
	Namespace       string                    `json:"namespace,omitempty"`
}

KnowledgeCapture is the plugin scope a collection was created in.

type KnowledgeSource

type KnowledgeSource struct {
	Node     *protocol.NodeID            `json:"node,omitempty"`
	Kind     string                      `json:"kind"`
	Worktree protocol.WorktreeID         `json:"worktree"`
	Path     string                      `json:"path"`
	Scope    protocol.PluginStorageScope `json:"scope"`
	Prefix   string                      `json:"prefix"`
}

KnowledgeSource is the flat reading of a source union.

func ReadKnowledgeSource

func ReadKnowledgeSource(source protocol.KnowledgeSource) KnowledgeSource

ReadKnowledgeSource flattens a validated source union.

type KnowledgeStoragePage

type KnowledgeStoragePage struct {
	Records []KnowledgeStorageRecord
	After   *string
}

KnowledgeStoragePage is one page of captured plugin values. After continues the scan; skipped keys still advance it.

func ReadKnowledgeStoragePage

func ReadKnowledgeStoragePage(ctx context.Context, db *sql.Conn, stored KnowledgeStored, after *string, limit int) (KnowledgeStoragePage, error)

ReadKnowledgeStoragePage reads one page of the plugin values a storage collection indexes, in key order.

type KnowledgeStorageRecord

type KnowledgeStorageRecord struct {
	Key            string
	Revision       uint64
	Hash           [32]byte
	Title, Body    string
	Source         protocol.PluginStorageSource
	SourceRevision uint64
	SourceHash     [32]byte
	Tags           []string
}

KnowledgeStorageRecord is one plugin value captured as a knowledge source: the indexed entry and the value its text was read from.

func ReadKnowledgeStorageRecord

func ReadKnowledgeStorageRecord(ctx context.Context, db *sql.Conn, stored KnowledgeStored, key string) (*KnowledgeStorageRecord, error)

ReadKnowledgeStorageRecord captures one plugin value of a storage collection, or nil when it no longer exists.

func (KnowledgeStorageRecord) Identity

func (record KnowledgeStorageRecord) Identity() string

Identity is the source revision the index and citations carry. It changes with the entry, its index data and the text it points to.

type KnowledgeStored

type KnowledgeStored struct {
	Collection protocol.KnowledgeCollection `json:"collection"`
	Capture    KnowledgeCapture             `json:"capture"`
	Automatic  bool                         `json:"automatic"`
}

KnowledgeStored is one durable collection with its captured scope. The retrieval index is derived from it.

func AllowedKnowledge

func AllowedKnowledge(ctx context.Context, db *sql.Conn, request protocol.Request) ([]KnowledgeStored, error)

AllowedKnowledge returns the collections a request may read. Query plans intersect these durable grants before reading the derived index.

func ReadKnowledgeCatalog

func ReadKnowledgeCatalog(ctx context.Context, db *sql.Conn) ([]KnowledgeStored, error)

ReadKnowledgeCatalog reads every stored collection for the indexing worker.

func RemoveOrphanedKnowledge

func RemoveOrphanedKnowledge(ctx context.Context, db *sql.Conn) ([]KnowledgeStored, bool, error)

RemoveOrphanedKnowledge deletes the collections whose owner was removed and returns the remaining catalog. Their derived index goes with the next indexing pass. Registering the same worktree, project or package again does not bring a collection back.

func (KnowledgeStored) IsPersonalMemoryStorage

func (stored KnowledgeStored) IsPersonalMemoryStorage() bool

IsPersonalMemoryStorage identifies the built-in and retired official memory collections, whose Bot-owned entries are private to their executing role.

type LocalModelCatalog

type LocalModelCatalog struct {
	Settings    protocol.ModelsLocalSettings
	Definitions map[string]*protocol.ModelsDefinition
}

LocalModelCatalog is the durable local model configuration: the settings and every pinned or registered definition by identity.

func ReadLocalModelCatalog

func ReadLocalModelCatalog(ctx context.Context, db *sql.Conn) (LocalModelCatalog, error)

ReadLocalModelCatalog reads the settings and joins registered definitions with the pinned builtins.

type MediaAssignment

type MediaAssignment struct {
	Model string `json:"model"`
	// Provider is absent when the bound model could not run at admission. The
	// purpose then has no model; it never falls back to another one.
	Provider *protocol.ConversationProvider `json:"provider,omitempty"`
}

MediaAssignment is one purpose's binding as captured when a turn was admitted.

type MediaCapture

type MediaCapture map[protocol.MediaKind]MediaAssignment

MediaCapture holds the assigned purposes only. An absent purpose follows the conversation model.

func CaptureMedia

func CaptureMedia(ctx context.Context, db *sql.Conn) (MediaCapture, error)

CaptureMedia freezes the per-purpose assignments for one admitted turn.

type ModuleConfigurationStore

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

func NewModuleConfigurationStore

func NewModuleConfigurationStore(ctx context.Context, db *sql.Conn, module string) ModuleConfigurationStore

func (ModuleConfigurationStore) Changed

func (s ModuleConfigurationStore) Changed() bool

func (ModuleConfigurationStore) Replace

func (ModuleConfigurationStore) RoleKeys

func (s ModuleConfigurationStore) RoleKeys() (map[string]string, error)

RoleKeys maps personal role identities to the stable role keys used across Nodes.

func (ModuleConfigurationStore) Values

type ModuleConfigurationValue

type ModuleConfigurationValue struct {
	Value json.RawMessage              `json:"value"`
	Index *protocol.PluginStorageIndex `json:"index,omitempty"`
}

type NativeSkillsLookup

type NativeSkillsLookup func() []protocol.NativeSkill

NativeSkillsLookup returns the compile-time built-in skills contributed by assembled native Node modules.

type PendingSessionApprovalRow

type PendingSessionApprovalRow struct {
	Approval  protocol.ConversationApproval
	Tool      string
	Arguments json.RawMessage
}

PendingSessionApprovalRow pairs a pending approval with its tool request.

func ListPendingSessionApprovals

func ListPendingSessionApprovals(ctx context.Context, db *sql.Conn, session protocol.SessionID) ([]PendingSessionApprovalRow, error)

ListPendingSessionApprovals returns all pending approvals for session ordered oldest-first, along with their tool names and arguments.

type Pinned

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

Pinned is a read transaction that began under an exclusive lease and outlives it. It keeps one lease, so the database stays open until Close.

func (*Pinned) Close

func (pinned *Pinned) Close() error

func (*Pinned) Connection

func (pinned *Pinned) Connection() *sql.Conn

Connection reads the pinned state.

type PluginValueRank

type PluginValueRank struct {
	Key      string
	Revision uint64
}

PluginValueRank is one keyword hit of a semantic plan: the key and the revision it was ranked at.

type PreparedPaths

type PreparedPaths struct {
	Path            string
	TerminalsClosed bool
}

PreparedPaths contains the observations and effects made outside SQL transactions: the canonical directory, and whether a project removal already closed one of the project's terminals.

func PreparePaths

func PreparePaths(command protocol.Command) (PreparedPaths, error)

type ProjectRemoval

type ProjectRemoval struct {
	Terminals []protocol.TerminalInfo
	Sessions  []protocol.SessionID
}

ProjectRemoval lists what the Node closes before a removal is recorded.

func PlanProjectRemoval

func PlanProjectRemoval(ctx context.Context, db *sql.Conn, expected protocol.Project) (ProjectRemoval, error)

PlanProjectRemoval validates a removal and lists the project's terminals that are not closed and its sessions, whose background commands stop. A stale or busy removal fails here, before anything is closed.

type ProjectSessionSummary

type ProjectSessionSummary struct {
	Session protocol.Session
	Reply   string
}

ProjectSessionSummary is one top-level project conversation with the leading text of its latest public assistant reply.

func ListProjectSessions

func ListProjectSessions(ctx context.Context, db *sql.Conn, project protocol.ProjectID, limit int) ([]ProjectSessionSummary, error)

ListProjectSessions returns up to limit accessible, non-removed top-level conversations of project, newest first. Subagent children are omitted and the reply is the same bounded preview the activity list shows.

type ProjectTaskIsolatedWorktree

type ProjectTaskIsolatedWorktree struct {
	Source   ProjectWorktree
	Worktree protocol.Worktree
	Branch   string
}

ProjectTaskIsolatedWorktree identifies a freshly provisioned managed worktree and Git branch bound to a newly dispatched project task.

type ProjectTaskRoute

type ProjectTaskRoute struct {
	Input       protocol.StartProjectTaskInput
	Outbound    protocol.Request
	Name        string
	Revision    uint64
	Source      *protocol.SessionID
	SourceTurn  *protocol.TurnID
	Stop        *protocol.RequestID
	StopSession protocol.SessionID
}

func ListTaskRoutes

func ListTaskRoutes(ctx context.Context, db *sql.Conn, peer protocol.NodeID) ([]ProjectTaskRoute, error)

func ReportRoute

func ReportRoute(ctx context.Context, db *sql.Conn, owner protocol.UserID, peer protocol.NodeID, task protocol.RequestID) (*ProjectTaskRoute, error)

func ReserveTaskRoute

func ReserveTaskRoute(ctx context.Context, db *sql.Conn, route ProjectTaskRoute) (ProjectTaskRoute, error)

type ProjectWorktree

type ProjectWorktree struct {
	Worktree protocol.Worktree
	Project  protocol.Project
}

ProjectWorktree contains only durable resource identity, not filesystem observations.

func PrepareWorkspaceWorktreeRemoval

func PrepareWorkspaceWorktreeRemoval(ctx context.Context, db *sql.Conn, id protocol.WorktreeID) (ProjectWorktree, error)

func ReadProjectWorktree

func ReadProjectWorktree(ctx context.Context, db *sql.Conn, id protocol.WorktreeID) (ProjectWorktree, error)

type ProviderLoginCapture

type ProviderLoginCapture struct {
	Attempt  protocol.ConversationLoginAttempt
	Provider protocol.ConversationProvider
	Target   providers.AccountTarget
}

func CaptureProviderLogin

func CaptureProviderLogin(ctx context.Context, db *sql.Conn, id protocol.ProviderID, expected uint64, attempt protocol.RequestID) (ProviderLoginCapture, error)

type ProviderRenewal

type ProviderRenewal struct {
	Capture    ProviderLoginCapture
	Credential protocol.CredentialID
	Revision   uint64
	Grant      providers.AccountGrant
}

func BeginProviderRenewal

func BeginProviderRenewal(ctx context.Context, db *sql.Conn, node protocol.NodeID, provider protocol.ConversationProvider, reference protocol.CredentialRef, now time.Time) (*ProviderRenewal, error)

func BeginScheduledProviderRenewal

func BeginScheduledProviderRenewal(ctx context.Context, db *sql.Conn, node protocol.NodeID, provider protocol.ConversationProvider, reference protocol.CredentialRef, now time.Time) (*ProviderRenewal, error)

BeginScheduledProviderRenewal rechecks selection in the write transaction that admits the refresh so a stale timer cannot renew a retired account.

type ProviderResourceCapture

type ProviderResourceCapture struct {
	Provider   protocol.ConversationProvider
	Endpoint   protocol.PluginModelAuthEndpoint
	Secret     protocol.Secret
	Credential protocol.Credential
}

func CaptureNativeProviderResource

func CaptureNativeProviderResource(ctx context.Context, db *sql.Conn, node protocol.NodeID, id protocol.ProviderID, revision uint64, resolve func(protocol.Authentication) (protocol.PluginModelAuthEndpoint, bool)) (ProviderResourceCapture, error)

CaptureNativeProviderResource resolves one fixed account-read endpoint on an OAuth provider for a compile-time native module without requiring a plugin package capture.

func CaptureProviderResource

func CaptureProviderResource(ctx context.Context, db *sql.Conn, node protocol.NodeID, caller protocol.PluginReference, id protocol.ProviderID, revision uint64, name string, mutation bool) (ProviderResourceCapture, error)

type ResolvedPluginSettings

type ResolvedPluginSettings struct {
	Values     map[string]json.RawMessage
	Secrets    map[string]protocol.Secret
	MCP        json.RawMessage
	MCPAllowed map[string]bool
	MCPTargets map[string]string
}

func ResolvePluginSettings

func ResolvePluginSettings(ctx context.Context, db *sql.Conn, reference protocol.PluginReference) (ResolvedPluginSettings, error)

type SchemaObject

type SchemaObject struct {
	Kind string
	Name string
}

type SemanticPlan

type SemanticPlan struct {
	Package     protocol.PluginReference
	Space       string
	Collections []KnowledgeStored
	Keyword     []PluginValueRank
	Eligible    map[string]bool
	Embedding   protocol.ModelsLocalChoice
}

SemanticPlan captures what one plugin storage search may rank: the package, its automatic collections, the keyword ranking and the keys whose text is indexed.

func PrepareSemanticSearch

func PrepareSemanticSearch(ctx context.Context, db *sql.Conn, request protocol.Request) (SemanticPlan, error)

PrepareSemanticSearch captures the plan of one plugin storage search. A keyword search, or one without text, selects no collection.

type SemanticSelection

type SemanticSelection struct {
	Keys     []string
	Stamps   []SemanticStamp
	Mode     protocol.KnowledgeMode
	Indexing bool
}

SemanticSelection is the fused key order of one search.

type SemanticStamp

type SemanticStamp struct {
	Collection protocol.KnowledgeID
	Key        string
	Revision   string
}

SemanticStamp pins a semantic hit to the source revision it was indexed at.

type SessionBotSwitch

type SessionBotSwitch struct {
	Session  protocol.SessionID
	Role     protocol.RoleReference
	Mode     protocol.WorkMode
	Worktree protocol.WorktreeID
}

SessionBotSwitch describes an in-place Bot (role) switch on an idle session, with optional mode override and idle worktree switch.

type SessionContextStats

type SessionContextStats struct {
	ContextTokens uint64
	ContextLimit  uint32
	Compacted     bool
	Running       bool
	Archived      bool
}

SessionContextStats summarizes a session's current context footprint and lifecycle state for Bot handoff decisions.

func ReadSessionContextStats

func ReadSessionContextStats(ctx context.Context, db *sql.Conn, sessionID protocol.SessionID) (SessionContextStats, error)

ReadSessionContextStats returns the latest context token usage, compaction status, and active-run status for a session.

type SessionLeftover

type SessionLeftover struct {
	Session  protocol.SessionID
	Worktree protocol.Worktree
}

SessionLeftover is the worktree a removed session leaves without a user.

func ReadSessionLeftovers

func ReadSessionLeftovers(ctx context.Context, db *sql.Conn, sessions []protocol.SessionID) ([]SessionLeftover, error)

ReadSessionLeftovers reports, for each of sessions that is removed, the worktrees it used, now or in an earlier revision, that no remaining session uses or used. A main worktree and one whose removal is already recorded are never a leftover.

type Store

type Store struct {
	Node      *Handle
	Knowledge *Handle
	NodeID    protocol.NodeID
	Profile   string
	// contains filtered or unexported fields
}

func Open

func Open(ctx context.Context, profile string, node protocol.NodeID) (*Store, error)

Open is called only by the owner of the profile's advisory lock.

func OpenWithSchema

func OpenWithSchema(ctx context.Context, profile string, node protocol.NodeID, extraDDL ...string) (_ *Store, failure error)

OpenWithSchema opens the profile store and includes any additional module SQLite DDL statements in node.turso's schema creation, upgrade, and audit.

func (*Store) Close

func (storage *Store) Close() error

func (*Store) CloseIdle

func (storage *Store) CloseIdle() error

CloseIdle closes each database that no read or write is using.

func (*Store) OpenAllModuleDBs

func (storage *Store) OpenAllModuleDBs(ctx context.Context) ([]*Handle, error)

OpenAllModuleDBs opens any valid on-disk module databases under <profile>/storage/modules/*.turso that have not yet been opened and returns all module database handles in deterministic namespace order.

func (*Store) OpenModuleDB

func (storage *Store) OpenModuleDB(ctx context.Context, namespace string) (*Handle, error)

OpenModuleDB opens or returns the cached Turso/SQLite handle dedicated to a native module under <profile>/storage/modules/<namespace>.turso.

type SubagentListOptions added in v0.2.3

type SubagentListOptions struct {
	Before *string `json:"before"`
	Limit  *uint16 `json:"limit"`
}

type SubagentPage added in v0.2.3

type SubagentPage struct {
	Subagents  []SubagentSummary `json:"subagents"`
	NextBefore *string           `json:"next_before"`
}

func ListSubagents added in v0.2.3

func ListSubagents(ctx context.Context, db *sql.Conn, parent protocol.TurnID, options SubagentListOptions) (SubagentPage, error)

ListSubagents pages by immutable session creation order, not by the execution currently selected for that session. Only its founding delegation grants a parent access; follow-ups across parent turns do not create new entries.

type SubagentSummary added in v0.2.3

type SubagentSummary struct {
	Session    protocol.SessionID          `json:"session"`
	Turn       protocol.TurnID             `json:"turn"`
	Title      string                      `json:"title,omitempty"`
	Role       *subagentRole               `json:"role,omitempty"`
	Status     protocol.ConversationStatus `json:"status"`
	Paused     bool                        `json:"paused,omitempty"`
	StopReason string                      `json:"stop_reason,omitempty"`
}

type TaskDeliveryPost

type TaskDeliveryPost struct {
	ExternalSender *protocol.ConversationExternalSender
	Session        protocol.SessionID
	DedupKey       string
	Speaker        string
	SpeakerRole    *protocol.RoleID
	Text           string
}

TaskDeliveryPost describes a signed, idempotent canonical assistant message posted to an existing conversation without queueing or invoking a model.

type TaskWorktreeRequired

type TaskWorktreeRequired struct{ Source ProjectWorktree }

TaskWorktreeRequired asks the caller to prepare a checkout outside the SQL writer, then re-enter admission to recheck the same request and register it.

func (*TaskWorktreeRequired) Error

func (*TaskWorktreeRequired) Error() string

type ToolPresentationLookup

type ToolPresentationLookup func(name string) (protocol.ToolPresentation, protocol.ToolGrouping, *protocol.ToolDisplay, bool)

ToolPresentationLookup resolves presentation metadata for assembled native module tools (by canonical name or superseded legacy plugin alias).

type TurnFacts

type TurnFacts struct {
	// Usage is the turn's own model usage plus that of the children it
	// delegated; SessionUsage is the same for every turn of the session.
	Usage        TurnTokens
	SessionUsage TurnTokens
	// Running counts background work that will start a notice turn when it
	// ends; Pending counts ended results no turn has taken yet.
	Running int
	Pending int
	Chain   AutomaticChain
}

TurnFacts is what a session's stored state says once a turn has ended. A package loop decides from it whether to continue, wait or pause.

func ReadTurnFacts

func ReadTurnFacts(ctx context.Context, db *sql.Conn, session protocol.SessionID, turn protocol.TurnID) (TurnFacts, error)

ReadTurnFacts reads the facts of an ended turn in the caller's transaction. Usage follows the statistics selection: Sailry's own turns and the child turns delegated from them.

type TurnTokens

type TurnTokens struct {
	Input       uint64 `json:"input"`
	Output      uint64 `json:"output"`
	CachedInput uint64 `json:"cached_input"`
	Reasoning   uint64 `json:"reasoning"`
}

TurnTokens totals usage with a reported input and output pair. Cached input and reasoning are parts of Input and Output, not additions to them.

type WakeMissedPolicy

type WakeMissedPolicy string

WakeMissedPolicy controls what happens when a module wake schedule fires late after the Node was stopped or asleep.

const (
	WakeMissedSkip     WakeMissedPolicy = "skip"
	WakeMissedCoalesce WakeMissedPolicy = "coalesce"
)

type WakeSchedule

type WakeSchedule struct {
	Key      string // module-chosen, e.g. "brief/<project>"
	Revision uint64
	Enabled  bool
	Topic    string
	Payload  json.RawMessage
	Timing   protocol.DispatchTiming // reuse once/every/weekly
	Missed   WakeMissedPolicy        // "skip" | "coalesce" (default coalesce: one catch-up run)
	NextMs   *int64                  // read-only
}

WakeSchedule describes one module-owned durable wake schedule stored in the module's native dispatch namespace.

func ListNativeWakeSchedules

func ListNativeWakeSchedules(ctx context.Context, db *sql.Conn, namespace, prefix string) ([]WakeSchedule, error)

ListNativeWakeSchedules lists module-owned wake schedules in namespace whose Key starts with prefix (or all schedules when prefix is empty).

func SetNativeWakeSchedule

func SetNativeWakeSchedule(ctx context.Context, db *sql.Conn, namespace string, input WakeSchedule, timestamp int64) (WakeSchedule, []protocol.Event, error)

SetNativeWakeSchedule upserts one module-owned wake schedule keyed by (namespace, input.Key) with optimistic revision checking.

Source Files

Jump to

Keyboard shortcuts

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