SPB Git

Repository Public

README.md 6.0 KB 94 lines markdown

1# SPIntelligence23Optional, bring-your-own-key assistant for SP Term. One library product, `AIAssistant`4(Swift 6 language mode, macOS 14+, no dependencies). The module is mostly guard rails:5nothing leaves the machine and nothing is executable without an explicit, typed approval step.67```8swift build9swift test      # mock transport only; no provider is ever contacted10```1112## Flow1314```swift15// 1. Configuration (persistable, never contains the key) and key storage16let provider = AIProviderConfig(kind: .anthropic)                 // model "claude-sonnet-5-5", free string17let secrets = KeychainSecretStore()                               // service "ai.spboucher.spterm.ai"18try secrets.setSecret(SecretValue(typedKey), for: provider.id)1920// 2. Preview: redacted payload + destination, policy checked, no I/O21let policy = NetworkPolicy(localOnly: false)22let preview = try ContextPreview.make(23    mode: .explain,24    context: AIContext(question: "Why did this fail?", selectedText: selection, workingDirectory: cwd, host: host, shell: "zsh"),25    provider: provider, policy: policy)26// show preview.providerLabel / destinationHost / model / systemPrompt / payloadText / findings / byteCount2728// 3. Send only what was approved29let approved = ConsentGate().approve(preview)                     // after the user clicks "Send"30let client = AIClient(secrets: secrets, policy: policy)31let answer = try await client.send(approved)                      // or: for try await delta in client.stream(approved)3233// 4. Commands are proposals until the user confirms34for proposal in answer.proposedCommands(workingDirectory: cwd, host: host) {35    let gate = ConsentGate()36    switch gate.requirement(for: proposal) {37    case .standard:   let cmd = try gate.approve(proposal, with: .standard)38    case .reinforced: let cmd = try gate.approve(proposal, with: .reinforced(typedPhrase: typed)) // gate.confirmationPhrase(for:)39    }40    // only an ApprovedCommand may reach the PTY41}4243// Broadcast-input protection (cheap, synchronous)44let level = CommandRiskAnalyzer.level(ofLine: line, isMultiHost: true)45```4647## API4849| Area | Types |50|---|---|51| Providers | `AIProviderKind` (`.anthropic`, `.openAI`, `.openAICompatible`), `AIProviderConfig` (Codable: `id`, `kind`, `label`, `baseURL`, `model`) |52| Secrets | `SecretValue` (redacted descriptions, `reveal()`), `SecretStore`, `KeychainSecretStore`, `InMemorySecretStore`, `SecretStoreError` |53| Redaction | `SecretRedactor.redact(_:) -> RedactionResult` (`text`, `findings: [RedactionFinding]`), `SecretKind` |54| Risk | `CommandRiskAnalyzer.assess(_:isMultiHost:) -> RiskAssessment` (`level`, `findings`, `reasons`, `explanations`, `requiresReinforcedConfirmation`), `CommandRiskAnalyzer.level(ofLine:isMultiHost:)`, `RiskLevel`, `RiskReason`, `RiskFinding` |55| Context | `AIMode` (`systemPrompt`), `AIContext`, `NetworkPolicy` / `NetworkPolicyError`, `ContextPreview.make(...)`, `ApprovedPreview` |56| Consent | `ProposedCommand`, `UserConfirmation`, `ConsentRequirement`, `ConsentGate`, `ApprovedCommand`, `ConsentError` |57| Client | `AIClient.send(_:)`, `AIClient.stream(_:)`, `AIResponse`, `AIUsage`, `AIClientError`, `AIAPIError`, `HTTPTransport`, `HTTPRequest`, `HTTPResponse`, `HTTPStreamResponse`, `URLSessionTransport` |58| Helpers | `extractCommands(fromMarkdown:)`, `AgentCLICatalog`, `AgentCLI`, `DetectedAgentCLI` |5960## Guarantees6162- **Keys.** Stored only in a `SecretStore` (account = provider `id`); never part of `AIProviderConfig`.63  `SecretValue`, `HTTPRequest` and every error type print without the key; provider and transport64  error messages are passed through the redactor (plus the literal key) before being thrown.65- **Preview before send.** `AIClient` accepts only `ApprovedPreview`, which can only come from66  `ConsentGate.approve(_:)` applied to a `ContextPreview`, which can only come from `ContextPreview.make`67  (redaction + policy). None of these types has a public initializer. The user message sent is68  `preview.payloadText` verbatim; `byteCount` is the size of the non-streaming JSON body.69- **Local-only.** `NetworkPolicy(localOnly: true)` accepts only the literals `localhost`, `127.0.0.0/8`70  and `::1`, with no DNS resolution. It is checked when the preview is built and again by the client71  before the key is read or the transport is called. Plain `http` to a non-loopback host is refused72  unless `allowsInsecureRemoteHTTP` is set.73- **Execution.** The assistant produces `ProposedCommand` only; its risk is computed in the initializer.74  `ApprovedCommand` has no public initializer. Destructive, privilege-escalating, network-transfer and75  multi-host proposals require `.reinforced(typedPhrase:)` matching `confirmationPhrase(for:)`.76- **Agent CLIs.** `AgentCLICatalog` only tests for executables through the injected closure.77  It never launches a tool or reads its configuration or credentials.7879## Limits8081- `SecretRedactor` is pattern based and biased towards over-masking. It is a safety net, not a proof:82  a secret with no recognisable shape and no telltale key name passes through. Pass the stored keys83  as `additionalSecrets` to mask them literally.84- `CommandRiskAnalyzer` is a static lexer, not a shell. It does not expand variables, aliases, functions85  or globs, and does not follow scripts. `.safe` means "no known risk pattern", not "harmless".86  Multi-host input adds `.multiHost` and raises the level one step.87- `KeychainSecretStore` sets `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; macOS enforces that attribute88  only in the data-protection keychain (`useDataProtectionKeychain: true`, which needs a signed app with89  a keychain access group). With the default login keychain the item is protected by the keychain's own ACL.90- Wire format: Anthropic `POST {base}/v1/messages` (`x-api-key`, `anthropic-version: 2023-06-01`;91  body `model`, `max_tokens`, `system`, `messages`), OpenAI `POST {base}/v1/chat/completions`92  (`Authorization: Bearer`; `max_completion_tokens` for `.openAI`, `max_tokens` for `.openAICompatible`).93  A base URL ending in `/v1` is accepted. Single-turn text only: no tools, no conversation history.94
Files main
Menu

Theme