Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion docs/extension-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,25 @@ end)

Lifecycle payloads are intentionally bounded. `message_append` includes the appended entry text and metadata for the current message, but lifecycle events do not include full transcript history.

`context_build` is the first lifecycle seam with a mutation contract. Handlers may return bounded `contributions` entries. Each contribution must include non-empty `content` and is capped by the host. The context payload exposes `breakdown.system`, `breakdown.skills`, `breakdown.history`, and `breakdown.extensions` token estimates so extensions can reason about context budget without seeing the full transcript.
`context_build` has a bounded mutation contract. Handlers may return `contributions` entries. Each contribution must include non-empty `content` and is capped by the host. The context payload exposes `breakdown.system`, `breakdown.skills`, `breakdown.history`, and `breakdown.extensions` token estimates so extensions can reason about context budget without seeing the full transcript.

`before_provider_request` has a conservative mutation contract. The payload exposes request metadata, a redacted header map, and a provider `payload` object. Handlers may return a modified `payload` and `provider_request.headers` for non-sensitive headers:

```lua
lc.on("before_provider_request", function(event)
event.payload.payload.metadata = "debug-marker"
return {
payload = event.payload,
provider_request = {
headers = {
["X-Debug-Run"] = "local",
},
},
}
end)
```

Sensitive headers such as `Authorization`, `x-api-key`, `cookie`, and `proxy-authorization` are redacted in payloads and cannot be modified by provider hooks.

## Current limitations

