DEV-000069 general agent delegation codex bridge foundation
CI / test (push) Successful in 20s
CI / test (pull_request) Successful in 20s

This commit is contained in:
m
2026-08-17 20:07:14 +03:00
parent d870e1361d
commit b3491520bd
21 changed files with 1914 additions and 20 deletions
+278
View File
@@ -107,6 +107,10 @@ func main() {
if err != nil {
log.Fatal(err)
}
attentionClient, err := newContinuityAttentionClient(envOr("CONTINUITY_RUNTIME_URL", "http://continuity-runtime:8081"), &http.Client{Timeout: 5 * time.Second})
if err != nil {
log.Fatal(err)
}
learning := learningRecorder{epistemics: epistemicsRepository, capability: capabilityRepository}
mux := http.NewServeMux()
authenticateCreator := func(w http.ResponseWriter, r *http.Request) (identity.CreatorSession, bool) {
@@ -327,6 +331,9 @@ func main() {
planningReply = responseResult.Reply
needsCognition = false
learning.recordReminderResponse(r.Context(), reminderResponseLearningInput{Utterance: utterance, Intent: intent, Result: responseResult, At: now})
if resumed, err := continueDelegationFromHumanResponse(r.Context(), workRepository, responseResult.Response, now); err == nil && resumed {
planningReply = "Принял. Продолжаю ту же задачу coding-agent без потери контекста."
}
} else if responseErr == nil && looksLikeUnsupportedContinuation(utterance.Content, responseResult) {
learning.recordFastPathDecline(r.Context(), fastPathDeclineLearningInput{Utterance: utterance, Intent: intent, Result: responseResult, Reason: declineReasonForResponse(responseResult), At: now})
}
@@ -365,6 +372,8 @@ func main() {
var capabilityStatus capability.CapabilityResolutionStatus
var capabilityKind capability.CapabilityKind
var capabilityGapID capability.CapabilityGapID
var delegationID work.DelegationID
var delegationState work.DelegationState
var reminder *continuity.ProspectiveItem
if helpPath.Kind == work.HelpPathDirectCapability && len(helpPath.SuggestedCapabilityKinds) > 0 {
capabilityKind = helpPath.SuggestedCapabilityKinds[0]
@@ -423,6 +432,18 @@ func main() {
planningReply = planning.Reply
workPlanned = true
needsCognition = false
if created, resolution, createErr := maybeCreateAgentDelegation(r.Context(), workRepository, capabilityRepository, session, conversation, intent, utterance, planning, now); createErr == nil && created != nil {
delegationID = created.Delegation.ID
delegationState = created.Delegation.State
capabilityKind = created.Delegation.CapabilityKind
capabilityStatus = resolution.Status
planningReply = "Понял задачу. Я собрал work item, выбрал coding-agent в CANARY-режиме и создал delegation. Буду вести её как отдельный run с checkpoint/resume, без потери исходного human intent."
} else if resolution.Gap != nil {
capabilityKind = resolution.Requirement.CapabilityKind
capabilityStatus = resolution.Status
capabilityGapID = resolution.Gap.ID
planningReply = planningReply + " Для coding delegation подходящий agent implementation сейчас недоступен, поэтому я сохранил план без ложного запуска."
}
}
response := interaction.ChatMessageResponse{
ConversationID: conversation.ID,
@@ -440,6 +461,8 @@ func main() {
CapabilityStatus: capabilityStatus,
CapabilityKind: capabilityKind,
CapabilityGapID: capabilityGapID,
DelegationID: string(delegationID),
DelegationState: string(delegationState),
Reminder: reminder,
}
w.Header().Set("Content-Type", "application/json")
@@ -447,6 +470,210 @@ func main() {
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(response)
})
mux.HandleFunc("GET /v1/creator/delegations/{id}", func(w http.ResponseWriter, r *http.Request) {
if _, ok := authenticateCreator(w, r); !ok {
return
}
value, err := workRepository.LoadDelegation(r.Context(), work.DelegationID(r.PathValue("id")))
if err != nil {
http.Error(w, "delegation not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(value)
})
mux.HandleFunc("GET /v1/creator/delegations/{id}/latest-checkpoint", func(w http.ResponseWriter, r *http.Request) {
if _, ok := authenticateCreator(w, r); !ok {
return
}
value, err := workRepository.LatestAgentCheckpoint(r.Context(), work.DelegationID(r.PathValue("id")))
if err != nil {
http.Error(w, "checkpoint not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(value)
})
mux.HandleFunc("POST /v1/creator/delegations/{id}/runs/{run}/checkpoints", func(w http.ResponseWriter, r *http.Request) {
session, ok := authenticateCreator(w, r)
if !ok {
return
}
var request struct {
BlockerClass work.AgentBlockerClass
CompletedSummary string
RemainingSummary string
TestSummary string
BranchName string
CommitHash string
NextStep string
ArtifactRefs []work.EvidenceRef
RecordedAtUnixMillis int64
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32<<10))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&request); err != nil {
http.Error(w, "invalid checkpoint", http.StatusBadRequest)
return
}
run, err := workRepository.LoadAgentRun(r.Context(), work.AgentRunID(r.PathValue("run")))
if err != nil || run.DelegationID != work.DelegationID(r.PathValue("id")) {
http.Error(w, "run not found", http.StatusNotFound)
return
}
updatedRun, checkpoint, err := workdomain.CheckpointRun(run, request.BlockerClass, request.CompletedSummary, request.RemainingSummary, request.TestSummary, request.BranchName, request.CommitHash, request.NextStep, request.ArtifactRefs, time.UnixMilli(request.RecordedAtUnixMillis))
if err != nil {
http.Error(w, "invalid checkpoint", http.StatusBadRequest)
return
}
if err := workRepository.SaveAgentCheckpoint(r.Context(), updatedRun, checkpoint); err != nil {
http.Error(w, "save checkpoint", http.StatusInternalServerError)
return
}
if request.BlockerClass == work.AgentBlockerHumanDecisionRequired {
delegation, err := workRepository.LoadDelegation(r.Context(), run.DelegationID)
if err == nil {
_, _ = attentionClient.Create(r.Context(), r.Header.Get("Authorization"), continuity.CreateAttentionRequest{
OwnerPrincipalID: session.PrincipalID,
ScopeID: authority.ScopeID("domovoy-global-scope"),
SourceKind: continuity.AttentionSourceAgentDelegation,
SourceExternalRef: delegationAttentionRef(delegation.ID),
Level: continuity.AttentionActionRequired,
Summary: "Нужен твой выбор по задаче coding-agent: " + firstNonEmpty(request.RemainingSummary, delegation.DesiredOutcome),
DueAtUnixMillis: checkpoint.RecordedAtUnixMillis,
CreatedAtUnixMillis: checkpoint.RecordedAtUnixMillis,
})
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(checkpoint)
})
mux.HandleFunc("POST /v1/creator/delegations/{id}/runs/{run}/results", func(w http.ResponseWriter, r *http.Request) {
if _, ok := authenticateCreator(w, r); !ok {
return
}
var request struct {
Summary string
OutcomeRef string
VerificationSummary string
ArtifactRefs []work.EvidenceRef
RecordedAtUnixMillis int64
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32<<10))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&request); err != nil {
http.Error(w, "invalid result", http.StatusBadRequest)
return
}
run, err := workRepository.LoadAgentRun(r.Context(), work.AgentRunID(r.PathValue("run")))
if err != nil || run.DelegationID != work.DelegationID(r.PathValue("id")) {
http.Error(w, "run not found", http.StatusNotFound)
return
}
updatedRun, result, err := workdomain.CompleteRun(run, request.Summary, request.OutcomeRef, request.VerificationSummary, request.ArtifactRefs, time.UnixMilli(request.RecordedAtUnixMillis))
if err != nil {
http.Error(w, "invalid result", http.StatusBadRequest)
return
}
if err := workRepository.SaveAgentResult(r.Context(), updatedRun, result); err != nil {
http.Error(w, "save result", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(result)
})
mux.HandleFunc("POST /v1/creator/delegations/{id}/resume", func(w http.ResponseWriter, r *http.Request) {
if _, ok := authenticateCreator(w, r); !ok {
return
}
delegation, err := workRepository.LoadDelegation(r.Context(), work.DelegationID(r.PathValue("id")))
if err != nil {
http.Error(w, "delegation not found", http.StatusNotFound)
return
}
run, err := workRepository.LoadAgentRun(r.Context(), delegation.LatestRunID)
if err != nil {
http.Error(w, "run not found", http.StatusNotFound)
return
}
checkpoint, err := workRepository.LatestAgentCheckpoint(r.Context(), delegation.ID)
if err != nil {
http.Error(w, "checkpoint not found", http.StatusNotFound)
return
}
updatedDelegation, resumedRun, err := workdomain.ResumeDelegationRun(delegation, run, checkpoint, time.Now())
if err != nil {
http.Error(w, "resume not allowed", http.StatusConflict)
return
}
if err := workRepository.SaveResumedRun(r.Context(), updatedDelegation, resumedRun); err != nil {
http.Error(w, "save resumed run", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(resumedRun)
})
mux.HandleFunc("POST /v1/creator/delegations/{id}/verify", func(w http.ResponseWriter, r *http.Request) {
if _, ok := authenticateCreator(w, r); !ok {
return
}
var request struct {
Verified bool
Summary string
EvidenceRefs []work.EvidenceRef
RecordedAtUnixMillis int64
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32<<10))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&request); err != nil || request.RecordedAtUnixMillis < 1 {
http.Error(w, "invalid verification", http.StatusBadRequest)
return
}
delegation, err := workRepository.LoadDelegation(r.Context(), work.DelegationID(r.PathValue("id")))
if err != nil {
http.Error(w, "delegation not found", http.StatusNotFound)
return
}
run, err := workRepository.LoadAgentRun(r.Context(), delegation.LatestRunID)
if err != nil {
http.Error(w, "run not found", http.StatusNotFound)
return
}
result, err := workRepository.LatestAgentResult(r.Context(), delegation.ID)
if err != nil {
http.Error(w, "result not found", http.StatusNotFound)
return
}
updatedDelegation, verification, err := workdomain.VerifyDelegationResult(delegation, run, result, request.Verified, request.Summary, request.EvidenceRefs, time.UnixMilli(request.RecordedAtUnixMillis))
if err != nil {
http.Error(w, "invalid verification", http.StatusBadRequest)
return
}
if err := workRepository.SaveDelegationVerification(r.Context(), updatedDelegation, verification); err != nil {
http.Error(w, "save verification", http.StatusInternalServerError)
return
}
runCount, _ := workRepository.CountAgentRuns(r.Context(), delegation.ID)
learning.recordDelegationOutcome(r.Context(), delegationLearningInput{
Intent: interaction.OriginalHumanIntent{ID: interaction.OriginalHumanIntentID(delegation.SourceIntentID), Text: delegation.DesiredOutcome},
Utterance: interaction.HumanUtterance{ID: interaction.HumanUtteranceID(delegation.SourceUtteranceID), Content: delegation.DesiredOutcome},
DelegationID: string(delegation.ID),
RunID: string(run.ID),
ImplementationID: run.ImplementationID,
OutcomeRef: result.OutcomeRef,
VerificationRefs: evidenceRefsToEpistemics(request.EvidenceRefs),
Verified: request.Verified,
ExecutionWindows: runCount,
HumanBlocked: false,
At: time.UnixMilli(request.RecordedAtUnixMillis),
})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(verification)
})
mux.HandleFunc("GET /v1/principal-bindings/{actor}/{principal}", func(w http.ResponseWriter, r *http.Request) {
binding, err := identityRepository.LoadBinding(r.Context(), identity.ActorID(r.PathValue("actor")), identity.PrincipalID(r.PathValue("principal")))
if err != nil {
@@ -859,3 +1086,54 @@ func humanCapabilityList(kinds []capability.CapabilityKind) string {
}
return strings.Join(labels, ", ")
}
func delegationAttentionRef(id work.DelegationID) string {
return "work:delegation:" + string(id)
}
func continueDelegationFromHumanResponse(ctx context.Context, repository *postgres.WorkRepository, response continuity.HumanResponse, now time.Time) (bool, error) {
if response.Operation != continuity.ResponseContinue || !strings.HasPrefix(response.TargetExternalRef, "work:delegation:") {
return false, nil
}
delegationID := work.DelegationID(strings.TrimPrefix(response.TargetExternalRef, "work:delegation:"))
delegation, err := repository.LoadDelegation(ctx, delegationID)
if err != nil {
return false, err
}
run, err := repository.LoadAgentRun(ctx, delegation.LatestRunID)
if err != nil {
return false, err
}
checkpoint, err := repository.LatestAgentCheckpoint(ctx, delegationID)
if err != nil {
return false, err
}
updatedDelegation, resumedRun, err := workdomain.ResumeDelegationRun(delegation, run, checkpoint, now)
if err != nil {
return false, err
}
if err := repository.SaveResumedRun(ctx, updatedDelegation, resumedRun); err != nil {
return false, err
}
return true, nil
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return strings.TrimSpace(value)
}
}
return ""
}
func evidenceRefsToEpistemics(values []work.EvidenceRef) []epistemics.EvidenceRef {
result := make([]epistemics.EvidenceRef, 0, len(values))
for _, value := range values {
if strings.TrimSpace(string(value)) == "" {
continue
}
result = append(result, epistemics.EvidenceRef(value))
}
return result
}