Skip to content
Draft
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
42 changes: 42 additions & 0 deletions agent/chatgpt_guard.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package agent

import (
"context"
"errors"
"iter"
"strings"

"github.com/Autumn-27/norma/llm"
)

// A ChatGPT-plan carrier is private Responses state, not Anthropic thinking.
// Other providers must fail rather than silently discard it or send it as a
// different provider's opaque data after a profile switch or failover.
var errForeignPlanState = errors.New("conversation contains ChatGPT plan state; use the same profile or start a new conversation")

func hasPlanState(req llm.CompletionRequest) bool {
for _, msg := range req.Messages {
for _, block := range msg.Content {
if block.Type == llm.BlockRedactedThinking && strings.HasPrefix(block.Data, planCarrier) {
return true
}
}
}
return false
}

type foreignPlanGuard struct{ inner llm.Provider }

func (g foreignPlanGuard) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
if hasPlanState(req) {
return func(yield func(llm.StreamEvent, error) bool) { yield(llm.StreamEvent{}, errForeignPlanState) }
}
return g.inner.Stream(ctx, req)
}

func (g foreignPlanGuard) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
if hasPlanState(req) {
return llm.Message{}, "", llm.Usage{}, errForeignPlanState
}
return g.inner.Complete(ctx, req)
}
39 changes: 39 additions & 0 deletions agent/chatgpt_guard_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package agent

import (
"context"
"iter"
"testing"

"github.com/Autumn-27/norma/llm"
)

type guardProbe struct{ calls int }

func (p *guardProbe) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
p.calls++
return func(func(llm.StreamEvent, error) bool) {}
}
func (p *guardProbe) Complete(context.Context, llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
p.calls++
return llm.Message{}, "", llm.Usage{}, nil
}

func TestForeignPlanStateIsNotSentToOtherProviders(t *testing.T) {
inner := &guardProbe{}
p := foreignPlanGuard{inner: inner}
req := llm.CompletionRequest{Messages: []llm.Message{{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockRedactedThinking, Data: planCarrier + `{}`}}}}}
if _, _, _, err := p.Complete(context.Background(), req); err == nil {
t.Fatal("Complete accepted foreign plan state")
}
var gotErr error
for _, err := range p.Stream(context.Background(), req) {
gotErr = err
}
if gotErr == nil || inner.calls != 0 {
t.Fatalf("Stream error=%v, delegated calls=%d", gotErr, inner.calls)
}
if _, _, _, err := p.Complete(context.Background(), llm.CompletionRequest{}); err != nil || inner.calls != 1 {
t.Fatalf("ordinary request: error=%v, delegated calls=%d", err, inner.calls)
}
}
307 changes: 307 additions & 0 deletions agent/chatgpt_plan_provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,307 @@
package agent

// This isolated bridge is not wired into ARTEX. Before enabling it, every other
// provider (including pool members) must reject the tagged blocks below, and
// compaction and all alternate context views must be audited for their handling.
// The carrier is provider-private state, not Anthropic redacted thinking.
// The host must reject explicitly configured output caps before constructing this
// provider. Norma supplies internal limits for ordinary requests and compaction;
// all nonnegative limits are omitted on the wire and therefore unenforced.
// Compaction's "disabled" thinking override is accepted but not sent: this
// protocol cannot guarantee reasoning is disabled. Other overrides are rejected.
// The host UI and profile must disclose that neither output caps nor a thinking
// switch can be enforced for this provider.
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"iter"
"strings"

"github.com/Autumn-27/artex/chatgptplan"
"github.com/Autumn-27/norma/llm"
)

const planCarrier = "artex.chatgptplan.item.v1:"
const planNamespace = "artex"

type ChatGPTPlanProvider struct {
Client chatgptplan.Client
Model string
AccountID string // Stable account registration ID; binds opaque replay to its origin.
Token func(context.Context) (string, error)
}