Expand Down
15 changes: 10 additions & 5 deletions internal/assistant/anthropic.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ func anthropicPayload(request *CompletionRequest, messages []map[string]any) map
// reasoning is available. Match production agent clients by omitting
// temperature unless/until librecode exposes an explicit user setting.
payload := map[string]any{
jsonModelKey: request.Model.ID,
"max_tokens": minPositive(request.Model.MaxTokens, 4096),
"messages": messages,
"tools": anthropicTools(request),
jsonModelKey: request.Model.ID,
"max_tokens": minPositive(request.Model.MaxTokens, 4096),
jsonMessagesKey: messages,
"tools": anthropicTools(request),
}
if usesAnthropicOAuth(request) {
payload["system"] = anthropicOAuthSystemPrompt(request.SystemPrompt)
Expand Down Expand Up @@ -282,7 +282,12 @@ func (client *HTTPCompletionClient) requestAnthropic(
request *CompletionRequest,
payload map[string]any,
) (*providerResult, error) {
content, err := client.postJSON(ctx, endpoint, anthropicHeaders(request), payload)
headers := anthropicHeaders(request)
providerRequest, err := applyProviderRequestHook(ctx, request, payload, headers)
if err != nil {
return nil, err
}
content, err := client.postJSON(ctx, endpoint, providerRequest.Headers, providerRequest.Payload)
if err != nil {
return nil, err
}
Expand Down
25 changes: 14 additions & 11 deletions internal/assistant/anthropic_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,17 +191,19 @@ func testCompletionRequestAuth(args ...string) *CompletionRequest {
}

return &CompletionRequest{
OnEvent: nil,
OnToolCall: nil,
OnToolResult: nil,
ToolRegistry: nil,
SessionID: "",
SystemPrompt: "",
ThinkingLevel: "",
CWD: "",
Auth: testRequestAuth(apiKey),
Messages: nil,
Usage: model.EmptyTokenUsage(),
OnEvent: nil,
OnProviderObserve: nil,
OnProviderRequest: nil,
OnToolCall: nil,
OnToolResult: nil,
ToolRegistry: nil,
SessionID: "",
SystemPrompt: "",
ThinkingLevel: "",
CWD: "",
Auth: testRequestAuth(apiKey),
Messages: nil,
Usage: model.EmptyTokenUsage(),
Model: model.Model{
ThinkingLevelMap: nil,
Headers: nil,
Expand All @@ -217,6 +219,7 @@ func testCompletionRequestAuth(args ...string) *CompletionRequest {
MaxTokens: 0,
Reasoning: false,
},
ProviderAttempt: 0,
}
}

Expand Down
29 changes: 17 additions & 12 deletions internal/assistant/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ const (
jsonUserRole = "user"
jsonAssistantRole = "assistant"
jsonToolRole = "tool"
jsonSystemRole = "system"
jsonMessagesKey = "messages"
jsonCommandKey = "command"
jsonBreakdownKey = "breakdown"
jsonReadToolName = "read"
Expand Down Expand Up @@ -83,18 +85,21 @@ const (

// CompletionRequest describes one model completion request.
type CompletionRequest struct {
OnEvent func(StreamEvent) `json:"-"`
OnToolCall func(context.Context, ToolCallEvent) `json:"-"`
OnToolResult func(context.Context, *ToolEvent) `json:"-"`
ToolRegistry *tool.Registry `json:"-"`
SessionID string `json:"session_id"`
SystemPrompt string `json:"system_prompt"`
ThinkingLevel string `json:"thinking_level"`
CWD string `json:"cwd"`
Auth model.RequestAuth `json:"auth"`
Messages []database.MessageEntity `json:"messages"`
Usage model.TokenUsage `json:"usage"`
Model model.Model `json:"model"`
OnEvent func(StreamEvent) `json:"-"`
OnProviderObserve func(context.Context, *CompletionRequest, int) `json:"-"`
OnProviderRequest ProviderRequestHook `json:"-"`
OnToolCall func(context.Context, ToolCallEvent) `json:"-"`
OnToolResult func(context.Context, *ToolEvent) `json:"-"`
ToolRegistry *tool.Registry `json:"-"`
SessionID string `json:"session_id"`
SystemPrompt string `json:"system_prompt"`
ThinkingLevel string `json:"thinking_level"`
CWD string `json:"cwd"`
Auth model.RequestAuth `json:"auth"`
Messages []database.MessageEntity `json:"messages"`
Usage model.TokenUsage `json:"usage"`
Model model.Model `json:"model"`
ProviderAttempt int `json:"-"`
}

// CompletionResult is a provider response plus model-visible side effects.
Expand Down
8 changes: 4 additions & 4 deletions internal/assistant/context_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,10 +246,10 @@ func contextBreakdown(
contributions []contextContribution,
) map[string]int {
breakdown := map[string]int{
"system": systemTokens,
"skills": skillTokens,
"history": historyTokens,
"extensions": 0,
jsonSystemRole: systemTokens,
"skills": skillTokens,
"history": historyTokens,
"extensions": 0,
}
for index := range contributions {
breakdown["extensions"] += contributions[index].Tokens
Expand Down
15 changes: 8 additions & 7 deletions internal/assistant/lifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,14 @@ func (runtime *Runtime) dispatchLifecycle(
runtime.emit(ctx, string(name), payload)
if runtime.extensions == nil {
return extension.LifecycleDispatchResult{
Payload: cloneAnyMap(payload),
Name: string(name),
Errors: []string{},
Duration: 0,
HandlerCount: 0,
Consumed: false,
Stopped: false,
Payload: cloneAnyMap(payload),
ProviderRequest: extension.ProviderRequestMutation{Headers: map[string]string{}},
Name: string(name),
Errors: []string{},
Duration: 0,
HandlerCount: 0,
Consumed: false,
Stopped: false,
}, nil
}
result, err := runtime.extensions.DispatchLifecycle(ctx, extension.LifecycleEvent{
Expand Down
11 changes: 8 additions & 3 deletions internal/assistant/openai_chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ func (client *HTTPCompletionClient) advanceOpenAIChatLoop(
state *openAIChatLoopState,
) (bool, error) {
payload := openAIChatPayload(request, state.messages)
content, err := client.postJSON(ctx, state.endpoint, openAIHeaders(request), payload)
headers := openAIHeaders(request)
providerRequest, err := applyProviderRequestHook(ctx, request, payload, headers)
if err != nil {
return false, err
}
content, err := client.postJSON(ctx, state.endpoint, providerRequest.Headers, providerRequest.Payload)
if err != nil {
return false, err
}
Expand Down Expand Up @@ -114,7 +119,7 @@ func appendOpenAIChatToolConversation(state *openAIChatLoopState, result *provid
func openAIChatPayload(request *CompletionRequest, messages []map[string]any) map[string]any {
payload := map[string]any{
jsonModelKey: request.Model.ID,
"messages": messages,
jsonMessagesKey: messages,
"stream": false,
"temperature": 0.2,
"tools": openAIChatTools(request),
Expand Down Expand Up @@ -181,7 +186,7 @@ func parseOpenAIChatResult(content []byte) (*providerResult, error) {
func openAIChatMessages(request *CompletionRequest) []map[string]any {
messages := []map[string]any{}
if request.SystemPrompt != "" {
messages = append(messages, map[string]any{jsonRoleKey: "system", jsonContentKey: request.SystemPrompt})
messages = append(messages, map[string]any{jsonRoleKey: jsonSystemRole, jsonContentKey: request.SystemPrompt})
}
for _, message := range request.Messages {
role, ok := openAIRole(message.Role)
Expand Down
13 changes: 12 additions & 1 deletion internal/assistant/openai_responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,18 @@ func (client *HTTPCompletionClient) completeResponsesLoop(
result := &CompletionResult{Text: "", Thinking: nil, ToolEvents: nil, Usage: model.EmptyTokenUsage()}
for {
payload := responsesPayload(request, input, stream)
providerResult, err := client.requestResponses(ctx, endpoint, headers, payload, stream, request.OnEvent)
providerRequest, err := applyProviderRequestHook(ctx, request, payload, cloneStringMap(headers))
if err != nil {
return nil, err
}
providerResult, err := client.requestResponses(
ctx,
endpoint,
providerRequest.Headers,
providerRequest.Payload,
stream,
request.OnEvent,
)
if err != nil {
return nil, err
}
Expand Down
Loading
Loading