SPB Git

Repository Public

README.md 6.0 KB

# SPIntelligence

Optional, bring-your-own-key assistant for SP Term. One library product, AIAssistant (Swift 6 language mode, macOS 14+, no dependencies). The module is mostly guard rails: nothing leaves the machine and nothing is executable without an explicit, typed approval step.

text
swift build
swift test      # mock transport only; no provider is ever contacted

# Flow

swift
// 1. Configuration (persistable, never contains the key) and key storage
let provider = AIProviderConfig(kind: .anthropic)                 // model "claude-sonnet-5-5", free string
let secrets = KeychainSecretStore()                               // service "ai.spboucher.spterm.ai"
try secrets.setSecret(SecretValue(typedKey), for: provider.id)

// 2. Preview: redacted payload + destination, policy checked, no I/O
let policy = NetworkPolicy(localOnly: false)
let preview = try ContextPreview.make(
    mode: .explain,
    context: AIContext(question: "Why did this fail?", selectedText: selection, workingDirectory: cwd, host: host, shell: "zsh"),
    provider: provider, policy: policy)
// show preview.providerLabel / destinationHost / model / systemPrompt / payloadText / findings / byteCount

// 3. Send only what was approved
let approved = ConsentGate().approve(preview)                     // after the user clicks "Send"
let client = AIClient(secrets: secrets, policy: policy)
let answer = try await client.send(approved)                      // or: for try await delta in client.stream(approved)

// 4. Commands are proposals until the user confirms
for proposal in answer.proposedCommands(workingDirectory: cwd, host: host) {
    let gate = ConsentGate()
    switch gate.requirement(for: proposal) {
    case .standard:   let cmd = try gate.approve(proposal, with: .standard)
    case .reinforced: let cmd = try gate.approve(proposal, with: .reinforced(typedPhrase: typed)) // gate.confirmationPhrase(for:)
    }
    // only an ApprovedCommand may reach the PTY
}

// Broadcast-input protection (cheap, synchronous)
let level = CommandRiskAnalyzer.level(ofLine: line, isMultiHost: true)

# API

Area Types
Providers AIProviderKind (.anthropic, .openAI, .openAICompatible), AIProviderConfig (Codable: id, kind, label, baseURL, model)
Secrets SecretValue (redacted descriptions, reveal()), SecretStore, KeychainSecretStore, InMemorySecretStore, SecretStoreError
Redaction SecretRedactor.redact(_:) -> RedactionResult (text, findings: [RedactionFinding]), SecretKind
Risk CommandRiskAnalyzer.assess(_:isMultiHost:) -> RiskAssessment (level, findings, reasons, explanations, requiresReinforcedConfirmation), CommandRiskAnalyzer.level(ofLine:isMultiHost:), RiskLevel, RiskReason, RiskFinding
Context AIMode (systemPrompt), AIContext, NetworkPolicy / NetworkPolicyError, ContextPreview.make(...), ApprovedPreview
Consent ProposedCommand, UserConfirmation, ConsentRequirement, ConsentGate, ApprovedCommand, ConsentError
Client AIClient.send(_:), AIClient.stream(_:), AIResponse, AIUsage, AIClientError, AIAPIError, HTTPTransport, HTTPRequest, HTTPResponse, HTTPStreamResponse, URLSessionTransport
Helpers extractCommands(fromMarkdown:), AgentCLICatalog, AgentCLI, DetectedAgentCLI

# Guarantees

  • Keys. Stored only in a SecretStore (account = provider id); never part of AIProviderConfig. SecretValue, HTTPRequest and every error type print without the key; provider and transport error messages are passed through the redactor (plus the literal key) before being thrown.
  • Preview before send. AIClient accepts only ApprovedPreview, which can only come from ConsentGate.approve(_:) applied to a ContextPreview, which can only come from ContextPreview.make (redaction + policy). None of these types has a public initializer. The user message sent is preview.payloadText verbatim; byteCount is the size of the non-streaming JSON body.
  • Local-only. NetworkPolicy(localOnly: true) accepts only the literals localhost, 127.0.0.0/8 and ::1, with no DNS resolution. It is checked when the preview is built and again by the client before the key is read or the transport is called. Plain http to a non-loopback host is refused unless allowsInsecureRemoteHTTP is set.
  • Execution. The assistant produces ProposedCommand only; its risk is computed in the initializer. ApprovedCommand has no public initializer. Destructive, privilege-escalating, network-transfer and multi-host proposals require .reinforced(typedPhrase:) matching confirmationPhrase(for:).
  • Agent CLIs. AgentCLICatalog only tests for executables through the injected closure. It never launches a tool or reads its configuration or credentials.

# Limits

  • SecretRedactor is pattern based and biased towards over-masking. It is a safety net, not a proof: a secret with no recognisable shape and no telltale key name passes through. Pass the stored keys as additionalSecrets to mask them literally.
  • CommandRiskAnalyzer is a static lexer, not a shell. It does not expand variables, aliases, functions or globs, and does not follow scripts. .safe means "no known risk pattern", not "harmless". Multi-host input adds .multiHost and raises the level one step.
  • KeychainSecretStore sets kSecAttrAccessibleWhenUnlockedThisDeviceOnly; macOS enforces that attribute only in the data-protection keychain (useDataProtectionKeychain: true, which needs a signed app with a keychain access group). With the default login keychain the item is protected by the keychain's own ACL.
  • Wire format: Anthropic POST {base}/v1/messages (x-api-key, anthropic-version: 2023-06-01; body model, max_tokens, system, messages), OpenAI POST {base}/v1/chat/completions (Authorization: Bearer; max_completion_tokens for .openAI, max_tokens for .openAICompatible). A base URL ending in /v1 is accepted. Single-turn text only: no tools, no conversation history.
Files main
Menu

Theme