// planItemToBlock validates the subset that the neutral model can faithfully
// represent. The complete raw item is retained separately for exact replay.
func planItemToBlock(raw json.RawMessage) (*llm.ContentBlock, error) {
var x struct {
Type string `json:"type"`
Role string `json:"role"`
Namespace string `json:"namespace"`
Name string `json:"name"`
CallID string `json:"call_id"`
Arguments string `json:"arguments"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
Refusal string `json:"refusal"`
} `json:"content"`
}
if json.Unmarshal(raw, &x) != nil {
return nil, errors.New("chatgptplan bridge: invalid output item")
}
switch x.Type {
case "reasoning":
return nil, nil
case "message":
if x.Role != "assistant" || len(x.Content) != 1 || (x.Content[0].Type != "output_text" && x.Content[0].Type != "refusal") {
return nil, errors.New("chatgptplan bridge: unsupported output message")
}
text := x.Content[0].Text
if x.Content[0].Type == "refusal" {
text = x.Content[0].Refusal
}
b := llm.TextBlock(text)
if b.Text == "" {
return nil, errors.New("chatgptplan bridge: empty output text")
}
return &b, nil
case "function_call":
if x.Namespace != planNamespace || x.Name == "" || x.CallID == "" || !json.Valid([]byte(x.Arguments)) {
return nil, errors.New("chatgptplan bridge: invalid function call")
}
var obj map[string]json.RawMessage
if json.Unmarshal([]byte(x.Arguments), &obj) != nil || obj == nil {
return nil, errors.New("chatgptplan bridge: tool arguments must be an object")
}
return &llm.ContentBlock{Type: llm.BlockToolUse, ID: x.CallID, Name: x.Name, Input: json.RawMessage(strings.TrimSpace(x.Arguments))}, nil
default:
return nil, fmt.Errorf("chatgptplan bridge: unsupported output item %q", x.Type)
}
}
func planEqualBlock(a, b llm.ContentBlock) bool {
if a.Type != b.Type {
return false
}
switch a.Type {
case llm.BlockText:
return a.Text == b.Text
case llm.BlockToolUse:
return a.ID == b.ID && a.Name == b.Name && string(a.Input) == string(b.Input) && a.ThoughtSignature == ""
}
return false
}
func planAccountCarrier(accountID string) string {
return planCarrier + base64.RawURLEncoding.EncodeToString([]byte(accountID)) + ":"
}
func planInput(req llm.CompletionRequest, accountID string) ([]any, error) {
var out []any
if len(req.System) > 0 {
out = append(out, map[string]any{"role": "developer", "content": strings.Join(req.System, "\n\n")})
}
calls := map[string]bool{}
results := map[string]bool{}
for _, m := range req.Messages {
if m.Role != llm.RoleAssistant && m.Role != llm.RoleUser {
return nil, errors.New("chatgptplan bridge: unsupported role")
}
for i := 0; i < len(m.Content); i++ {
b := m.Content[i]
if b.Type == llm.BlockRedactedThinking {
if m.Role != llm.RoleAssistant || !strings.HasPrefix(b.Data, planAccountCarrier(accountID)) {
return nil, errors.New("chatgptplan bridge: unsupported opaque block")
}
raw := json.RawMessage(strings.TrimPrefix(b.Data, planAccountCarrier(accountID)))
block, err := planItemToBlock(raw)
if err != nil {
return nil, err
}
if block != nil {
i++
if i >= len(m.Content) || !planEqualBlock(*block, m.Content[i]) {
return nil, errors.New("chatgptplan bridge: carrier mismatch or missing block")
}
if block.Type == llm.BlockToolUse {
if calls[block.ID] {
return nil, errors.New("chatgptplan bridge: duplicate call")
}
calls[block.ID] = true
}
}
out = append(out, raw)
continue
}
switch b.Type {
case llm.BlockText:
out = append(out, map[string]any{"role": string(m.Role), "content": b.Text})
case llm.BlockToolResult:
if m.Role != llm.RoleUser || b.ToolUseID == "" || !calls[b.ToolUseID] || results[b.ToolUseID] {
return nil, errors.New("chatgptplan bridge: invalid tool result")
}
var s strings.Builder
for _, c := range b.Content {
if c.Type != llm.BlockText {
return nil, errors.New("chatgptplan bridge: unsupported tool result")
}
s.WriteString(c.Text)
}
results[b.ToolUseID] = true
output := s.String()
if b.IsError {
output = "Tool execution error:\n" + output
}
out = append(out, map[string]any{"type": "function_call_output", "call_id": b.ToolUseID, "output": output})
default:
return nil, errors.New("chatgptplan bridge: unsupported untagged block")
}
}
}
for id := range calls {
if !results[id] {
return nil, errors.New("chatgptplan bridge: unpaired call")
}
}
for id := range results {
if !calls[id] {
return nil, errors.New("chatgptplan bridge: unpaired result")
}
}
if out == nil {
out = []any{}
}
return out, nil
}
func (p *ChatGPTPlanProvider) completion(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
fail := func(e error) (llm.Message, string, llm.Usage, error) { return llm.Message{}, "", llm.Usage{}, e }
if p.Token == nil || p.Model == "" || p.AccountID == "" {
return fail(errors.New("chatgptplan bridge: missing token callback, model, or account ID"))
}
if req.Temperature != nil || len(req.Stop) > 0 || req.MaxTokens < 0 || (req.Thinking != "" && req.Thinking != "disabled") {
return fail(errors.New("chatgptplan bridge: unsupported request options"))
}
input, err := planInput(req, p.AccountID)
if err != nil {
return fail(err)
}
body := map[string]any{"model": p.Model, "input": input}
names := map[string]bool{}
if len(req.Tools) > 0 {
tools := make([]any, 0, len(req.Tools))
for _, t := range req.Tools {
if t.Name == "" || names[t.Name] {
return fail(errors.New("chatgptplan bridge: invalid tool schema"))
}
names[t.Name] = true
tools = append(tools, map[string]any{"type": "function", "name": t.Name, "description": t.Description, "parameters": t.InputSchema})
}
body["tools"] = []any{map[string]any{"type": "namespace", "name": planNamespace, "description": "ARTEX tools", "tools": tools}}
}
raw, err := json.Marshal(body)
if err != nil {
return fail(err)
}
token, err := p.Token(ctx)
if err != nil {
return fail(err)
}
result, err := p.Client.Stream(ctx, token, raw, nil)
if err != nil {
return fail(err)
}
msg := llm.Message{Role: llm.RoleAssistant}
stop := "end_turn"
seen := map[string]bool{}
// Inspect the entire completed response before exposing any tool calls.
refusal := false
for _, item := range result.Output {
var x struct {
Type string `json:"type"`
Content []struct {
Type string `json:"type"`
} `json:"content"`
}
if json.Unmarshal(item, &x) != nil {
return fail(errors.New("chatgptplan bridge: invalid output item"))
}
if x.Type == "message" {
for _, c := range x.Content {
if c.Type == "refusal" {
refusal = true
}
}
}
}
for _, item := range result.Output {
block, e := planItemToBlock(item)
if e != nil {
return fail(e)
}
if block != nil && block.Type == llm.BlockToolUse {
if !names[block.Name] || seen[block.ID] {
return fail(errors.New("chatgptplan bridge: unknown or duplicate tool call"))
}
seen[block.ID] = true
if refusal {
continue
}
stop = "tool_use"
}
msg.Content = append(msg.Content, llm.ContentBlock{Type: llm.BlockRedactedThinking, Data: planAccountCarrier(p.AccountID) + string(item)})
if block != nil {
msg.Content = append(msg.Content, *block)
}
}
if refusal {
stop = "refusal"
}
var response struct {
Usage struct {
Input int `json:"input_tokens"`
Output int `json:"output_tokens"`
InputDetails struct {
Cached int `json:"cached_tokens"`
} `json:"input_tokens_details"`
} `json:"usage"`
}
if json.Unmarshal(result.Response, &response) != nil {
return fail(errors.New("chatgptplan bridge: invalid response"))
}
usage := llm.Usage{InputTokens: response.Usage.Input, OutputTokens: response.Usage.Output, CacheReadTokens: response.Usage.InputDetails.Cached}
return msg, stop, usage, nil
}
func (p *ChatGPTPlanProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
return p.completion(ctx, req)
}
func (p *ChatGPTPlanProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
msg, stop, usage, err := p.completion(ctx, req)
if err != nil {
yield(llm.StreamEvent{}, err)
return
}
for _, b := range msg.Content {
var ev llm.StreamEvent
switch b.Type {
case llm.BlockRedactedThinking:
ev = llm.StreamEvent{Type: llm.SERedactedThinking, Text: b.Data}
case llm.BlockText:
ev = llm.StreamEvent{Type: llm.SETextDelta, Text: b.Text}
case llm.BlockToolUse:
if !yield(llm.StreamEvent{Type: llm.SEToolUseStart, ToolID: b.ID, ToolName: b.Name}, nil) {
return
}
ev = llm.StreamEvent{Type: llm.SEToolInputJSON, Text: string(b.Input)}
}
if !yield(ev, nil) {
return
}
}
if !yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: stop, Usage: usage}, nil) {
return
}
yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil)
}
}
Loading
Loading