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 contactedFlow
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 = providerid); never part ofAIProviderConfig.SecretValue,HTTPRequestand 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.
AIClientaccepts onlyApprovedPreview, which can only come fromConsentGate.approve(_:)applied to aContextPreview, which can only come fromContextPreview.make(redaction + policy). None of these types has a public initializer. The user message sent ispreview.payloadTextverbatim;byteCountis the size of the non-streaming JSON body. - Local-only.
NetworkPolicy(localOnly: true)accepts only the literalslocalhost,127.0.0.0/8and::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. Plainhttpto a non-loopback host is refused unlessallowsInsecureRemoteHTTPis set. - Execution. The assistant produces
ProposedCommandonly; its risk is computed in the initializer.ApprovedCommandhas no public initializer. Destructive, privilege-escalating, network-transfer and multi-host proposals require.reinforced(typedPhrase:)matchingconfirmationPhrase(for:). - Agent CLIs.
AgentCLICatalogonly tests for executables through the injected closure. It never launches a tool or reads its configuration or credentials.
Limits
SecretRedactoris 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 asadditionalSecretsto mask them literally.CommandRiskAnalyzeris a static lexer, not a shell. It does not expand variables, aliases, functions or globs, and does not follow scripts..safemeans "no known risk pattern", not "harmless". Multi-host input adds.multiHostand raises the level one step.KeychainSecretStoresetskSecAttrAccessibleWhenUnlockedThisDeviceOnly; 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; bodymodel,max_tokens,system,messages), OpenAIPOST {base}/v1/chat/completions(Authorization: Bearer;max_completion_tokensfor.openAI,max_tokensfor.openAICompatible). A base URL ending in/v1is accepted. Single-turn text only: no tools, no conversation history.