From 98a63c876f6c1b26d1a335e840e0f72c061c23d1 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 10:43:20 +0800 Subject: [PATCH 01/84] Report Skill upload and update field errors (#860) * Report Skill upload and update field errors * Keep the Skills update body rules outside the shared gate * Keep 400 for malformed Skill versions and the generic not-found message --- contracts/agents-api/core.openapi.yaml | 4 +- contracts/agents-api/source-files.md | 8 +- contracts/agents-api/zh/source-files.md | 10 +- .../core/internal/api/admin_skills_routes.go | 4 +- services/core/internal/api/errors.go | 13 +- services/core/internal/api/errors_skills.go | 9 +- .../core/internal/api/errors_skills_test.go | 2 + .../core/internal/api/session_artifacts.go | 2 +- services/core/internal/api/skills.go | 13 +- .../internal/api/skills_field_errors_test.go | 154 ++++++++++++++++++ services/core/internal/api/skills_transfer.go | 7 +- services/core/internal/api/skills_upload.go | 63 ++++--- .../core/internal/api/source_files_content.go | 4 +- .../core/internal/api/source_files_test.go | 2 +- .../persistence/postgres/skillpg/skillpg.go | 3 + .../postgres/skillpg/skillpg_test.go | 4 +- services/core/internal/skills/errors.go | 3 + 17 files changed, 257 insertions(+), 48 deletions(-) create mode 100644 services/core/internal/api/skills_field_errors_test.go diff --git a/contracts/agents-api/core.openapi.yaml b/contracts/agents-api/core.openapi.yaml index 0a95caad4..a0448560b 100644 --- a/contracts/agents-api/core.openapi.yaml +++ b/contracts/agents-api/core.openapi.yaml @@ -6311,7 +6311,7 @@ paths: required: true type: string produces: - - application/octet-stream + - application/zip responses: "200": description: OK @@ -6447,7 +6447,7 @@ paths: required: true type: string produces: - - application/octet-stream + - application/zip responses: "200": description: OK diff --git a/contracts/agents-api/source-files.md b/contracts/agents-api/source-files.md index 6bfe8e65f..bf29d2c78 100644 --- a/contracts/agents-api/source-files.md +++ b/contracts/agents-api/source-files.md @@ -62,11 +62,11 @@ A copy into a workspace reads a consistent snapshot of the File and can finish a | Operation | Behavior | | --- | --- | | `POST /skills` | Uploads a new Skill. Its first version is both default and latest | -| `POST /skills/{skill_id}/versions` | Uploads a new version. A `default` form field of `true` makes it the default; `false` or omitted leaves the default unchanged | +| `POST /skills/{skill_id}/versions` | Uploads a new version. A `default` form field of `true` or `false`, in any letter case, makes it the default or leaves the default unchanged; omitted leaves it unchanged | | `GET /skills`, `GET /skills/{skill_id}` | Skill metadata, without decrypting any bundle | -| `POST /skills/{skill_id}` | `{"default_version": ""}` changes the default version | +| `POST /skills/{skill_id}` | `{"default_version": ""}` changes the default version. Body errors are field errors with the member as `param`; a version the Skill does not have returns 404 with `param: "default_version"` | | `DELETE /skills/{skill_id}` | Deletes the Skill and every version | -| `GET /skills/{skill_id}/content` | ZIP of the default version | +| `GET /skills/{skill_id}/content` | ZIP of the default version, `Content-Type: application/zip`, filename `-.zip` | | `GET /skills/{skill_id}/versions`, `GET /skills/{skill_id}/versions/{version}` | Version metadata. The list orders by version number, and `after` is a version ID (`skillver_…`), not a number | | `GET /skills/{skill_id}/versions/{version}/content` | ZIP of that version | | `DELETE /skills/{skill_id}/versions/{version}` | See [Delete a version](#delete-a-version) | @@ -87,6 +87,8 @@ A bundle has one top-level folder containing `SKILL.md` and any supporting files - Entries are regular files or directories with clean relative paths. Links, special files, absolute paths, `..` components and duplicates are rejected. - Limits: 5 MiB compressed, 20 MiB expanded, 500 files, and 1,000 ZIP entries including directories. +A rejected upload returns 400 `invalid_request_error` with `param: "files"` and code `invalid_value`, and a message that states the cause. A missing `files` part, an unknown part and `default` on create are `Missing required parameter` and `Unknown parameter` errors for that member; an invalid `default` names `param: "default"`. The upload routes also reject a `name` that contains `_` and a `description` longer than 1024 characters. Skills already stored, plugin Skills and Environment installation keep accepting `_` in the name and any non-empty description. + Core encrypts each version's bundle bound to its Project, Skill and version. ZIP uploads keep executable bits; directory uploads store files with mode 0644. ### Versions and metadata diff --git a/contracts/agents-api/zh/source-files.md b/contracts/agents-api/zh/source-files.md index 697b11ede..f0edfd5de 100644 --- a/contracts/agents-api/zh/source-files.md +++ b/contracts/agents-api/zh/source-files.md @@ -1,7 +1,7 @@ --- title: "文件与 Skill" source: contracts/agents-api/source-files.md -source_hash: 32041f334a2bf3141731fab69901fc97665da225e4e03328df0db7300faa18ff +source_hash: a87f5745f8d96e7399726fa99cb8c69fc083ee03faf122bce7c4fc33ad95b5d0 --- Files(`/v1/files`)和 Skills(`/v1/skills`)是具有独立生命周期的项目资源,不依赖 Session。File 保存上传字节,Environment 通过 ID 复制它们。Skill 保存不可变、版本化的包,由模板和 Session 引用。项目的所有 API 密钥共享这些资源。 @@ -64,11 +64,11 @@ Core 在自身数据库中以 PostgreSQL 大对象存储 File 字节。上传和 | 操作 | 行为 | | --- | --- | | `POST /skills` | 上传新 Skill。首版同时为默认和最新版本 | -| `POST /skills/{skill_id}/versions` | 上传新版本。表单 `default` 为 `true` 时设为默认;`false` 或省略时默认不变 | +| `POST /skills/{skill_id}/versions` | 上传新版本。表单 `default` 取 `true` 或 `false`(不区分大小写),分别设为默认或保持默认不变;省略时默认不变 | | `GET /skills`, `GET /skills/{skill_id}` | Skill 元数据,不解密任何包 | -| `POST /skills/{skill_id}` | `{"default_version": ""}` 修改默认版本 | +| `POST /skills/{skill_id}` | `{"default_version": ""}` 修改默认版本。请求体错误是以该成员为 `param` 的字段错误;Skill 没有的版本返回 404,`param: "default_version"` | | `DELETE /skills/{skill_id}` | 删除 Skill 与所有版本 | -| `GET /skills/{skill_id}/content` | 默认版本 ZIP | +| `GET /skills/{skill_id}/content` | 默认版本 ZIP,`Content-Type: application/zip`,文件名 `-.zip` | | `GET /skills/{skill_id}/versions`, `GET /skills/{skill_id}/versions/{version}` | 版本元数据。列表按版本号排序,`after` 是版本 ID(`skillver_…`),不是数字 | | `GET /skills/{skill_id}/versions/{version}/content` | 指定版本 ZIP | | `DELETE /skills/{skill_id}/versions/{version}` | 见[删除版本](#delete-a-version) | @@ -89,6 +89,8 @@ curl "$OPENAI_BASE_URL/skills" -H "Authorization: Bearer $OPENAI_API_KEY" -F fil - 条目为普通文件或目录,使用规范相对路径。链接、特殊文件、绝对路径、`..` 组件和重复项被拒绝。 - 限制:压缩后 5 MiB,展开后 20 MiB,500 个文件,以及含目录在内的 1,000 个 ZIP 条目。 +被拒绝的上传返回 400 `invalid_request_error`,`param: "files"`,code 为 `invalid_value`,message 说明原因。缺少 `files` 部分、未知部分以及创建时携带 `default` 分别返回针对该成员的 `Missing required parameter` 与 `Unknown parameter` 错误;无效的 `default` 的 `param: "default"`。上传路由还会拒绝包含 `_` 的 `name` 以及超过 1024 个字符的 `description`。已存储的 Skill、插件 Skill 和 Environment 安装仍接受名称中的 `_` 和任何非空 `description`。 + Core 将每个版本的包加密并绑定到项目、Skill 与版本。ZIP 上传保留可执行位;目录上传以 mode 0644 存储文件。 ### 版本与元数据 {#versions-and-metadata} diff --git a/services/core/internal/api/admin_skills_routes.go b/services/core/internal/api/admin_skills_routes.go index 583968e5b..bd0a77c05 100644 --- a/services/core/internal/api/admin_skills_routes.go +++ b/services/core/internal/api/admin_skills_routes.go @@ -46,7 +46,7 @@ func (h *Handler) adminDeleteSkill(w http.ResponseWriter, r *http.Request) { // @Summary Download Skill content in a Project // @Description Core key only. Reuses the public resource projection and operation rules; the Project ID selects the target space and does not authenticate. // @Tags Skills -// @Produce octet-stream +// @Produce application/zip // @Security DeploymentAdminAuth // @Param skill_id path string true "Skill ID" // @Success 200 {file} binary @@ -103,7 +103,7 @@ func (h *Handler) adminDeleteSkillVersion(w http.ResponseWriter, r *http.Request // @Summary Download immutable Skill version content in a Project // @Description Core key only. Reuses the public resource projection and operation rules; the Project ID selects the target space and does not authenticate. // @Tags Skills -// @Produce octet-stream +// @Produce application/zip // @Security DeploymentAdminAuth // @Param skill_id path string true "Skill ID" // @Param version path string true "Concrete version number" diff --git a/services/core/internal/api/errors.go b/services/core/internal/api/errors.go index af339ab6d..05d2ad2bb 100644 --- a/services/core/internal/api/errors.go +++ b/services/core/internal/api/errors.go @@ -61,9 +61,10 @@ func writeContentTooLarge(w http.ResponseWriter) { const unstorableTextMessage = "Request text contains characters this service cannot store or compare, such as U+0000 or invalid UTF-8." // fieldError is a request validation failure reported with the official -// invalid_request_error code. An empty param serializes as null. +// invalid_request_error code unless it names another. An empty param +// serializes as null. type fieldError struct { - param, message string + param, message, code string } func (e *fieldError) Error() string { return e.message } @@ -75,10 +76,14 @@ func writeFieldError(w http.ResponseWriter, err error) bool { if !errors.As(err, &field) { return false } + code := field.code + if code == "" { + code = "invalid_request_error" + } if field.param == "" { - writeError(w, http.StatusBadRequest, "invalid_request_error", field.message) + writeError(w, http.StatusBadRequest, code, field.message) } else { - writeError(w, http.StatusBadRequest, "invalid_request_error", field.message, field.param) + writeError(w, http.StatusBadRequest, code, field.message, field.param) } return true } diff --git a/services/core/internal/api/errors_skills.go b/services/core/internal/api/errors_skills.go index 89109e2af..736e2e4f9 100644 --- a/services/core/internal/api/errors_skills.go +++ b/services/core/internal/api/errors_skills.go @@ -23,12 +23,15 @@ func writeSkillsError(w http.ResponseWriter, r *http.Request, err error) { } else { writeError(w, http.StatusBadRequest, "invalid_request_error", cursor.Message) } - case errors.Is(err, skills.ErrNotFound): - code := "not_found_error" + case errors.Is(err, skills.ErrNotFound), errors.Is(err, skills.ErrVersionNotFound): + code, param := "not_found_error", []string(nil) if skillsRoute { code = "" } - writeError(w, http.StatusNotFound, code, "Resource not found.") + if errors.Is(err, skills.ErrVersionNotFound) { + param = []string{"default_version"} + } + writeError(w, http.StatusNotFound, code, "Resource not found.", param...) case errors.Is(err, skills.ErrInvalidInput): writeError(w, http.StatusBadRequest, "invalid_request", invalidInputMessage) case writeAuditSourceError(w, r, err) || writeTextValueError(w, r, err): diff --git a/services/core/internal/api/errors_skills_test.go b/services/core/internal/api/errors_skills_test.go index f08aaa25d..c7431eb29 100644 --- a/services/core/internal/api/errors_skills_test.go +++ b/services/core/internal/api/errors_skills_test.go @@ -34,6 +34,8 @@ func TestWriteSkillsError(t *testing.T) { `{"error":{"message":"Resource not found.","type":"invalid_request_error","code":null,"param":null}}`}, {"project not found", project, skills.ErrNotFound, http.StatusNotFound, `{"error":{"message":"Resource not found.","type":"not_found_error","code":"not_found_error","param":null}}`}, + {"default version missing", "/v1/skills/skill_missing", skills.ErrVersionNotFound, http.StatusNotFound, + `{"error":{"message":"Resource not found.","type":"invalid_request_error","code":null,"param":"default_version"}}`}, {"invalid input", "/v1/skills", skills.ErrInvalidInput, http.StatusBadRequest, `{"error":{"message":"Invalid resource identifier or request limits.","type":"invalid_request_error","code":"invalid_request","param":null}}`}, {"unstorable text", "/v1/skills", fmt.Errorf("create: %w", textvalue.ErrUnstorable), http.StatusBadRequest, diff --git a/services/core/internal/api/session_artifacts.go b/services/core/internal/api/session_artifacts.go index 79275ca82..5e0a41f9b 100644 --- a/services/core/internal/api/session_artifacts.go +++ b/services/core/internal/api/session_artifacts.go @@ -60,7 +60,7 @@ func (h *Handler) deleteSessionArtifact(w http.ResponseWriter, r *http.Request) } func (h *Handler) sessionArtifactContent(w http.ResponseWriter, r *http.Request) { - err := serveStoredContent(w, r, func(ctx context.Context, consume func(string, int64, io.Reader) error) error { + err := serveStoredContent(w, r, "application/octet-stream", func(ctx context.Context, consume func(string, int64, io.Reader) error) error { return h.ArtifactsReader.ReadSessionArtifact(ctx, tenantID(r), chi.URLParam(r, "session_id"), chi.URLParam(r, "artifact_id"), func(a sessions.Artifact, body io.Reader) error { return consume(path.Base(a.Path), a.SizeBytes, body) }) diff --git a/services/core/internal/api/skills.go b/services/core/internal/api/skills.go index 392c3c8d4..b62e2ca3a 100644 --- a/services/core/internal/api/skills.go +++ b/services/core/internal/api/skills.go @@ -2,6 +2,7 @@ package api import ( "context" + "encoding/json" "net/http" "strconv" @@ -56,13 +57,23 @@ func (h *Handler) getSkill(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, skillResponseResource(value)) } +var skillUpdateShape = shape{kind: objectValue, members: []member{{"default_version", requiredString}}} + func (h *Handler) updateSkill(w http.ResponseWriter, r *http.Request) { body, ok := readJSONBodyLimit(w, r, 64<<10, "Request exceeds 64 KiB.") if !ok { return } + // The Skills routes keep their own body rules; a well-formed object reports + // its field errors first. + if json.Valid(body) && jsonValueKind(body) == "an object" { + if err := checkValue("", body, skillUpdateShape); err != nil { + writeFieldError(w, err) + return + } + } var input v1.SkillUpdateRequest - if decodeInputObject(body, &input, "default_version") != nil || input.DefaultVersion == "" { + if decodeInputObject(body, &input, "default_version") != nil { writeSkillsError(w, r, skills.ErrInvalidInput) return } diff --git a/services/core/internal/api/skills_field_errors_test.go b/services/core/internal/api/skills_field_errors_test.go new file mode 100644 index 000000000..a1be754f4 --- /dev/null +++ b/services/core/internal/api/skills_field_errors_test.go @@ -0,0 +1,154 @@ +package api + +import ( + "archive/zip" + "bytes" + "context" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "net/textproto" + "strings" + "testing" + + "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/skills" + "github.com/go-chi/chi/v5" +) + +func skillZip(t *testing.T, name, description string) []byte { + t.Helper() + var buffer bytes.Buffer + writer := zip.NewWriter(&buffer) + file, err := writer.Create("proof/SKILL.md") + if err != nil { + t.Fatal(err) + } + if _, err = file.Write([]byte("---\nname: " + name + "\ndescription: " + description + "\n---\nbody")); err != nil { + t.Fatal(err) + } + if err = writer.Close(); err != nil { + t.Fatal(err) + } + return buffer.Bytes() +} + +// skillServer serves the Skill routes over HTTP, which the bounded transfers need. +func skillServer(t *testing.T, fake *fakeSkills) *httptest.Server { + t.Helper() + router := chi.NewRouter() + router.Use(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), adminTenantContextKey{}, "tenant"))) + }) + }) + (&Handler{Dependencies: Dependencies{Skills: fake}}).registerSkillRoutes(router) + server := httptest.NewServer(router) + t.Cleanup(server.Close) + return server +} + +func TestSkillUploadFieldErrors(t *testing.T) { + type part struct { + field, filename string + body []byte + } + good := skillZip(t, "proof", "Verify an upload.") + for _, test := range []struct { + name string + version bool + parts []part + want string + }{ + {"no files", false, nil, `"message":"Missing required parameter: 'files'.","type":"invalid_request_error","code":"invalid_request_error","param":"files"`}, + {"default on create", false, []part{{"files", "p.zip", good}, {"default", "", []byte("true")}}, `"message":"Unknown parameter: 'default'.","type":"invalid_request_error","code":"invalid_request_error","param":"default"`}, + {"bad default", true, []part{{"files", "p.zip", good}, {"default", "", []byte("yes")}}, `"code":"invalid_request_error","param":"default"`}, + {"bad bundle", false, []part{{"files", "p.zip", []byte("not a zip")}}, `"type":"invalid_request_error","code":"invalid_value","param":"files"`}, + {"underscore name", false, []part{{"files", "p.zip", skillZip(t, "my_skill", "Verify an upload.")}}, `"message":"The Skill name must not contain '_'.","type":"invalid_request_error","code":"invalid_value","param":"files"`}, + {"long description", false, []part{{"files", "p.zip", skillZip(t, "proof", strings.Repeat("d", 1025))}}, `"message":"The Skill description must be at most 1024 characters.","type":"invalid_request_error","code":"invalid_value","param":"files"`}, + } { + t.Run(test.name, func(t *testing.T) { + var buffer bytes.Buffer + writer := multipart.NewWriter(&buffer) + for _, entry := range test.parts { + header := textproto.MIMEHeader{} + disposition := `form-data; name="` + entry.field + `"` + if entry.filename != "" { + disposition += `; filename="` + entry.filename + `"` + } + header.Set("Content-Disposition", disposition) + p, err := writer.CreatePart(header) + if err != nil { + t.Fatal(err) + } + _, _ = p.Write(entry.body) + } + _ = writer.Close() + path := "/v1/skills" + if test.version { + path += "/skill_x/versions" + } + response, err := http.Post(skillServer(t, &fakeSkills{t: t}).URL+path, writer.FormDataContentType(), &buffer) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, _ := io.ReadAll(response.Body) + if response.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), test.want) { + t.Fatalf("%d %s", response.StatusCode, body) + } + }) + } +} + +func TestSkillUploadAcceptsCapitalizedDefault(t *testing.T) { + var buffer bytes.Buffer + writer := multipart.NewWriter(&buffer) + file, _ := writer.CreateFormFile("files", "p.zip") + _, _ = file.Write(skillZip(t, "proof", "Verify an upload.")) + _ = writer.WriteField("default", "True") + _ = writer.Close() + request := httptest.NewRequest(http.MethodPost, "/v1/skills/skill_x/versions", &buffer) + request.Header.Set("Content-Type", writer.FormDataContentType()) + if _, makeDefault, err := readSkillUpload(request, true); err != nil || !makeDefault { + t.Fatal(makeDefault, err) + } +} + +func TestSkillUpdateErrors(t *testing.T) { + fake := &fakeSkills{t: t, setDefaultVersion: func(context.Context, skills.SetDefaultVersion) (skills.Skill, error) { + return skills.Skill{}, skills.ErrVersionNotFound + }} + router := chi.NewRouter() + router.Post("/v1/skills/{skill_id}", (&Handler{Dependencies: Dependencies{Skills: fake}}).updateSkill) + for _, test := range []struct{ name, body, want string }{ + {"unknown key", `{"default_version":"1","x":1}`, `"message":"Unknown parameter: 'x'.","type":"invalid_request_error","code":"invalid_request_error","param":"x"`}, + {"missing", `{}`, `"message":"Missing required parameter: 'default_version'.","type":"invalid_request_error","code":"invalid_request_error","param":"default_version"`}, + {"wrong type", `{"default_version":1}`, `"message":"Invalid type for 'default_version': expected a string, but got an integer instead.","type":"invalid_request_error","code":"invalid_request_error","param":"default_version"`}, + {"missing version", `{"default_version":"9"}`, `"message":"Resource not found.","type":"invalid_request_error","code":null,"param":"default_version"`}, + } { + t.Run(test.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodPost, "/v1/skills/skill_x", strings.NewReader(test.body)) + request = request.WithContext(context.WithValue(request.Context(), adminTenantContextKey{}, "tenant")) + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if !strings.Contains(response.Body.String(), test.want) || (test.name == "missing version") != (response.Code == http.StatusNotFound) { + t.Fatalf("%d %s", response.Code, response.Body) + } + }) + } +} + +func TestSkillContentDownloadHeaders(t *testing.T) { + fake := &fakeSkills{t: t, readDefaultVersion: func(context.Context, skills.ReadDefaultVersion) (skills.Content, error) { + return skills.Content{Version: skills.Version{Name: "proof", Version: 3}, Archive: []byte("zip")}, nil + }} + response, err := http.Get(skillServer(t, fake).URL + "/v1/skills/skill_x/content") + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.Header.Get("Content-Type") != "application/zip" || response.Header.Get("Content-Disposition") != `attachment; filename=proof-3.zip` { + t.Fatal(response.Header) + } +} diff --git a/services/core/internal/api/skills_transfer.go b/services/core/internal/api/skills_transfer.go index 975017902..365692783 100644 --- a/services/core/internal/api/skills_transfer.go +++ b/services/core/internal/api/skills_transfer.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "fmt" "io" "net/http" "time" @@ -34,7 +35,7 @@ func (h *Handler) uploadSkill(w http.ResponseWriter, r *http.Request, version bo var limit *http.MaxBytesError if errors.As(err, &limit) { writeContentTooLarge(w) - } else { + } else if !writeFieldError(w, err) { writeSkillsError(w, r, skills.ErrInvalidInput) } return @@ -57,7 +58,7 @@ func (h *Handler) uploadSkill(w http.ResponseWriter, r *http.Request, version bo } func (h *Handler) skillContent(w http.ResponseWriter, r *http.Request) { - err := serveStoredContent(w, r, func(ctx context.Context, consume func(string, int64, io.Reader) error) error { + err := serveStoredContent(w, r, "application/zip", func(ctx context.Context, consume func(string, int64, io.Reader) error) error { skill := skills.PathID(chi.URLParam(r, "skill_id")) var content skills.Content var err error @@ -69,7 +70,7 @@ func (h *Handler) skillContent(w http.ResponseWriter, r *http.Request) { if err != nil { return err } - return consume(content.Version.Name+".zip", int64(len(content.Archive)), bytes.NewReader(content.Archive)) + return consume(fmt.Sprintf("%s-%d.zip", content.Version.Name, content.Version.Version), int64(len(content.Archive)), bytes.NewReader(content.Archive)) }) if err != nil { writeSkillsError(w, r, err) diff --git a/services/core/internal/api/skills_upload.go b/services/core/internal/api/skills_upload.go index 6a98b3e5e..208a226bb 100644 --- a/services/core/internal/api/skills_upload.go +++ b/services/core/internal/api/skills_upload.go @@ -12,18 +12,17 @@ import ( "unicode/utf8" "github.com/MiniMax-AI/OpenAgentCore/internal/agentskill" - "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/skills" ) // readSkillUpload preserves directory paths from Content-Disposition. The // multipart Part.FileName helper would discard their parent components. func readSkillUpload(r *http.Request, versionUpload bool) ([]byte, bool, error) { if r.Header.Get("Content-Encoding") != "" { - return nil, false, skills.ErrInvalidInput + return nil, false, invalidFiles("Skill uploads do not support Content-Encoding.") } reader, err := r.MultipartReader() if err != nil { - return nil, false, skills.ErrInvalidInput + return nil, false, invalidFiles("Skill uploads must be multipart/form-data.") } var archive bytes.Buffer writer := zip.NewWriter(&archive) @@ -42,41 +41,53 @@ func readSkillUpload(r *http.Request, versionUpload bool) ([]byte, bool, error) kind, attrs, err := mime.ParseMediaType(part.Header.Get("Content-Disposition")) field := attrs["name"] if err != nil || kind != "form-data" || part.Header.Get("Content-Transfer-Encoding") != "" { - return nil, false, skills.ErrInvalidInput + return nil, false, invalidFiles("Each part must be form-data without a Content-Transfer-Encoding.") } if field == "default" { - if !versionUpload || seenDefault { - return nil, false, skills.ErrInvalidInput + if !versionUpload { + return nil, false, &fieldError{param: "default", message: "Unknown parameter: 'default'."} } - if _, ok := attrs["filename"]; ok { - return nil, false, skills.ErrInvalidInput + if _, ok := attrs["filename"]; ok || seenDefault { + return nil, false, &fieldError{param: "default", message: "The 'default' field must be one plain value."} } value, err := io.ReadAll(io.LimitReader(part, 6)) - if err != nil || (string(value) != "true" && string(value) != "false") { - return nil, false, skills.ErrInvalidInput + if err != nil { + return nil, false, err + } + makeDefault = strings.EqualFold(string(value), "true") + if !makeDefault && !strings.EqualFold(string(value), "false") { + return nil, false, invalidValue("default", string(value), []string{"true", "false"}) } seenDefault = true - makeDefault = string(value) == "true" } else { name := attrs["filename"] - if (field != "files" && field != "files[]") || name == "" || files >= 500 || zipUpload { - return nil, false, skills.ErrInvalidInput + if field != "files" && field != "files[]" { + if !echoableField(field) { + return nil, false, errUnknownParameter + } + return nil, false, &fieldError{param: field, message: "Unknown parameter: '" + field + "'."} + } + if name == "" { + return nil, false, invalidFiles("Each 'files' part must be a file with a filename.") + } + if files >= 500 || zipUpload { + return nil, false, invalidFiles("Upload either one ZIP file or at most 500 files, not both.") } if field == "files" { if files != 0 { - return nil, false, skills.ErrInvalidInput + return nil, false, invalidFiles("Upload either one ZIP file or at most 500 files, not both.") } uploaded, err = io.ReadAll(io.LimitReader(part, agentskill.MaxArchiveBytes+1)) if err != nil { return nil, false, err } if len(uploaded) > agentskill.MaxArchiveBytes { - return nil, false, skills.ErrInvalidInput + return nil, false, invalidFiles("The ZIP file exceeds 5 MiB.") } zipUpload = true } else { if !utf8.ValidString(name) || len(name) > 4096 || path.IsAbs(name) || path.Clean(name) != name || strings.ContainsAny(name, "\\\x00\r\n") || !strings.Contains(name, "/") || paths[name] { - return nil, false, skills.ErrInvalidInput + return nil, false, invalidFiles("Each file name must be a unique, clean relative path inside a top-level folder.") } paths[name] = true body, err := io.ReadAll(io.LimitReader(part, int64(agentskill.MaxExpandedBytes-expanded)+1)) @@ -85,7 +96,7 @@ func readSkillUpload(r *http.Request, versionUpload bool) ([]byte, bool, error) } expanded += len(body) if expanded > agentskill.MaxExpandedBytes { - return nil, false, skills.ErrInvalidInput + return nil, false, invalidFiles("The files exceed 20 MiB expanded.") } header := &zip.FileHeader{Name: name, Method: zip.Deflate} header.SetMode(0644) @@ -110,13 +121,25 @@ func readSkillUpload(r *http.Request, versionUpload bool) ([]byte, bool, error) return nil, false, err } if files == 0 { - return nil, false, skills.ErrInvalidInput + return nil, false, missingParameter("files") } if !zipUpload { uploaded = archive.Bytes() } - if _, err := agentskill.Inspect(uploaded); err != nil { - return nil, false, skills.ErrInvalidInput + metadata, err := agentskill.Inspect(uploaded) + if err != nil { + return nil, false, invalidFiles("The bundle must hold one top-level folder with a valid SKILL.md and files within the limits.") + } + // Installed and plugin Skills keep the wider native rules; only this route is stricter. + if strings.Contains(metadata.Name, "_") { + return nil, false, invalidFiles("The Skill name must not contain '_'.") + } + if utf8.RuneCountInString(metadata.Description) > 1024 { + return nil, false, invalidFiles("The Skill description must be at most 1024 characters.") } return uploaded, makeDefault, nil } + +func invalidFiles(message string) error { + return &fieldError{param: "files", code: "invalid_value", message: message} +} diff --git a/services/core/internal/api/source_files_content.go b/services/core/internal/api/source_files_content.go index 7c2812f0d..50156655a 100644 --- a/services/core/internal/api/source_files_content.go +++ b/services/core/internal/api/source_files_content.go @@ -24,7 +24,7 @@ func (h *Handler) sourceFileContent(w http.ResponseWriter, r *http.Request) { // serveStoredContent streams the body read supplies. It returns read's error // while no response has started; after that, a failure aborts the response. -func serveStoredContent(w http.ResponseWriter, r *http.Request, read func(context.Context, func(string, int64, io.Reader) error) error) error { +func serveStoredContent(w http.ResponseWriter, r *http.Request, contentType string, read func(context.Context, func(string, int64, io.Reader) error) error) error { deadline := time.Now().Add(sourceTransferTimeout) if http.NewResponseController(w).SetWriteDeadline(deadline) != nil { writeError(w, http.StatusServiceUnavailable, "file_transfer_unavailable", "Bounded file transfer is unavailable.") @@ -34,7 +34,7 @@ func serveStoredContent(w http.ResponseWriter, r *http.Request, read func(contex defer cancel() started := false err := read(ctx, func(filename string, size int64, body io.Reader) error { - w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Type", contentType) w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": filename})) w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) w.Header().Set("Cache-Control", "no-store") diff --git a/services/core/internal/api/source_files_test.go b/services/core/internal/api/source_files_test.go index 9adcd126a..a45392fdd 100644 --- a/services/core/internal/api/source_files_test.go +++ b/services/core/internal/api/source_files_test.go @@ -265,7 +265,7 @@ func TestEnvironmentSourceCopyEnforcesScopeUnionAndSize(t *testing.T) { func TestStoredContentDoesNotCompleteTruncatedResponse(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - serveStoredContent(w, r, func(_ context.Context, consume func(string, int64, io.Reader) error) error { + serveStoredContent(w, r, "application/octet-stream", func(_ context.Context, consume func(string, int64, io.Reader) error) error { return consume("source.bin", 3, strings.NewReader("x")) }) })) diff --git a/services/core/internal/persistence/postgres/skillpg/skillpg.go b/services/core/internal/persistence/postgres/skillpg/skillpg.go index cc3089737..37a8285f7 100644 --- a/services/core/internal/persistence/postgres/skillpg/skillpg.go +++ b/services/core/internal/persistence/postgres/skillpg/skillpg.go @@ -108,6 +108,9 @@ func (s *Store) SetDefaultVersion(ctx context.Context, tenantID string, skillID return err } target, err := q.GetSkillVersion(ctx, sqlc.GetSkillVersionParams{TenantID: tenant, SkillID: pgID(skillID), Version: version}) + if errors.Is(err, pgx.ErrNoRows) { + return skills.ErrVersionNotFound + } if err != nil { return err } diff --git a/services/core/internal/persistence/postgres/skillpg/skillpg_test.go b/services/core/internal/persistence/postgres/skillpg/skillpg_test.go index d843546e5..2a0ab10a5 100644 --- a/services/core/internal/persistence/postgres/skillpg/skillpg_test.go +++ b/services/core/internal/persistence/postgres/skillpg/skillpg_test.go @@ -197,7 +197,7 @@ func TestOwnershipEncryptionAndVersions(t *testing.T) { if _, err = f.service.ListVersions(ctx, skills.ListVersions{TenantID: tenant, SkillID: id, After: "3", Limit: 20, Ascending: true}); !errors.As(err, &cursorErr) || cursorErr.Message != "Invalid 'after': '3'. Expected an ID that begins with 'skillver'." { t.Fatal("numeric version is not a cursor", err) } - if _, err = f.service.SetDefaultVersion(ctx, skills.SetDefaultVersion{TenantID: tenant, SkillID: id, Version: "999"}); !errors.Is(err, skills.ErrNotFound) { + if _, err = f.service.SetDefaultVersion(ctx, skills.SetDefaultVersion{TenantID: tenant, SkillID: id, Version: "999"}); !errors.Is(err, skills.ErrVersionNotFound) { t.Fatal("missing default", err) } updated, err := f.service.SetDefaultVersion(ctx, skills.SetDefaultVersion{TenantID: tenant, SkillID: id, Version: "3"}) @@ -341,7 +341,7 @@ func TestMetadataTracksDefaultVersion(t *testing.T) { if _, err := replaced.service.SetDefaultVersion(ctx, skills.SetDefaultVersion{TenantID: foreign, SkillID: id, Version: "2"}); !errors.Is(err, skills.ErrNotFound) { t.Fatal("foreign default update", err) } - if _, err := replaced.service.SetDefaultVersion(ctx, skills.SetDefaultVersion{TenantID: tenant, SkillID: id, Version: "999"}); !errors.Is(err, skills.ErrNotFound) { + if _, err := replaced.service.SetDefaultVersion(ctx, skills.SetDefaultVersion{TenantID: tenant, SkillID: id, Version: "999"}); !errors.Is(err, skills.ErrVersionNotFound) { t.Fatal("missing default update", err) } assertStored(1, 2) diff --git a/services/core/internal/skills/errors.go b/services/core/internal/skills/errors.go index 5d63bfcf0..28683951f 100644 --- a/services/core/internal/skills/errors.go +++ b/services/core/internal/skills/errors.go @@ -12,6 +12,9 @@ var ( // Malformed identifiers and other tenants' resources are indistinguishable // from missing ones. ErrNotFound = errors.New("skill not found") + // ErrVersionNotFound reports a version number that names no version of an + // existing Skill. + ErrVersionNotFound = errors.New("skill version not found") // ErrInvalidInput reports an invalid archive, version, page limit or tenant. ErrInvalidInput = errors.New("invalid skill request") // ErrDefaultVersion rejects deleting the default version while other From 7d267d7e00fb3ee344050ca220693014f1e03840 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 10:46:12 +0800 Subject: [PATCH 02/84] Validate Session, Vault, Credential and Template request shapes (#862) * Validate Session, Vault, Credential and Template request shapes * Expect named field errors in the Session official-client tests * Delete the unused objectMember helper --- contracts/agents-api/sessions-events.md | 2 +- contracts/agents-api/vaults.md | 4 +- contracts/agents-api/wire-semantics.md | 2 + contracts/agents-api/zh/sessions-events.md | 4 +- contracts/agents-api/zh/vaults.md | 6 +- contracts/agents-api/zh/wire-semantics.md | 4 +- scripts/generate-public-api.py | 36 ++- .../internal/api/configuration_validation.go | 98 +++++--- services/core/internal/api/credentials.go | 34 ++- .../core/internal/api/credentials_oauth.go | 120 ++++------ .../core/internal/api/credentials_update.go | 27 +-- .../internal/api/environment_templates.go | 36 ++- services/core/internal/api/function_inputs.go | 75 ------ services/core/internal/api/handler.go | 2 +- services/core/internal/api/inputs.go | 13 +- services/core/internal/api/json_members.go | 25 -- .../core/internal/api/json_members_test.go | 23 +- .../core/internal/api/official_shapes.gen.go | 220 ++++++++++++++++++ .../core/internal/api/request_shapes_test.go | 53 +++++ .../internal/api/session_credentials_test.go | 8 +- .../api/session_initial_input_test.go | 2 +- .../core/internal/api/session_metadata.go | 58 ++--- services/core/internal/api/session_request.go | 41 +--- .../core/internal/api/session_request_test.go | 14 +- .../internal/api/validation_errors_test.go | 15 +- services/core/internal/api/vaults.go | 41 +--- .../core/internal/environmentconfig/setup.go | 11 +- .../core/tests/official_session_metadata.py | 11 +- .../core/tests/official_session_requests.py | 10 +- 29 files changed, 561 insertions(+), 434 deletions(-) create mode 100644 services/core/internal/api/request_shapes_test.go diff --git a/contracts/agents-api/sessions-events.md b/contracts/agents-api/sessions-events.md index 5b43214e9..88ebb0f37 100644 --- a/contracts/agents-api/sessions-events.md +++ b/contracts/agents-api/sessions-events.md @@ -61,7 +61,7 @@ On `openai_hosted` and `self_hosted` Sessions, messages sent while a Turn runs j ### Input errors -Checks run in this order: request validation, Session lookup, retry lookup, the Environment file-write gate for batches with a message, the pending-input gate, then each event in batch order. A rejected batch writes nothing and leaves any pending action unchanged. Every 409 has type `conflict_error` ([error envelope](./wire-semantics.md)). +Checks run in this order: [request validation](./wire-semantics.md#configuration-validation), whose paths start with `events[i]`, Session lookup, retry lookup, the Environment file-write gate for batches with a message, the pending-input gate, then each event in batch order. A rejected batch writes nothing and leaves any pending action unchanged. Every 409 has type `conflict_error` ([error envelope](./wire-semantics.md)). | Case | Status and code | Message | | --- | --- | --- | diff --git a/contracts/agents-api/vaults.md b/contracts/agents-api/vaults.md index 30b4c03d0..bd43c2cfa 100644 --- a/contracts/agents-api/vaults.md +++ b/contracts/agents-api/vaults.md @@ -58,7 +58,7 @@ A malformed, missing or foreign ID returns 404 `not_found_error`, and so does a | Field | Rules | | --- | --- | -| `name` | Optional. Omitted stays `null`; explicit `null` is rejected. A string is trimmed and must then hold 1–256 UTF-8 bytes | +| `name` | Optional. Omitted stays `null`; explicit `null` is rejected. A string is trimmed and must then hold 1–256 UTF-8 bytes (param `name`) | | `metadata` | Omitted or `null` becomes `{}`. Values must be strings; another type returns 400 `invalid_request_error` with param `metadata.`. The encoded object is limited to 64 KiB, with no pair-count or length limits | A Vault reads as `id`, `object: "vault"`, `created_at`, `name` and `metadata`. There is no update route. @@ -67,7 +67,7 @@ Deleting a Vault removes it and all its Credentials in one transaction, whatever ## Credentials -Creation takes a required `name` (trimmed, 1–256 UTF-8 bytes) and an `auth` object whose `type` is `static_bearer` or `mcp_oauth`. `mcp_server_url` must be an absolute HTTPS URL without userinfo or fragment; Core keeps it byte for byte, including any query, and performs no DNS or HTTP request. +Creation takes a required `name` (trimmed, 1–256 UTF-8 bytes) and an `auth` object whose `type` is `static_bearer` or `mcp_oauth`. `mcp_server_url` must be an absolute HTTPS URL without userinfo or fragment; Core keeps it byte for byte, including any query, and performs no DNS or HTTP request. Field errors name the field as param, such as `auth.type`, `auth.access_token` or `auth.mcp_server_url`, and an unknown or missing member has the official `Unknown parameter` or `Missing required parameter` message ([request validation](./wire-semantics.md#configuration-validation)). A Credential reads as `id`, `vault_id`, `name`, `object: "vault.credential"`, `created_at`, `updated_at` and `auth`. `auth` holds `type` and `mcp_server_url`; an OAuth Credential adds `expires_at` and `refresh` with `client_id`, `token_endpoint`, `token_endpoint_auth.type`, `resource` and `scope`. Reads and lists need no storage key. diff --git a/contracts/agents-api/wire-semantics.md b/contracts/agents-api/wire-semantics.md index 182915c32..0fbc8d00c 100644 --- a/contracts/agents-api/wire-semantics.md +++ b/contracts/agents-api/wire-semantics.md @@ -176,6 +176,8 @@ Agent create and update bodies and the inline `agent` of Session create are chec | Function `parameters` with a string root `type` other than `object` | null | `Invalid schema for function '': schema must be a JSON Schema of 'type: "object"', got 'type: ""'.` | | `text.format` JSON schema with a string root `type` other than `object` | null | `agent.text.format.schema must have top-level type "object"; got ""`, also on Agent requests | +Session create and update, Vault create, Credential create and update, Environment Template create and update and Session events are checked the same way against their pinned bodies, before their own decoding. The param is the JSON path, such as `metadata`, `input[0].role`, `input[0].content[0].type`, `events[0].input[0].role`, `auth.type`, `auth.access_token`, `env.KEY` or `name`. `input` and a function result `output` take a string or an array, and any other type reports `expected a string or an array`. The Session `agent` and `environment` and the Template `network` keep their own parsers and are first checked to be objects. Rules the pinned schema does not express report the field as param with a message that names the rule: Vault and Credential `name` (1–256 UTF-8 bytes after trimming), Template `name` (1–256 characters), a nonempty `auth.token` and `auth.access_token`, an HTTPS `auth.mcp_server_url` and `auth.refresh.token_endpoint`, an RFC 3339 `auth.expires_at`, environment variable names (`env.`) and a Credential update with nothing to change (param `auth`). + Within one object Core reports a union's `type` first, then unknown members, then member values in document order, then missing members in the pinned schema's order; tools before `text`, and the whole object before the duplicate and schema-root checks. Schemas without a string root `type` are not checked. Function and output schemas, `request_metadata` and `x_agents_core` keep their own parsers. Update bodies and the inline Session agent are validated before the Agent lookup, so owned, foreign, missing and malformed Agent IDs give the same response. Core saves values the pinned shapes allow even when the selected Harness cannot run them: function names of any length and the reasoning, service tier, web search and programmatic tool calling values a Harness does not declare. diff --git a/contracts/agents-api/zh/sessions-events.md b/contracts/agents-api/zh/sessions-events.md index 099ea2ed7..618f0b60b 100644 --- a/contracts/agents-api/zh/sessions-events.md +++ b/contracts/agents-api/zh/sessions-events.md @@ -1,7 +1,7 @@ --- title: "Session、事件和历史" source: contracts/agents-api/sessions-events.md -source_hash: e8dfd2f21bdcf16832c60fb9fac2df42bc96553d7f1294dc2742c3eb455772a1 +source_hash: 39fe5deab865e778bd8d3fa50a5d66707e10df4652b868e47f17126d962291eb --- 本契约涵盖 Session 内部发生的事情:发送输入、实时事件流,以及读取 Turn、Item 和使用量的持久化历史。Session 资源本身(创建配置、重试标识、更新、列出和删除)见 [API 行为](wire-semantics.md)。消息和函数结果内容见[消息内容](message-content.md)。[Agents API 指南](../../../docs/zh/api/public-agent-api.md)展示了使用 SDK 和 HTTP 的调用方式。 @@ -63,7 +63,7 @@ Turn 失败后 Session 仍可使用:新输入会启动一个新 Turn。后来 ### 输入错误 {#input-errors} -检查按以下顺序执行:请求验证、Session 查找、重试查找、针对包含消息的批次的 Environment 文件写入门控、待处理输入门控,最后按批次顺序检查每个事件。被拒绝的批次不会写入任何内容,也不会改变任何待处理操作。所有 409 响应的 `type` 都是 `conflict_error`([错误封装](wire-semantics.md))。 +检查按以下顺序执行:[请求验证](wire-semantics.md#configuration-validation)(路径以 `events[i]` 开头)、Session 查找、重试查找、针对包含消息的批次的 Environment 文件写入门控、待处理输入门控,最后按批次顺序检查每个事件。被拒绝的批次不会写入任何内容,也不会改变任何待处理操作。所有 409 响应的 `type` 都是 `conflict_error`([错误封装](wire-semantics.md))。 | 情况 | 状态和代码 | 消息 | | --- | --- | --- | diff --git a/contracts/agents-api/zh/vaults.md b/contracts/agents-api/zh/vaults.md index 4f598f528..9aee59336 100644 --- a/contracts/agents-api/zh/vaults.md +++ b/contracts/agents-api/zh/vaults.md @@ -1,7 +1,7 @@ --- title: "Vault 与 Credential" source: contracts/agents-api/vaults.md -source_hash: b27509949dca26f064cda765ea97229e3325dee3ff650b17fa332a756409cf34 +source_hash: 1a57ba70173f8a000b6b0cb74eb7fa6a6c688b4f71d7e617b4fdfb60e6d6fef5 --- Vault 是项目所有的 Credential 容器。Credential 保存一个 HTTPS MCP server 的秘密:`static_bearer` token 或 `mcp_oauth` grant。Session 在 `vault_ids` 中关联 Vault;Core 在创建 Session 时为每个 HTTP MCP server 选择一个 Credential,只在分派工作时将解密 token 交给 Runtime。秘密只能写入:任何读取都不返回 token、refresh token、client secret 或密文。 @@ -60,7 +60,7 @@ MCP tool 可以通过 `credential_id` 指定 Credential;未指定时,Core | 字段 | 规则 | | --- | --- | -| `name` | 可选;省略保持 `null`,显式 `null` 被拒绝。字符串去除首尾空白后必须为 1–256 UTF-8 字节 | +| `name` | 可选;省略保持 `null`,显式 `null` 被拒绝。字符串去除首尾空白后必须为 1–256 UTF-8 字节(param 为 `name`) | | `metadata` | 省略或 `null` 转为 `{}`。值必须为字符串;其他类型返回 400 `invalid_request_error`,param 为 `metadata.`。编码后对象上限 64 KiB,无键值对数量或长度限制 | Vault 读取包含 `id`、`object: "vault"`、`created_at`、`name` 和 `metadata`。没有更新路由。 @@ -69,7 +69,7 @@ Vault 读取包含 `id`、`object: "vault"`、`created_at`、`name` 和 `metadat ## Credential {#credentials} -创建需要 `name`(去除首尾空白后 1–256 UTF-8 字节)和 `auth` 对象,`type` 为 `static_bearer` 或 `mcp_oauth`。`mcp_server_url` 必须是无 userinfo、无 fragment 的绝对 HTTPS URL;Core 逐字节保留,包括 query,不执行 DNS 或 HTTP 请求。 +创建需要 `name`(去除首尾空白后 1–256 UTF-8 字节)和 `auth` 对象,`type` 为 `static_bearer` 或 `mcp_oauth`。`mcp_server_url` 必须是无 userinfo、无 fragment 的绝对 HTTPS URL;Core 逐字节保留,包括 query,不执行 DNS 或 HTTP 请求。字段错误以该字段作为 param,例如 `auth.type`、`auth.access_token` 或 `auth.mcp_server_url`;未知成员或缺失成员使用官方的 `Unknown parameter` 或 `Missing required parameter` 消息([请求验证](wire-semantics.md#configuration-validation))。 Credential 读取包含 `id`、`vault_id`、`name`、`object: "vault.credential"`、`created_at`、`updated_at` 和 `auth`。`auth` 包含 `type`、`mcp_server_url`;OAuth Credential 还包含 `expires_at` 和 `refresh`,后者包含 `client_id`、`token_endpoint`、`token_endpoint_auth.type`、`resource` 和 `scope`。读取和列表无需 storage key。 diff --git a/contracts/agents-api/zh/wire-semantics.md b/contracts/agents-api/zh/wire-semantics.md index 978886b12..8aeb6c232 100644 --- a/contracts/agents-api/zh/wire-semantics.md +++ b/contracts/agents-api/zh/wire-semantics.md @@ -1,7 +1,7 @@ --- title: "API 行为" source: contracts/agents-api/wire-semantics.md -source_hash: 851e09252847f11040524f329419587687e81d361e4e92c0a3e912d2fd887d45 +source_hash: 6f57c50e736d1837b3609209812438063cc96c24c145ffe9302a93d5f9c7746f --- 已锁定版本的 OpenAI Python SDK([upstream.json](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/contracts/agents-api/upstream.json))定义了 `/v1` 路由、字段和类型。本页面说明这些类型未作规定之处 Core 的行为,例如状态码、错误字段、默认值和列表边界,以及 Core 与官方服务存在差异的地方。[OpenAI 兼容性](index.md) 列出了这些差异和尚存缺口;[Sessions, events and history](sessions-events.md)、[message content](message-content.md)、[Vaults](vaults.md)、[source Files and Skills](source-files.md) 和 [Environment files and Artifacts](environment-files.md) 分别负责各自资源的规则。 @@ -178,6 +178,8 @@ Agent 创建和更新正文以及 Session 创建中的内联 `agent`,会在其 | Function `parameters` 的字符串根 `type` 不是 `object` | null | `Invalid schema for function '': schema must be a JSON Schema of 'type: "object"', got 'type: ""'.` | | `text.format` JSON schema 的字符串根 `type` 不是 `object` | null | `agent.text.format.schema must have top-level type "object"; got ""`,Agent 请求上也会返回此消息 | +Session 创建和更新、Vault 创建、Credential 创建和更新、Environment Template 创建和更新以及 Session events,会在各自解码之前,按同样方式根据已锁定的正文形状进行检查。param 是 JSON 路径,例如 `metadata`、`input[0].role`、`input[0].content[0].type`、`events[0].input[0].role`、`auth.type`、`auth.access_token`、`env.KEY` 或 `name`。`input` 和函数结果的 `output` 接受字符串或数组,其他类型会报告 `expected a string or an array`。Session 的 `agent` 和 `environment` 以及 Template 的 `network` 使用各自的解析器,并先检查其是否为对象。已锁定 schema 未表达的规则以字段作为 param,并给出说明该规则的消息:Vault 和 Credential 的 `name`(去除首尾空白后 1–256 UTF-8 字节)、Template 的 `name`(1–256 个字符)、非空的 `auth.token` 和 `auth.access_token`、HTTPS 的 `auth.mcp_server_url` 和 `auth.refresh.token_endpoint`、RFC 3339 的 `auth.expires_at`、环境变量名(`env.`),以及没有任何可更改内容的 Credential 更新(param 为 `auth`)。 + 在同一个对象内,Core 会先报告联合类型的 `type`,然后报告未知成员,再按文档顺序报告成员值,最后按固定 schema 的顺序报告缺失成员;先检查 tools,再检查 `text`,并在重复项和 schema 根检查之前检查整个对象。没有字符串根 `type` 的 schema 不会被检查。Function 和 output schema、`request_metadata` 和 `x_agents_core` 使用各自的解析器。更新正文和 Session 内联 Agent 会在查找 Agent 之前进行验证,因此属于当前租户、属于外部租户、缺失和格式错误的 Agent ID 会得到相同的响应。 即使所选 Harness 无法执行,Core 也会保存已锁定形状允许的值:任意长度的函数名称,以及 Harness 未声明的 reasoning、service tier、Web 搜索和 programmatic tool calling 取值。 diff --git a/scripts/generate-public-api.py b/scripts/generate-public-api.py index a9621d7f6..22aca5703 100644 --- a/scripts/generate-public-api.py +++ b/scripts/generate-public-api.py @@ -13,8 +13,19 @@ SHAPES = ROOT / 'services/core/internal/api/official_shapes.gen.go' CLIENT_TYPES = ROOT / 'packages/agents-client/src/generated/public-api.ts' CORE_CLIENT_TYPES = ROOT / 'packages/agents-client/src/generated/core-api.ts' -# Agent configuration request bodies checked by Core's shape walker. -REQUEST_SHAPES = ('CreateAgentParams', 'UpdateAgentParams', 'SessionAgentConfigParam') +# Request bodies checked by Core's shape walker, with the members whose values +# have their own Core parser and are only checked to be objects here. +REQUEST_SHAPES = { + 'CreateAgentParams': (), 'UpdateAgentParams': (), 'SessionAgentConfigParam': (), + 'CreateAgentSessionParams': ('agent', 'environment'), + 'UpdateAgentSessionParams': (), + 'CreateVaultParams': (), + 'CreateVaultCredentialParams': (), + 'RotateVaultCredentialParams': (), + 'CreateEnvironmentTemplateParams': ('network',), + 'UpdateEnvironmentTemplateParams': ('network',), + 'CreateSessionEventsParams': (), +} HTTP_METHODS = {'get', 'post', 'put', 'patch', 'delete', 'head', 'options'} @@ -192,7 +203,13 @@ def go_shape(document, schema, required=False): kind = value.get('type') if isinstance(kind, list): kind, = set(kind) - {'null'} - if 'oneOf' in value: + if 'oneOf' in value and 'discriminator' not in value: + # A string or an array, such as the Session input. + string, array = value['oneOf'] + if (string['type'], array['type']) != ('string', 'array'): + raise ValueError(f'Unsupported union: {value["oneOf"]}') + fields = ['kind: stringOrArrayValue', 'items: &' + go_shape(document, array['items'])] + elif 'oneOf' in value: if value['discriminator']['propertyName'] != 'type': raise ValueError(f'Unsupported union discriminator: {value["discriminator"]}') variants = {} @@ -224,19 +241,24 @@ def go_shape(document, schema, required=False): return 'shape{' + ', '.join(fields) + '}' -def go_members(document, schema, skip=None): +def go_members(document, schema, skip=None, opaque=()): # The walker rejects unknown members, so only closed objects project. if schema.get('additionalProperties') is not False: raise ValueError(f'Unsupported open object: {sorted(schema["properties"])}') required = schema.get('required', []) - return '[]member{\n' + ''.join(f'{{{json.dumps(name)}, {go_shape(document, value, name in required)}}},\n' for name, value in schema['properties'].items() if name != skip) + '}' + def member(name, value): + if name not in opaque: + return go_shape(document, value, name in required) + fields = ['kind: openObject'] + (['required: true'] if name in required else []) + (['nullable: true'] if nullable(document, value) else []) + return 'shape{' + ', '.join(fields) + '}' + return '[]member{\n' + ''.join(f'{{{json.dumps(name)}, {member(name, value)}}},\n' for name, value in schema['properties'].items() if name != skip) + '}' def request_shapes(document, owners): lines = ['// Code generated by scripts/generate-public-api.py; DO NOT EDIT.', 'package api', '', '// Pinned request shapes; x_agents_core is checked by its own parser.', 'var ('] - for name in REQUEST_SHAPES: - members = go_members(document, resolve(document, '#/components/schemas/' + name)) + for name, opaque in REQUEST_SHAPES.items(): + members = go_members(document, resolve(document, '#/components/schemas/' + name), opaque=opaque) if name in owners: members = members[:-1] + '{"x_agents_core", shape{}},\n}' lines.append(f'{name[0].lower() + name[1:]} = shape{{kind: objectValue, members: {members}}}') diff --git a/services/core/internal/api/configuration_validation.go b/services/core/internal/api/configuration_validation.go index f78dcd771..8220ef533 100644 --- a/services/core/internal/api/configuration_validation.go +++ b/services/core/internal/api/configuration_validation.go @@ -9,28 +9,29 @@ import ( "strings" ) -// Agent configuration protocol validation is owned by Core. It covers saved -// Agent create and update bodies and the inline Session agent, and runs before -// the configuration parsers (which keep Core's local limits and codes) and -// before harness admission. It walks the raw JSON along the request shapes that -// scripts/generate-public-api.py projects from the pinned schema -// (official_shapes.gen.go) and reports the first violation as a fieldError with -// the JSON path as param and the official message forms. x_agents_core keeps -// its own parser. +// Request protocol validation is owned by Core. It covers the Agent, Session, +// Vault, Credential, Environment Template and Session event bodies and the +// inline Session agent, and runs before the local parsers (which keep Core's +// limits and codes) and before harness admission. It walks the raw JSON along +// the request shapes that scripts/generate-public-api.py projects from the +// pinned schema (official_shapes.gen.go) and reports the first violation as a +// fieldError with the JSON path as param and the official message forms. +// x_agents_core keeps its own parser. type valueKind uint8 const ( - anyValue valueKind = iota // validated by its own parser - stringValue // str - booleanValue // bool - integerValue // int with an inclusive minimum - enumValue // Literal[...] of strings - arrayValue // Iterable/SequenceNotStr of items - mapValue // Dict[str, object], or Dict[str, str] with items - openObject // an object whose members are validated elsewhere - objectValue // TypedDict members - unionValue // TypedDicts selected by their "type" member + anyValue valueKind = iota // validated by its own parser + stringValue // str + booleanValue // bool + integerValue // int with an inclusive minimum + enumValue // Literal[...] of strings + arrayValue // Iterable/SequenceNotStr of items + mapValue // Dict[str, object], or Dict[str, str] with items + openObject // an object whose members are validated elsewhere + objectValue // TypedDict members + unionValue // TypedDicts selected by their "type" member + stringOrArrayValue // a str, or an Iterable of items ) type shape struct { @@ -51,8 +52,17 @@ type member struct { var requiredString = shape{kind: stringValue, required: true} -// validateSavedAgentBody checks a saved Agent create or update body. Malformed -// and non-object bodies keep the existing whole-body error. +// validateBody checks a request body against its pinned shape. Malformed and +// non-object bodies keep the existing whole-body error. +func validateBody(raw []byte, root shape) error { + if !json.Valid(raw) || jsonValueKind(raw) != "an object" { + return nil + } + return checkValue("", raw, root) +} + +// validateSavedAgentBody checks a saved Agent create or update body, then the +// semantic rules of its configuration. func validateSavedAgentBody(raw []byte, root shape) error { if !json.Valid(raw) || jsonValueKind(raw) != "an object" { return nil @@ -143,9 +153,16 @@ func checkValue(path string, raw json.RawMessage, s shape) error { return invalidType(path, "an integer", got) } return checkMinimum(path, string(bytes.TrimSpace(raw)), s.minimum) - case arrayValue: + case arrayValue, stringOrArrayValue: + expected := "an array" + if s.kind == stringOrArrayValue { + if got == "a string" { + return nil + } + expected = "a string or an array" + } if got != "an array" { - return invalidType(path, "an array", got) + return invalidType(path, expected, got) } var items []json.RawMessage if err := json.Unmarshal(raw, &items); err != nil { @@ -211,15 +228,13 @@ func checkValue(path string, raw json.RawMessage, s shape) error { // which encoding/json would merge, never reach it: the shared body gate // (readJSONObject) rejects them first. func checkMembers(path string, raw json.RawMessage, members []member) error { - keys, fields := orderedMembers(raw) - for _, key := range keys { - if _, known := findMember(members, key); !known { - if !echoableField(key) { - return errUnknownParameter - } - return &fieldError{param: joinPath(path, key), message: fmt.Sprintf("Unknown parameter: '%s'.", joinPath(path, key))} + if key, unknown := unknownMember(raw, members); unknown { + if !echoableField(key) { + return errUnknownParameter } + return &fieldError{param: joinPath(path, key), message: fmt.Sprintf("Unknown parameter: '%s'.", joinPath(path, key))} } + keys, fields := orderedMembers(raw) for _, key := range keys { spec, _ := findMember(members, key) if err := checkValue(joinPath(path, key), fields[key], spec.shape); err != nil { @@ -234,6 +249,31 @@ func checkMembers(path string, raw json.RawMessage, members []member) error { return nil } +// unknownMember returns the first key outside members in document order. It +// stops there and keeps no map, so a body of many unknown keys costs no more +// than its first one. +func unknownMember(raw json.RawMessage, members []member) (string, bool) { + decoder := json.NewDecoder(bytes.NewReader(raw)) + if token, err := decoder.Token(); err != nil || token != json.Delim('{') { + return "", false + } + for decoder.More() { + token, err := decoder.Token() + key, isKey := token.(string) + if err != nil || !isKey { + return "", false + } + if _, known := findMember(members, key); !known { + return key, true + } + var value json.RawMessage + if decoder.Decode(&value) != nil { + return "", false + } + } + return "", false +} + // configurationConflict reports the official semantic rejections of a // well-formed configuration: a non-object schema root, a repeated function name // and a repeated web_search or tool_search declaration. Schemas without a string diff --git a/services/core/internal/api/credentials.go b/services/core/internal/api/credentials.go index 62d0cf985..ec2cb94a4 100644 --- a/services/core/internal/api/credentials.go +++ b/services/core/internal/api/credentials.go @@ -1,6 +1,7 @@ package api import ( + "cmp" "encoding/json" "net/http" @@ -13,42 +14,33 @@ import ( func (h *Handler) createCredential(w http.ResponseWriter, r *http.Request) { vaultID := chi.URLParam(r, "vault_id") raw, ok := readJSONObject(w, r) - if !ok { + if !ok || writeFieldError(w, validateBody(raw, createVaultCredentialParams)) { return } var request struct { - Name *string `json:"name"` + Name string `json:"name"` Auth json.RawMessage `json:"auth"` } - if decodeInputObject(raw, &request, "name", "auth") != nil || request.Name == nil { - writeError(w, http.StatusBadRequest, "invalid_request", "name and supported auth are required.") - return - } - name, err := normalizedVaultName(*request.Name) - if err != nil { - writeError(w, http.StatusBadRequest, "invalid_request", err.Error()) + _ = json.Unmarshal(raw, &request) + name, err := normalizedVaultName(request.Name) + if writeFieldError(w, err) { return } + var auth v1.CredentialAuthInput + _ = json.Unmarshal(request.Auth, &auth) var credential vaults.Credential - switch credentialAuthType(request.Auth) { - case "static_bearer": - var auth v1.CredentialAuthInput - if decodeInputObject(request.Auth, &auth, "type", "mcp_server_url", "token") != nil || auth.Token == nil || *auth.Token == "" || !credentialHTTPSURL(auth.MCPServerURL) { - writeError(w, http.StatusBadRequest, "invalid_request", "static_bearer requires a nonempty string token and an absolute HTTPS mcp_server_url without userinfo or a fragment.") + if auth.Type == "static_bearer" { + if writeFieldError(w, cmp.Or(httpsURL("auth.mcp_server_url", *auth.MCPServerURL), nonEmptyString("auth.token", *auth.Token))) { return } credential, err = h.Vaults.CreateStaticCredential(r.Context(), vaults.CreateStaticCredential{TenantID: tenantID(r), VaultID: vaultID, Name: name, MCPServerURL: *auth.MCPServerURL, Token: *auth.Token}) - case "mcp_oauth": - command, parseErr := oauthCredentialCreate(request.Auth, name) - if parseErr != nil { - writeVaultsError(w, r, parseErr) + } else { + command, fieldErr := oauthCredentialCreate(auth, name) + if writeFieldError(w, fieldErr) { return } command.TenantID, command.VaultID = tenantID(r), vaultID credential, err = h.Vaults.CreateOAuthCredential(r.Context(), command) - default: - writeError(w, http.StatusBadRequest, "invalid_request", "auth requires type static_bearer or mcp_oauth.") - return } if err != nil { writeVaultsError(w, r, err) diff --git a/services/core/internal/api/credentials_oauth.go b/services/core/internal/api/credentials_oauth.go index 4e384f66a..fa2db1407 100644 --- a/services/core/internal/api/credentials_oauth.go +++ b/services/core/internal/api/credentials_oauth.go @@ -1,6 +1,7 @@ package api import ( + "cmp" "encoding/json" "net/url" "regexp" @@ -10,115 +11,78 @@ import ( "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/vaults" ) -func credentialHTTPSURL(value *string) bool { - if value == nil { - return false +// The helpers below check the Core-local rules that the pinned schema does not +// express; each names its field. +func nonEmptyString(path, value string) error { + if value == "" { + return &fieldError{param: path, message: path + " must be a nonempty string."} } - u, err := url.Parse(*value) - return err == nil && u.Scheme == "https" && u.Hostname() != "" && u.User == nil && u.Fragment == "" + return nil } -var credentialTimestamp = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$`) - -func credentialExpiry(value *string) bool { - if value == nil { - return true - } - if !credentialTimestamp.MatchString(*value) { - return false +func httpsURL(path, value string) error { + u, err := url.Parse(value) + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" { + return &fieldError{param: path, message: path + " must be an absolute HTTPS URL without userinfo or a fragment."} } - _, err := time.Parse(time.RFC3339Nano, *value) - return err == nil + return nil } -// credentialAuthType reads the exact type member; a case variant is unknown. -func credentialAuthType(raw json.RawMessage) string { - var fields map[string]json.RawMessage - var value string - if json.Unmarshal(raw, &fields) != nil || json.Unmarshal(fields["type"], &value) != nil { - return "" +var credentialTimestamp = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$`) + +func credentialExpiry(path string, value *string) error { + if value != nil { + if _, err := time.Parse(time.RFC3339Nano, *value); err != nil || !credentialTimestamp.MatchString(*value) { + return &fieldError{param: path, message: path + " must be an RFC 3339 timestamp."} + } } - return value + return nil } -// oauthCredentialCreate parses an mcp_oauth creation; the caller sets the -// tenant and Vault. -func oauthCredentialCreate(raw json.RawMessage, name string) (vaults.CreateOAuthCredential, error) { - var auth v1.CredentialAuthInput - input := vaults.CreateOAuthCredential{Name: name} - if decodeInputObject(raw, &auth, "type", "mcp_server_url", "access_token", "expires_at", "refresh") != nil || auth.Type != "mcp_oauth" || auth.AccessToken == nil || *auth.AccessToken == "" || !credentialHTTPSURL(auth.MCPServerURL) || !credentialExpiry(auth.ExpiresAt) { - return input, vaults.ErrInvalidInput - } - input.MCPServerURL, input.AccessToken = *auth.MCPServerURL, *auth.AccessToken +// oauthCredentialCreate parses an mcp_oauth creation whose shape is checked; +// the caller sets the tenant and Vault. +func oauthCredentialCreate(auth v1.CredentialAuthInput, name string) (vaults.CreateOAuthCredential, error) { + input := vaults.CreateOAuthCredential{Name: name, MCPServerURL: *auth.MCPServerURL, AccessToken: *auth.AccessToken} input.OAuth.ExpiresAt = auth.ExpiresAt - if r := auth.Refresh; r != nil { - if r.ClientID == nil || r.RefreshToken == nil || !credentialHTTPSURL(r.TokenEndpoint) || r.TokenEndpointAuth == nil { - return input, vaults.ErrInvalidInput - } + err := cmp.Or(httpsURL("auth.mcp_server_url", input.MCPServerURL), nonEmptyString("auth.access_token", input.AccessToken), credentialExpiry("auth.expires_at", auth.ExpiresAt)) + if r := auth.Refresh; err == nil && r != nil { a := r.TokenEndpointAuth - switch a.Type { - case "none": - // Presence of client_secret is invalid even when explicitly null. - var fields struct { - Refresh struct { - Auth json.RawMessage `json:"token_endpoint_auth"` - } `json:"refresh"` - } - if json.Unmarshal(raw, &fields) != nil || decodeInputObject(fields.Refresh.Auth, &struct { - Type string `json:"type"` - }{}, "type") != nil { - return input, vaults.ErrInvalidInput - } - case "client_secret_basic", "client_secret_post": - if a.ClientSecret == nil { - return input, vaults.ErrInvalidInput - } + if a.ClientSecret != nil { input.ClientSecret = *a.ClientSecret - default: - return input, vaults.ErrInvalidInput } input.RefreshToken = *r.RefreshToken input.OAuth.Refresh = &vaults.OAuthRefreshMetadata{ClientID: *r.ClientID, TokenEndpoint: *r.TokenEndpoint, TokenEndpointAuth: a.Type, Resource: r.Resource, Scope: r.Scope} + err = httpsURL("auth.refresh.token_endpoint", *r.TokenEndpoint) } - return input, nil + return input, err } -// oauthCredentialUpdate parses an mcp_oauth patch; the caller sets the -// Credential's identity. -func oauthCredentialUpdate(raw json.RawMessage) (vaults.UpdateOAuthCredential, error) { - var auth v1.CredentialAuthReplacement - var input vaults.UpdateOAuthCredential - if decodeInputObject(raw, &auth, "type", "access_token", "expires_at", "refresh") != nil || auth.Type != "mcp_oauth" { - return input, vaults.ErrInvalidInput - } - input.AccessToken = auth.AccessToken - if input.AccessToken != nil && *input.AccessToken == "" { - return input, vaults.ErrInvalidInput +// oauthCredentialUpdate parses an mcp_oauth patch whose shape is checked; the +// caller sets the Credential's identity. +func oauthCredentialUpdate(auth v1.CredentialAuthReplacement) (vaults.UpdateOAuthCredential, error) { + input := vaults.UpdateOAuthCredential{AccessToken: auth.AccessToken} + var err error + if input.AccessToken != nil { + err = nonEmptyString("auth.access_token", *input.AccessToken) } if len(auth.ExpiresAt) > 0 { input.ExpiresAtSet = true - if json.Unmarshal(auth.ExpiresAt, &input.ExpiresAt) != nil || !credentialExpiry(input.ExpiresAt) { - return input, vaults.ErrInvalidInput - } + _ = json.Unmarshal(auth.ExpiresAt, &input.ExpiresAt) + err = cmp.Or(err, credentialExpiry("auth.expires_at", input.ExpiresAt)) } if r := auth.Refresh; r != nil { input.Refresh = &vaults.OAuthRefreshUpdate{RefreshToken: r.RefreshToken} if len(r.Scope) > 0 { input.Refresh.ScopeSet = true - if json.Unmarshal(r.Scope, &input.Refresh.Scope) != nil { - return input, vaults.ErrInvalidInput - } + _ = json.Unmarshal(r.Scope, &input.Refresh.Scope) } if a := r.TokenEndpointAuth; a != nil { - if a.Type != "client_secret_basic" && a.Type != "client_secret_post" { - return input, vaults.ErrInvalidInput - } input.Refresh.TokenEndpointAuthType, input.Refresh.ClientSecret = a.Type, a.ClientSecret } } - if input.AccessToken == nil && !input.ExpiresAtSet && (input.Refresh == nil || + if err == nil && input.AccessToken == nil && !input.ExpiresAtSet && (input.Refresh == nil || (input.Refresh.RefreshToken == nil && input.Refresh.ClientSecret == nil && !input.Refresh.ScopeSet)) { - return input, vaults.ErrInvalidInput + err = &fieldError{param: "auth", message: "auth requires access_token, expires_at or refresh to update."} } - return input, nil + return input, err } diff --git a/services/core/internal/api/credentials_update.go b/services/core/internal/api/credentials_update.go index a47108a35..75c3b81a1 100644 --- a/services/core/internal/api/credentials_update.go +++ b/services/core/internal/api/credentials_update.go @@ -12,37 +12,28 @@ import ( func (h *Handler) updateCredential(w http.ResponseWriter, r *http.Request) { vaultID, id := chi.URLParam(r, "vault_id"), chi.URLParam(r, "credential_id") raw, ok := readJSONObject(w, r) - if !ok { + if !ok || writeFieldError(w, validateBody(raw, rotateVaultCredentialParams)) { return } var request struct { - Auth json.RawMessage `json:"auth"` - } - if decodeInputObject(raw, &request, "auth") != nil { - writeError(w, http.StatusBadRequest, "invalid_request", "auth with a supported type is required.") - return + Auth v1.CredentialAuthReplacement `json:"auth"` } + _ = json.Unmarshal(raw, &request) + auth := request.Auth var credential vaults.Credential var err error - switch credentialAuthType(request.Auth) { - case "static_bearer": - var auth v1.CredentialAuthReplacement - if decodeInputObject(request.Auth, &auth, "type", "token") != nil || auth.Token == nil || *auth.Token == "" { - writeError(w, http.StatusBadRequest, "invalid_request", "static_bearer auth requires a nonempty string token.") + if auth.Type == "static_bearer" { + if writeFieldError(w, nonEmptyString("auth.token", *auth.Token)) { return } credential, err = h.Vaults.UpdateStaticCredential(r.Context(), vaults.UpdateStaticCredential{TenantID: tenantID(r), VaultID: vaultID, CredentialID: id, Token: *auth.Token}) - case "mcp_oauth": - command, parseErr := oauthCredentialUpdate(request.Auth) - if parseErr != nil { - writeVaultsError(w, r, parseErr) + } else { + command, fieldErr := oauthCredentialUpdate(auth) + if writeFieldError(w, fieldErr) { return } command.TenantID, command.VaultID, command.CredentialID = tenantID(r), vaultID, id credential, err = h.Vaults.UpdateOAuthCredential(r.Context(), command) - default: - writeError(w, http.StatusBadRequest, "invalid_request", "auth requires type static_bearer or mcp_oauth.") - return } if err != nil { writeVaultsError(w, r, err) diff --git a/services/core/internal/api/environment_templates.go b/services/core/internal/api/environment_templates.go index 5104f895f..c0240d057 100644 --- a/services/core/internal/api/environment_templates.go +++ b/services/core/internal/api/environment_templates.go @@ -3,9 +3,13 @@ package api import ( "context" "encoding/json" + "fmt" + "maps" "net/http" + "slices" v1 "github.com/MiniMax-AI/OpenAgentCore/contracts/agents-api/v1" + "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/environmentconfig" "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/environmenttemplates" "github.com/go-chi/chi/v5" ) @@ -33,11 +37,17 @@ func decodeTemplateInput(raw []byte) (environmenttemplates.Input, error) { in := environmenttemplates.Input{} if value, supplied := fields["name"]; supplied { in.SetName = true - if json.Unmarshal(value, &in.Name) != nil || environmenttemplates.ValidateName(in.Name) != nil { + if json.Unmarshal(value, &in.Name) != nil { return in, environmenttemplates.ErrInvalidInput } + if environmenttemplates.ValidateName(in.Name) != nil { + return in, &fieldError{param: "name", message: fmt.Sprintf("name must contain 1 to %d characters.", environmenttemplates.MaxNameLength)} + } } delete(fields, "name") + if err := templateEnvError(fields["env"]); err != nil { + return in, err + } _, in.SetNetwork = fields["network"] _, in.SetFiles = fields["files"] _, in.SetEnv = fields["env"] @@ -70,13 +80,29 @@ func decodeTemplateInput(raw []byte) (environmenttemplates.Input, error) { return in, nil } +// templateEnvError names the first environment variable Core cannot set. +func templateEnvError(raw json.RawMessage) error { + var env map[string]string + _ = json.Unmarshal(raw, &env) + for _, name := range slices.Sorted(maps.Keys(env)) { + if !environmentconfig.ValidEnvironmentEntry(name, env[name]) { + param := "env" + if echoableField(name) { + param += "." + name + } + return &fieldError{param: param, message: "Environment variable names must match [A-Za-z_][A-Za-z0-9_]* and must not be PATH, OPENAI_API_KEY or start with CODEX_ or OAC_; values must not contain U+0000."} + } + } + return nil +} + func templateResponse(t environmenttemplates.Template) v1.EnvironmentTemplate { return v1.EnvironmentTemplate{ID: t.ID, Object: "agent.environment.template", Name: t.Name, CreatedAt: t.CreatedAt.Unix(), UpdatedAt: t.UpdatedAt.Unix(), CapabilityDirectories: append([]string{}, t.CapabilityDirectories...), Network: v1.EnvironmentNetwork{Access: t.NetworkAccess, AllowedDomains: append([]string{}, t.AllowedDomains...)}, Packages: packageMetadata(&t.Packages), Files: templateFileResponse(t.Files), Plugins: pluginResponse(t.Plugins), Skills: skillResponse(t.Skills)} } -func readTemplateInput(w http.ResponseWriter, r *http.Request) (environmenttemplates.Input, bool) { +func readTemplateInput(w http.ResponseWriter, r *http.Request, pinned shape) (environmenttemplates.Input, bool) { raw, ok := readJSONObjectLimit(w, r, 16*1024*1024, "Request exceeds 16 MiB.") - if !ok { + if !ok || writeFieldError(w, validateBody(raw, pinned)) { return environmenttemplates.Input{}, false } in, err := decodeTemplateInput(raw) @@ -91,7 +117,7 @@ func readTemplateInput(w http.ResponseWriter, r *http.Request) (environmenttempl } func (h *Handler) createEnvironmentTemplate(w http.ResponseWriter, r *http.Request) { - in, ok := readTemplateInput(w, r) + in, ok := readTemplateInput(w, r, createEnvironmentTemplateParams) if !ok { return } @@ -113,7 +139,7 @@ func (h *Handler) getEnvironmentTemplate(w http.ResponseWriter, r *http.Request) } func (h *Handler) updateEnvironmentTemplate(w http.ResponseWriter, r *http.Request) { - in, ok := readTemplateInput(w, r) + in, ok := readTemplateInput(w, r, updateEnvironmentTemplateParams) if !ok { return } diff --git a/services/core/internal/api/function_inputs.go b/services/core/internal/api/function_inputs.go index ab62b47e2..5df7fb2c9 100644 --- a/services/core/internal/api/function_inputs.go +++ b/services/core/internal/api/function_inputs.go @@ -24,26 +24,6 @@ func decodeInputEvent(raw json.RawMessage) (decodedInputEvent, error) { switch event.Type { case "agent.session.input.message": fields = append(fields, "input") - var messages struct { - Input []struct { - Type json.RawMessage `json:"type"` - Content json.RawMessage `json:"content"` - } `json:"input"` - } - if json.Unmarshal(raw, &messages) != nil { - return event, sessions.ErrInvalidInput - } - for _, message := range messages.Input { - if len(message.Type) > 0 { - var kind string - if json.Unmarshal(message.Type, &kind) != nil || kind != "message" { - return event, sessions.ErrInvalidInput - } - } - if err := validateInputContent(message.Content); err != nil { - return event, err - } - } case "agent.session.input.cancel": case "agent.session.input.tool_result": fields = append(fields, "call_id", "turn_id", "success", "error", "output") @@ -80,15 +60,6 @@ func functionResultInput(event decodedInputEvent) (sessions.Input, error) { if event.CallID == "" || event.TurnID == "" || event.Success == nil { return sessions.Input{}, sessions.ErrInvalidInput } - if len(event.Error) > 0 && !bytes.Equal(bytes.TrimSpace(event.Error), []byte("null")) { - var message string - if json.Unmarshal(event.Error, &message) != nil { - return sessions.Input{}, sessions.ErrInvalidInput - } - } - if err := validateFunctionOutput(event.Output); err != nil { - return sessions.Input{}, err - } result, err := json.Marshal(struct { Success bool `json:"success"` Error json.RawMessage `json:"error,omitempty"` @@ -100,49 +71,3 @@ func functionResultInput(event decodedInputEvent) (sessions.Input, error) { payload, err := json.Marshal(sessions.FunctionResultInput{TurnID: event.TurnID, CallID: event.CallID, Result: result}) return sessions.Input{Kind: "tool_result", Payload: payload}, err } - -func validateFunctionOutput(raw json.RawMessage) error { - if len(raw) == 0 || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { - return nil - } - var text string - if json.Unmarshal(raw, &text) == nil { - return nil - } - return validateInputContent(raw) -} - -func validateInputContent(raw json.RawMessage) error { - var parts []json.RawMessage - if json.Unmarshal(raw, &parts) != nil { - return sessions.ErrInvalidInput - } - for _, part := range parts { - var value struct { - Type string `json:"type"` - Text *string `json:"text"` - ImageURL *string `json:"image_url"` - } - if json.Unmarshal(part, &value) != nil { - return sessions.ErrInvalidInput - } - field := "text" - switch value.Type { - case "input_text": - if value.Text == nil { - return sessions.ErrInvalidInput - } - case "input_image": - field = "image_url" - if value.ImageURL == nil { - return sessions.ErrInvalidInput - } - default: - return sessions.ErrInvalidInput - } - if err := decodeInputObject(part, &value, "type", field); err != nil { - return err - } - } - return nil -} diff --git a/services/core/internal/api/handler.go b/services/core/internal/api/handler.go index 8f7d59d4b..2f5f3b303 100644 --- a/services/core/internal/api/handler.go +++ b/services/core/internal/api/handler.go @@ -130,7 +130,7 @@ func (h *Handler) createSession(w http.ResponseWriter, r *http.Request) { if !ok { return } - if writeFieldError(w, metadataTypeError(raw)) { + if writeFieldError(w, validateBody(raw, createAgentSessionParams)) { return } var request decodedSessionRequest diff --git a/services/core/internal/api/inputs.go b/services/core/internal/api/inputs.go index a55265be1..7b20a09bf 100644 --- a/services/core/internal/api/inputs.go +++ b/services/core/internal/api/inputs.go @@ -1,11 +1,9 @@ package api import ( - "bytes" "context" "encoding/json" "net/http" - "reflect" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/sessions" @@ -22,20 +20,13 @@ type InputAdmission interface { func (h *Handler) createEvents(w http.ResponseWriter, r *http.Request) { raw, ok := readJSONObject(w, r) - if !ok { + if !ok || writeFieldError(w, validateBody(raw, createSessionEventsParams)) { return } var request struct { Events []json.RawMessage `json:"events"` } - decoder := json.NewDecoder(bytes.NewReader(raw)) - decoder.DisallowUnknownFields() - // An unknown member, including a case variant of events, is rejected before - // decoding; see inexactMember. - if inexactMember(raw, reflect.TypeOf(request)) || decoder.Decode(&request) != nil { - writeError(w, http.StatusBadRequest, "invalid_request", "Invalid Session input event request.") - return - } + _ = json.Unmarshal(raw, &request) key := r.Header.Get("Idempotency-Key") if key == "" { key = uuid.NewString() diff --git a/services/core/internal/api/json_members.go b/services/core/internal/api/json_members.go index bac5922cf..22c52c110 100644 --- a/services/core/internal/api/json_members.go +++ b/services/core/internal/api/json_members.go @@ -187,28 +187,3 @@ func jsonFields(t reflect.Type) map[string]reflect.Type { jsonFieldCache.Store(t, fields) return fields } - -// objectMember returns the value of the exact member name of a valid JSON -// object without decoding the other members, or nil. -func objectMember(raw []byte, name string) []byte { - i := skipSpace(raw, 0) - if i == len(raw) || raw[i] != '{' { - return nil - } - var scratch []byte - for i = skipSpace(raw, i+1); raw[i] != '}'; { - end := stringEnd(raw, i) - key := raw[i+1 : end-1] - if bytes.IndexByte(key, '\\') >= 0 { - scratch = appendUnescaped(scratch[:0], key) - key = scratch - } - i = skipSpace(raw, skipSpace(raw, end)+1) - valueEnd := skipValue(raw, i) - if string(key) == name { - return raw[i:valueEnd] - } - i = skipComma(raw, skipSpace(raw, valueEnd)) - } - return nil -} diff --git a/services/core/internal/api/json_members_test.go b/services/core/internal/api/json_members_test.go index ca6c28447..8fd367e8d 100644 --- a/services/core/internal/api/json_members_test.go +++ b/services/core/internal/api/json_members_test.go @@ -60,14 +60,16 @@ func TestInexactMember(t *testing.T) { func TestCaseVariantMembersAreUnknown(t *testing.T) { h, s := validationHandler(t) session := `{"agent":{"model":"m"},"environment":{"type":"none"},"input":"hi"` - unknownSession := `{"error":{"message":"Request must be a JSON object containing supported fields.","type":"invalid_request_error","code":"invalid_request","param":null}}` + "\n" - for _, body := range []string{ - session + `,"Metadata":{"k":"v"}}`, - session + `,"metadata":{"k":"v"},"Metadata":{"k":"w"}}`, - session + `,"Input":"replaced"}`, - session + `,"STREAM":true}`, + unknown := func(name string) string { + return `{"error":{"message":"Unknown parameter: '` + name + `'.","type":"invalid_request_error","code":"invalid_request_error","param":"` + name + `"}}` + "\n" + } + for body, name := range map[string]string{ + session + `,"Metadata":{"k":"v"}}`: "Metadata", + session + `,"metadata":{"k":"v"},"Metadata":{"k":"w"}}`: "Metadata", + session + `,"Input":"replaced"}`: "Input", + session + `,"STREAM":true}`: "STREAM", } { - if w := bodyGateRequest(h, "/v1/agents/sessions", "application/json", []byte(body)); w.Code != http.StatusBadRequest || w.Body.String() != unknownSession { + if w := bodyGateRequest(h, "/v1/agents/sessions", "application/json", []byte(body)); w.Code != http.StatusBadRequest || w.Body.String() != unknown(name) { t.Errorf("%s: %d %s", body, w.Code, w.Body) } } @@ -82,8 +84,7 @@ func TestCaseVariantMembersAreUnknown(t *testing.T) { } } events := "/v1/agents/sessions/" + uuid.NewString() + "/events" - unknownEvents := `{"error":{"message":"Invalid Session input event request.","type":"invalid_request_error","code":"invalid_request","param":null}}` + "\n" - if w := bodyGateRequest(h, events, "application/json", []byte(`{"Events":[]}`)); w.Code != http.StatusBadRequest || w.Body.String() != unknownEvents { + if w := bodyGateRequest(h, events, "application/json", []byte(`{"Events":[]}`)); w.Code != http.StatusBadRequest || w.Body.String() != unknown("Events") { t.Errorf("Events: %d %s", w.Code, w.Body) } message := `{"events":[{"type":"agent.session.input.message","input":[{"role":"assistant","Role":"user","content":[{"type":"input_text","text":"hi"}]}]}]}` @@ -140,8 +141,8 @@ func TestUnknownMembersRejectWithLinearAllocation(t *testing.T) { path, message string body []byte }{ - {"/v1/agents/sessions", "Request must be a JSON object containing supported fields.", unknownKeys(`{"agent":{"model":"m"},"environment":{"type":"none"},"input":"hi","metadata":{"k":"v"},`, 16<<20-64)}, - {"/v1/agents/sessions/" + uuid.NewString() + "/events", "Invalid Session input event request.", unknownKeys(`{"events":[],`, 1<<20-64)}, + {"/v1/agents/sessions", "Unknown parameter: 'k0000000'.", unknownKeys(`{"agent":{"model":"m"},"environment":{"type":"none"},"input":"hi","metadata":{"k":"v"},`, 16<<20-64)}, + {"/v1/agents/sessions/" + uuid.NewString() + "/events", "Unknown parameter: 'k0000000'.", unknownKeys(`{"events":[],`, 1<<20-64)}, } { runtime.GC() var before, after runtime.MemStats diff --git a/services/core/internal/api/official_shapes.gen.go b/services/core/internal/api/official_shapes.gen.go index b4ba45f34..ae71e6d90 100644 --- a/services/core/internal/api/official_shapes.gen.go +++ b/services/core/internal/api/official_shapes.gen.go @@ -207,4 +207,224 @@ var ( }}, nullable: true}}, {"x_agents_core", shape{}}, }} + createAgentSessionParams = shape{kind: objectValue, members: []member{ + {"metadata", shape{kind: mapValue, items: &shape{kind: stringValue}, nullable: true}}, + {"agent", shape{kind: openObject}}, + {"agent_id", shape{kind: stringValue}}, + {"environment", shape{kind: openObject, required: true}}, + {"vault_ids", shape{kind: arrayValue, items: &shape{kind: stringValue}, nullable: true}}, + {"input", shape{kind: stringOrArrayValue, items: &shape{kind: objectValue, members: []member{ + {"type", shape{kind: enumValue, values: []string{"message"}}}, + {"role", shape{kind: enumValue, values: []string{"user"}, required: true}}, + {"content", shape{kind: arrayValue, items: &shape{kind: unionValue, values: []string{"input_text", "input_image"}, variants: map[string][]member{ + "input_text": { + {"text", shape{kind: stringValue, required: true}}, + }, + "input_image": { + {"image_url", shape{kind: stringValue, required: true}}, + }, + }}, required: true}}, + }}, nullable: true}}, + {"stream", shape{kind: booleanValue}}, + {"x_agents_core", shape{}}, + }} + updateAgentSessionParams = shape{kind: objectValue, members: []member{ + {"metadata", shape{kind: mapValue, items: &shape{kind: stringValue}, nullable: true}}, + }} + createVaultParams = shape{kind: objectValue, members: []member{ + {"name", shape{kind: stringValue}}, + {"metadata", shape{kind: mapValue, items: &shape{kind: stringValue}, nullable: true}}, + }} + createVaultCredentialParams = shape{kind: objectValue, members: []member{ + {"name", shape{kind: stringValue, required: true}}, + {"auth", shape{kind: unionValue, values: []string{"mcp_oauth", "static_bearer"}, variants: map[string][]member{ + "mcp_oauth": { + {"mcp_server_url", shape{kind: stringValue, required: true}}, + {"access_token", shape{kind: stringValue, required: true}}, + {"expires_at", shape{kind: stringValue, nullable: true}}, + {"refresh", shape{kind: objectValue, members: []member{ + {"token_endpoint", shape{kind: stringValue, required: true}}, + {"client_id", shape{kind: stringValue, required: true}}, + {"resource", shape{kind: stringValue, nullable: true}}, + {"scope", shape{kind: stringValue, nullable: true}}, + {"refresh_token", shape{kind: stringValue, required: true}}, + {"token_endpoint_auth", shape{kind: unionValue, values: []string{"none", "client_secret_basic", "client_secret_post"}, variants: map[string][]member{ + "none": {}, + "client_secret_basic": { + {"client_secret", shape{kind: stringValue, required: true}}, + }, + "client_secret_post": { + {"client_secret", shape{kind: stringValue, required: true}}, + }, + }, required: true}}, + }, nullable: true}}, + }, + "static_bearer": { + {"mcp_server_url", shape{kind: stringValue, required: true}}, + {"token", shape{kind: stringValue, required: true}}, + }, + }, required: true}}, + }} + rotateVaultCredentialParams = shape{kind: objectValue, members: []member{ + {"auth", shape{kind: unionValue, values: []string{"mcp_oauth", "static_bearer"}, variants: map[string][]member{ + "mcp_oauth": { + {"access_token", shape{kind: stringValue, nullable: true}}, + {"expires_at", shape{kind: stringValue, nullable: true}}, + {"refresh", shape{kind: objectValue, members: []member{ + {"refresh_token", shape{kind: stringValue, nullable: true}}, + {"scope", shape{kind: stringValue, nullable: true}}, + {"token_endpoint_auth", shape{kind: unionValue, values: []string{"client_secret_basic", "client_secret_post"}, variants: map[string][]member{ + "client_secret_basic": { + {"client_secret", shape{kind: stringValue, nullable: true}}, + }, + "client_secret_post": { + {"client_secret", shape{kind: stringValue, nullable: true}}, + }, + }, nullable: true}}, + }, nullable: true}}, + }, + "static_bearer": { + {"token", shape{kind: stringValue, required: true}}, + }, + }, required: true}}, + }} + createEnvironmentTemplateParams = shape{kind: objectValue, members: []member{ + {"packages", shape{kind: objectValue, members: []member{ + {"python", shape{kind: arrayValue, items: &shape{kind: stringValue}, nullable: true}}, + {"system", shape{kind: arrayValue, items: &shape{kind: stringValue}, nullable: true}}, + {"npm", shape{kind: arrayValue, items: &shape{kind: stringValue}, nullable: true}}, + }, nullable: true}}, + {"setup_commands", shape{kind: arrayValue, items: &shape{kind: objectValue, members: []member{ + {"command", shape{kind: stringValue, required: true}}, + {"cwd", shape{kind: stringValue, nullable: true}}, + }}, nullable: true}}, + {"network", shape{kind: openObject, nullable: true}}, + {"env", shape{kind: mapValue, items: &shape{kind: stringValue}, nullable: true}}, + {"capability_directories", shape{kind: arrayValue, items: &shape{kind: stringValue}, nullable: true}}, + {"skills", shape{kind: arrayValue, items: &shape{kind: unionValue, values: []string{"skill_reference", "inline"}, variants: map[string][]member{ + "skill_reference": { + {"skill_id", shape{kind: stringValue, required: true}}, + {"version", shape{kind: stringValue, nullable: true}}, + }, + "inline": { + {"name", shape{kind: stringValue, required: true}}, + {"description", shape{kind: stringValue, required: true}}, + {"source", shape{kind: unionValue, values: []string{"base64"}, variants: map[string][]member{ + "base64": { + {"media_type", shape{kind: enumValue, values: []string{"application/zip"}, required: true}}, + {"data", shape{kind: stringValue, required: true}}, + }, + }, required: true}}, + }, + }}, nullable: true}}, + {"plugins", shape{kind: arrayValue, items: &shape{kind: unionValue, values: []string{"inline"}, variants: map[string][]member{ + "inline": { + {"name", shape{kind: stringValue, required: true}}, + {"description", shape{kind: stringValue, required: true}}, + {"source", shape{kind: unionValue, values: []string{"base64"}, variants: map[string][]member{ + "base64": { + {"media_type", shape{kind: enumValue, values: []string{"application/zip"}, required: true}}, + {"data", shape{kind: stringValue, required: true}}, + }, + }, required: true}}, + }, + }}, nullable: true}}, + {"files", shape{kind: arrayValue, items: &shape{kind: unionValue, values: []string{"file_id", "inline"}, variants: map[string][]member{ + "file_id": { + {"file_id", shape{kind: stringValue, required: true}}, + {"path", shape{kind: stringValue, required: true}}, + }, + "inline": { + {"data", shape{kind: stringValue, required: true}}, + {"path", shape{kind: stringValue, required: true}}, + }, + }}, nullable: true}}, + {"name", shape{kind: stringValue, nullable: true}}, + }} + updateEnvironmentTemplateParams = shape{kind: objectValue, members: []member{ + {"name", shape{kind: stringValue, nullable: true}}, + {"packages", shape{kind: objectValue, members: []member{ + {"python", shape{kind: arrayValue, items: &shape{kind: stringValue}, nullable: true}}, + {"system", shape{kind: arrayValue, items: &shape{kind: stringValue}, nullable: true}}, + {"npm", shape{kind: arrayValue, items: &shape{kind: stringValue}, nullable: true}}, + }, nullable: true}}, + {"setup_commands", shape{kind: arrayValue, items: &shape{kind: objectValue, members: []member{ + {"command", shape{kind: stringValue, required: true}}, + {"cwd", shape{kind: stringValue, nullable: true}}, + }}, nullable: true}}, + {"network", shape{kind: openObject, nullable: true}}, + {"env", shape{kind: mapValue, items: &shape{kind: stringValue}, nullable: true}}, + {"capability_directories", shape{kind: arrayValue, items: &shape{kind: stringValue}, nullable: true}}, + {"skills", shape{kind: arrayValue, items: &shape{kind: unionValue, values: []string{"skill_reference", "inline"}, variants: map[string][]member{ + "skill_reference": { + {"skill_id", shape{kind: stringValue, required: true}}, + {"version", shape{kind: stringValue, nullable: true}}, + }, + "inline": { + {"name", shape{kind: stringValue, required: true}}, + {"description", shape{kind: stringValue, required: true}}, + {"source", shape{kind: unionValue, values: []string{"base64"}, variants: map[string][]member{ + "base64": { + {"media_type", shape{kind: enumValue, values: []string{"application/zip"}, required: true}}, + {"data", shape{kind: stringValue, required: true}}, + }, + }, required: true}}, + }, + }}, nullable: true}}, + {"plugins", shape{kind: arrayValue, items: &shape{kind: unionValue, values: []string{"inline"}, variants: map[string][]member{ + "inline": { + {"name", shape{kind: stringValue, required: true}}, + {"description", shape{kind: stringValue, required: true}}, + {"source", shape{kind: unionValue, values: []string{"base64"}, variants: map[string][]member{ + "base64": { + {"media_type", shape{kind: enumValue, values: []string{"application/zip"}, required: true}}, + {"data", shape{kind: stringValue, required: true}}, + }, + }, required: true}}, + }, + }}, nullable: true}}, + {"files", shape{kind: arrayValue, items: &shape{kind: unionValue, values: []string{"file_id", "inline"}, variants: map[string][]member{ + "file_id": { + {"file_id", shape{kind: stringValue, required: true}}, + {"path", shape{kind: stringValue, required: true}}, + }, + "inline": { + {"data", shape{kind: stringValue, required: true}}, + {"path", shape{kind: stringValue, required: true}}, + }, + }}, nullable: true}}, + }} + createSessionEventsParams = shape{kind: objectValue, members: []member{ + {"events", shape{kind: arrayValue, items: &shape{kind: unionValue, values: []string{"agent.session.input.message", "agent.session.input.cancel", "agent.session.input.tool_result"}, variants: map[string][]member{ + "agent.session.input.message": { + {"input", shape{kind: arrayValue, items: &shape{kind: objectValue, members: []member{ + {"type", shape{kind: enumValue, values: []string{"message"}}}, + {"role", shape{kind: enumValue, values: []string{"user"}, required: true}}, + {"content", shape{kind: arrayValue, items: &shape{kind: unionValue, values: []string{"input_text", "input_image"}, variants: map[string][]member{ + "input_text": { + {"text", shape{kind: stringValue, required: true}}, + }, + "input_image": { + {"image_url", shape{kind: stringValue, required: true}}, + }, + }}, required: true}}, + }}, required: true}}, + }, + "agent.session.input.cancel": {}, + "agent.session.input.tool_result": { + {"turn_id", shape{kind: stringValue, required: true}}, + {"call_id", shape{kind: stringValue, required: true}}, + {"success", shape{kind: booleanValue, required: true}}, + {"output", shape{kind: stringOrArrayValue, items: &shape{kind: unionValue, values: []string{"input_text", "input_image"}, variants: map[string][]member{ + "input_text": { + {"text", shape{kind: stringValue, required: true}}, + }, + "input_image": { + {"image_url", shape{kind: stringValue, required: true}}, + }, + }}, nullable: true}}, + {"error", shape{kind: stringValue, nullable: true}}, + }, + }}, required: true}}, + }} ) diff --git a/services/core/internal/api/request_shapes_test.go b/services/core/internal/api/request_shapes_test.go new file mode 100644 index 000000000..0c9d49b1a --- /dev/null +++ b/services/core/internal/api/request_shapes_test.go @@ -0,0 +1,53 @@ +package api + +import ( + "net/http" + "testing" + + "github.com/google/uuid" +) + +// The Session, Vault, Credential, Template and event bodies follow the pinned +// request shapes: a field error names the offending field as param. +func TestRequestShapesReportFieldErrors(t *testing.T) { + validation, _ := validationHandler(t) + credentials, f, _ := credentialHandler(t) + session := uuid.NewString() + credentialPath := "/v1/vaults/" + f.credential.VaultID + "/credentials" + const agent = `"agent":{"model":"m"},"environment":{"type":"none"}` + for _, tc := range []struct { + name string + handler http.Handler + path, body string + param, error string + }{ + {"session unknown member", validation, "/v1/agents/sessions", `{` + agent + `,"x":1}`, "x", "Unknown parameter: 'x'."}, + {"session metadata", validation, "/v1/agents/sessions", `{` + agent + `,"metadata":[]}`, "metadata", "Invalid type for 'metadata': expected an object with string keys and string values, but got an array instead."}, + {"session role", validation, "/v1/agents/sessions", `{` + agent + `,"input":[{"role":"assistant","content":[]}]}`, "input[0].role", "Invalid value: 'assistant'. Supported values are: 'user'."}, + {"session content type", validation, "/v1/agents/sessions", `{` + agent + `,"input":[{"role":"user","content":[{"type":"input_audio"}]}]}`, "input[0].content[0].type", "Invalid value: 'input_audio'. Supported values are: 'input_text' and 'input_image'."}, + {"session update unknown member", validation, "/v1/agents/sessions/" + session, `{"x":1}`, "x", "Unknown parameter: 'x'."}, + {"session update metadata", validation, "/v1/agents/sessions/" + session, `{"metadata":1}`, "metadata", "Invalid type for 'metadata': expected an object with string keys and string values, but got an integer instead."}, + {"event role", validation, "/v1/agents/sessions/" + session + "/events", `{"events":[{"type":"agent.session.input.message","input":[{"role":"system","content":[]}]}]}`, "events[0].input[0].role", "Invalid value: 'system'. Supported values are: 'user'."}, + {"vault name", validation, "/v1/vaults", `{"name":1}`, "name", "Invalid type for 'name': expected a string, but got an integer instead."}, + {"vault unknown member", validation, "/v1/vaults", `{"foo":1}`, "foo", "Unknown parameter: 'foo'."}, + {"template name", validation, "/v1/agents/environments/templates", `{"name":1}`, "name", "Invalid type for 'name': expected a string, but got an integer instead."}, + {"template name length", validation, "/v1/agents/environments/templates", `{"name":""}`, "name", "name must contain 1 to 256 characters."}, + {"template env value", validation, "/v1/agents/environments/templates/" + uuid.NewString(), `{"env":{"KEY":1}}`, "env.KEY", "Invalid type for 'env.KEY': expected a string, but got an integer instead."}, + {"template env name", validation, "/v1/agents/environments/templates", `{"env":{"PATH":"x"}}`, "env.PATH", "Environment variable names must match [A-Za-z_][A-Za-z0-9_]* and must not be PATH, OPENAI_API_KEY or start with CODEX_ or OAC_; values must not contain U+0000."}, + {"credential missing token", credentials, credentialPath, `{"name":"n","auth":{"type":"static_bearer","mcp_server_url":"https://mcp.example/tools"}}`, "auth.token", "Missing required parameter: 'auth.token'."}, + {"credential auth type", credentials, credentialPath, `{"name":"n","auth":{"type":"basic"}}`, "auth.type", "Invalid value: 'basic'. Supported values are: 'mcp_oauth' and 'static_bearer'."}, + {"credential missing access token", credentials, credentialPath, `{"name":"n","auth":{"type":"mcp_oauth","mcp_server_url":"https://mcp.example/tools"}}`, "auth.access_token", "Missing required parameter: 'auth.access_token'."}, + {"credential url", credentials, credentialPath, `{"name":"n","auth":{"type":"static_bearer","mcp_server_url":"http://mcp.example","token":"t"}}`, "auth.mcp_server_url", "auth.mcp_server_url must be an absolute HTTPS URL without userinfo or a fragment."}, + {"credential empty token", credentials, credentialPath, `{"name":"n","auth":{"type":"static_bearer","mcp_server_url":"https://mcp.example","token":""}}`, "auth.token", "auth.token must be a nonempty string."}, + {"rotate unknown member", credentials, credentialPath + "/" + f.credential.ID, `{"auth":{"type":"static_bearer","token":"t","mcp_server_url":"https://mcp.example"}}`, "auth.mcp_server_url", "Unknown parameter: 'auth.mcp_server_url'."}, + {"rotate empty update", credentials, credentialPath + "/" + f.credential.ID, `{"auth":{"type":"mcp_oauth"}}`, "auth", "auth requires access_token, expires_at or refresh to update."}, + } { + t.Run(tc.name, func(t *testing.T) { + w := credentialRequest(tc.handler, http.MethodPost, tc.path, tc.body) + code, param, message := errorFields(t, w) + if w.Code != http.StatusBadRequest || code != "invalid_request_error" || param == nil || *param != tc.param || message != tc.error { + t.Fatalf("%d %s", w.Code, w.Body) + } + }) + } +} diff --git a/services/core/internal/api/session_credentials_test.go b/services/core/internal/api/session_credentials_test.go index c39771700..56b6fd285 100644 --- a/services/core/internal/api/session_credentials_test.go +++ b/services/core/internal/api/session_credentials_test.go @@ -24,20 +24,16 @@ func TestMCPCredentialReferenceIsSchemaNotAuthorization(t *testing.T) { } func TestSessionVaultTypesAndCreationIntent(t *testing.T) { - for _, field := range []string{"", `,"vault_ids":null`, `,"vault_ids":[]`, `,"vault_ids":["vault"]`, `,"vault_ids":[null]`, `,"vault_ids":[3]`, `,"vault_ids":{}`, `,"vault_ids":"vault"`} { + for _, field := range []string{"", `,"vault_ids":null`, `,"vault_ids":[]`, `,"vault_ids":["vault"]`} { var decoded decodedSessionRequest err := json.Unmarshal([]byte(`{"agent":{"model":"model"},"environment":{"type":"none"}`+field+`}`), &decoded) if err != nil { t.Fatal(err) } input, err := decoded.validated() - invalid := strings.Contains(field, "[null]") || strings.Contains(field, "[3]") || strings.Contains(field, "{}") || strings.Contains(field, `:"vault"`) - if (err != nil) != invalid { + if err != nil { t.Fatal("Vault IDs type/default decision differed", field) } - if invalid { - continue - } intent, err := sessionCreationRequest(input, nil) if err != nil || (len(intent) != 0) != (len(input.VaultIDs) > 0) { t.Fatal("attached inline intent missing or unrelated inline identity changed", err) diff --git a/services/core/internal/api/session_initial_input_test.go b/services/core/internal/api/session_initial_input_test.go index b778c836f..4c990879a 100644 --- a/services/core/internal/api/session_initial_input_test.go +++ b/services/core/internal/api/session_initial_input_test.go @@ -36,7 +36,7 @@ func TestInitialInputUsesExecutionAdmissionAndSharedMessageValidation(t *testing t.Fatal(execution.input, err) } } - for _, value := range []string{`[{"type":null,"role":"user","content":[{"type":"input_text","text":"x"}]}]`, `[{"type":"","role":"user","content":[{"type":"input_text","text":"x"}]}]`, `0`, `true`, `{}`, `[]`, `""`, `[{"role":"user","content":[]}]`, `[{"role":"user","content":[{"type":"input_text","text":""}]}]`, `[{"role":"user","unknown":true,"content":[{"type":"input_text","text":"x"}]}]`, `[{"role":"user","content":[{"type":"input_text","text":"x","unknown":true}]}]`, `[{"role":"assistant","content":[{"type":"input_text","text":"x"}]}]`} { + for _, value := range []string{`0`, `true`, `{}`, `[]`, `""`, `[{"role":"user","content":[]}]`, `[{"role":"user","content":[{"type":"input_text","text":""}]}]`, `[{"role":"user","unknown":true,"content":[{"type":"input_text","text":"x"}]}]`, `[{"role":"user","content":[{"type":"input_text","text":"x","unknown":true}]}]`, `[{"role":"assistant","content":[{"type":"input_text","text":"x"}]}]`} { if _, err := initialSessionInputs(json.RawMessage(value)); err == nil { t.Fatal("invalid initial input accepted", value) } diff --git a/services/core/internal/api/session_metadata.go b/services/core/internal/api/session_metadata.go index 213fbd667..c4caabc54 100644 --- a/services/core/internal/api/session_metadata.go +++ b/services/core/internal/api/session_metadata.go @@ -16,36 +16,21 @@ import ( func (h *Handler) updateSession(w http.ResponseWriter, r *http.Request) { raw, ok := readJSONObject(w, r) - if !ok { - return - } - if writeFieldError(w, metadataTypeError(raw)) { + if !ok || writeFieldError(w, validateBody(raw, updateAgentSessionParams)) { return } var request struct { Metadata json.RawMessage `json:"metadata"` } - if err := decodeInputObject(raw, &request, "metadata"); err != nil { - writeError(w, http.StatusBadRequest, "invalid_request", "Request must be a JSON object containing supported fields.") - return - } + _ = json.Unmarshal(raw, &request) if len(request.Metadata) == 0 { writeError(w, http.StatusBadRequest, "invalid_request_error", "At least one update field is required") return } - var pairs map[string]*string - if err := json.Unmarshal(request.Metadata, &pairs); err != nil { - writeError(w, http.StatusBadRequest, "invalid_request", "metadata must be null or an object with string values.") - return - } - values, err := stringMetadata(pairs) - if err == nil { - err = metadataFieldError(metadata.Validate(values)) - } - if err != nil { - if !writeFieldError(w, err) { - writeError(w, http.StatusBadRequest, "invalid_request", "metadata must be null or an object with string values.") - } + var values map[string]string + _ = json.Unmarshal(request.Metadata, &values) + values = metadataOrEmpty(values) + if writeFieldError(w, metadataFieldError(metadata.Validate(values))) { return } session, err := h.Sessions.UpdateSessionMetadata(r.Context(), sessions.UpdateSessionMetadataCommand{TenantID: tenantID(r), SessionID: chi.URLParam(r, "session_id"), Metadata: values}) @@ -56,29 +41,6 @@ func (h *Handler) updateSession(w http.ResponseWriter, r *http.Request) { h.respondSession(w, r, session) } -// metadataTypeError reports the first non-string value of a request body's -// top-level metadata object in document order, before generic body decoding -// can reject it. Other body and metadata shapes keep their existing errors. -// The shared body gate has already rejected repeated keys. -func metadataTypeError(body []byte) error { - decoder := json.NewDecoder(bytes.NewReader(objectMember(body, "metadata"))) - if token, err := decoder.Token(); err != nil || token != json.Delim('{') { - return nil - } - for decoder.More() { - token, err := decoder.Token() - key, isKey := token.(string) - var value json.RawMessage - if err != nil || !isKey || decoder.Decode(&value) != nil { - return nil - } - if kind := jsonValueKind(value); kind != "a string" { - return &fieldError{param: "metadata." + key, message: fmt.Sprintf("Invalid type for 'metadata.%s': expected a string, but got %s instead.", key, kind)} - } - } - return nil -} - func jsonValueKind(value json.RawMessage) string { value = bytes.TrimSpace(value) if len(value) == 0 { @@ -113,6 +75,14 @@ func stringMetadata(values map[string]*string) (map[string]string, error) { return metadata, nil } +// metadataOrEmpty keeps omitted and null metadata equal to an empty map. +func metadataOrEmpty(values map[string]string) map[string]string { + if values == nil { + return map[string]string{} + } + return values +} + // metadataFieldError renders a metadata violation with the pinned messages // and params. U+0000 is a documented local limit; the official service // accepts it. diff --git a/services/core/internal/api/session_request.go b/services/core/internal/api/session_request.go index b4e091ee8..776dab025 100644 --- a/services/core/internal/api/session_request.go +++ b/services/core/internal/api/session_request.go @@ -14,14 +14,11 @@ import ( // otherwise erase it. The embedded wire type retains strict nested decoding. type decodedSessionRequest struct { v1.CreateSessionRequest - Execution json.RawMessage `json:"x_agents_core"` - Input json.RawMessage `json:"input"` - Agent json.RawMessage `json:"agent"` - AgentID json.RawMessage `json:"agent_id"` - Environment json.RawMessage `json:"environment"` - Stream json.RawMessage `json:"stream"` - Metadata map[string]*string `json:"metadata"` - VaultIDs json.RawMessage `json:"vault_ids"` + Execution json.RawMessage `json:"x_agents_core"` + Input json.RawMessage `json:"input"` + Agent json.RawMessage `json:"agent"` + Environment json.RawMessage `json:"environment"` + VaultIDs []string `json:"vault_ids"` } type sessionRequest struct { @@ -50,17 +47,7 @@ func (request decodedSessionRequest) validated() (sessionRequest, error) { _ = json.Unmarshal(request.Execution, &fields) input.modelProviderNull = bytes.Equal(bytes.TrimSpace(fields["model_provider"]), []byte("null")) } - var vaultIDs []*string - if len(request.VaultIDs) != 0 && json.Unmarshal(request.VaultIDs, &vaultIDs) != nil { - return input, sessions.ErrInvalidInput - } - input.VaultIDs = make([]string, 0, len(vaultIDs)) - for _, id := range vaultIDs { - if id == nil { - return input, sessions.ErrInvalidInput - } - input.VaultIDs = append(input.VaultIDs, *id) - } + input.VaultIDs = append([]string{}, request.VaultIDs...) canonicalEnvironment, err := preparationEnvironmentInput(request.Environment, input.XAgentsCore) if err != nil { return input, err @@ -94,18 +81,6 @@ func (request decodedSessionRequest) validated() (sessionRequest, error) { return input, sessions.ErrInvalidInput } } - if len(request.AgentID) > 0 { - var id string - if bytes.Equal(bytes.TrimSpace(request.AgentID), []byte("null")) || json.Unmarshal(request.AgentID, &id) != nil { - return input, sessions.ErrInvalidInput - } - input.AgentID = &id - } - if len(request.Stream) > 0 { - if bytes.Equal(bytes.TrimSpace(request.Stream), []byte("null")) || json.Unmarshal(request.Stream, &input.Stream) != nil { - return input, sessions.ErrInvalidInput - } - } - input.Metadata, err = stringMetadata(request.Metadata) - return input, err + input.Metadata = metadataOrEmpty(request.Metadata) + return input, nil } diff --git a/services/core/internal/api/session_request_test.go b/services/core/internal/api/session_request_test.go index ea17672e1..61431eff1 100644 --- a/services/core/internal/api/session_request_test.go +++ b/services/core/internal/api/session_request_test.go @@ -23,19 +23,19 @@ func TestSessionCreateFieldPresence(t *testing.T) { }{ {"omitted", ``, 201, nil, ""}, {"false stream", `,"stream":false`, 201, nil, ""}, - {"null stream", `,"stream":null`, 400, nil, ""}, - {"whitespace null stream", `,"stream": null `, 400, nil, ""}, - {"string stream", `,"stream":"false"`, 400, nil, ""}, - {"numeric stream", `,"stream":0`, 400, nil, ""}, - {"null agent ID", `,"agent_id":null`, 400, nil, ""}, - {"numeric agent ID", `,"agent_id":0`, 400, nil, ""}, + {"null stream", `,"stream":null`, 400, nil, "stream"}, + {"whitespace null stream", `,"stream": null `, 400, nil, "stream"}, + {"string stream", `,"stream":"false"`, 400, nil, "stream"}, + {"numeric stream", `,"stream":0`, 400, nil, "stream"}, + {"null agent ID", `,"agent_id":null`, 400, nil, "agent_id"}, + {"numeric agent ID", `,"agent_id":0`, 400, nil, "agent_id"}, {"null metadata", `,"metadata":null`, 201, nil, ""}, {"empty metadata", `,"metadata":{}`, 201, nil, ""}, {"string metadata", `,"metadata":{"empty":"","label":"中文🧪"}`, 201, map[string]string{"empty": "", "label": "中文🧪"}, ""}, {"null metadata value", `,"metadata":{"label":null}`, 400, nil, "metadata.label"}, {"mixed metadata values", `,"metadata":{"empty":"","label":null}`, 400, nil, "metadata.label"}, {"numeric metadata value", `,"metadata":{"label":0}`, 400, nil, "metadata.label"}, - {"array metadata", `,"metadata":[]`, 400, nil, ""}, + {"array metadata", `,"metadata":[]`, 400, nil, "metadata"}, } { t.Run(tc.name, func(t *testing.T) { handler, saved, _ := testHandler(t, admitSessions) diff --git a/services/core/internal/api/validation_errors_test.go b/services/core/internal/api/validation_errors_test.go index 0c84bda60..01c769bb8 100644 --- a/services/core/internal/api/validation_errors_test.go +++ b/services/core/internal/api/validation_errors_test.go @@ -166,16 +166,11 @@ func TestMetadataValidationUsesOfficialFields(t *testing.T) { if want := map[bool]int{true: 0, false: 3}[op.limited]; s.writes != want { t.Fatalf("rejected metadata reached storage: %d writes", s.writes) } - // Type errors precede the generic whole-body error. Agent bodies follow - // the pinned shape walk, which reports unknown members first. + // The pinned shape walk reports unknown members first. body := strings.Replace(fmt.Sprintf(op.body, `{"k":1}`), "{", `{"unsupported_field":true,`, 1) - want := "metadata.k" - if strings.HasPrefix(op.name, "agent") { - want = "unsupported_field" - } w := credentialRequest(h, op.method, op.path, body) - if code, param, _ := errorFields(t, w); w.Code != http.StatusBadRequest || code != "invalid_request_error" || param == nil || *param != want { - t.Fatalf("metadata type did not precede generic error: %d %s", w.Code, w.Body) + if code, param, _ := errorFields(t, w); w.Code != http.StatusBadRequest || code != "invalid_request_error" || param == nil || *param != "unsupported_field" { + t.Fatalf("unknown member did not precede metadata type: %d %s", w.Code, w.Body) } for _, tc := range accepted { before := s.writes @@ -250,8 +245,8 @@ func TestTemplateNetworkRejectionsUseOfficialCode(t *testing.T) { if s.writes != 0 { t.Fatal("rejected network reached storage") } - // Other unsupported template installation fields keep their local code. - for _, body := range []string{`{"unsupported":true,"network":{"access":"restricted","allowed_domains":["*.example.com"]}}`, `{"network":{"access":"restricted","allowed_domains":"example.com"}}`, `{"packages":{"cargo":["x"]}}`} { + // A network the walker leaves to the local parser keeps its local code. + for _, body := range []string{`{"network":{"access":"restricted","allowed_domains":"example.com"}}`} { w := credentialRequest(h, http.MethodPost, "/v1/agents/environments/templates", body) if code, _, _ := errorFields(t, w); w.Code != http.StatusBadRequest || code != "unsupported_or_invalid_configuration" { t.Fatalf("%s: %d %s", body, w.Code, w.Body) diff --git a/services/core/internal/api/vaults.go b/services/core/internal/api/vaults.go index 699ae5ebd..95b463a47 100644 --- a/services/core/internal/api/vaults.go +++ b/services/core/internal/api/vaults.go @@ -3,7 +3,6 @@ package api import ( "context" "encoding/json" - "errors" "net/http" "strings" @@ -35,44 +34,26 @@ type VaultsReader interface { func (h *Handler) createVault(w http.ResponseWriter, r *http.Request) { raw, ok := readJSONObject(w, r) - if !ok { - return - } - if writeFieldError(w, metadataTypeError(raw)) { + if !ok || writeFieldError(w, validateBody(raw, createVaultParams)) { return } var request struct { - Name json.RawMessage `json:"name"` - Metadata map[string]*string `json:"metadata"` - } - if decodeInputObject(raw, &request, "name", "metadata") != nil { - writeError(w, http.StatusBadRequest, "invalid_request", "Request must be a JSON object containing supported fields.") - return + Name *string `json:"name"` + Metadata map[string]string `json:"metadata"` } + _ = json.Unmarshal(raw, &request) input := vaults.CreateVault{TenantID: tenantID(r)} - if len(request.Name) > 0 { - var name *string - if json.Unmarshal(request.Name, &name) != nil || name == nil { - writeError(w, http.StatusBadRequest, "invalid_request", "name must be a string.") - return - } - trimmed, err := normalizedVaultName(*name) + if request.Name != nil { + name, err := normalizedVaultName(*request.Name) if err != nil { - writeError(w, http.StatusBadRequest, "invalid_request", err.Error()) + writeFieldError(w, err) return } - input.Name = &trimmed + input.Name = &name } // Vault metadata has no pair or character limits, only the storage limits. - var err error - input.Metadata, err = stringMetadata(request.Metadata) - if err == nil { - err = metadataFieldError(metadata.ValidateStorable(input.Metadata)) - } - if err != nil { - if !writeFieldError(w, err) { - writeError(w, http.StatusBadRequest, "invalid_request", "metadata values must be strings.") - } + input.Metadata = metadataOrEmpty(request.Metadata) + if writeFieldError(w, metadataFieldError(metadata.ValidateStorable(input.Metadata))) { return } vault, err := h.Vaults.CreateVault(r.Context(), input) @@ -103,7 +84,7 @@ func vaultResponse(vault vaults.Vault) v1.Vault { func normalizedVaultName(name string) (string, error) { name = strings.TrimSpace(name) if len(name) == 0 || len(name) > 256 { - return "", errors.New("name must contain 1 to 256 UTF-8 bytes after trimming.") + return "", &fieldError{param: "name", message: "name must contain 1 to 256 UTF-8 bytes after trimming."} } return name, nil } diff --git a/services/core/internal/environmentconfig/setup.go b/services/core/internal/environmentconfig/setup.go index a7b1442b8..0cc62fe92 100644 --- a/services/core/internal/environmentconfig/setup.go +++ b/services/core/internal/environmentconfig/setup.go @@ -45,6 +45,13 @@ func (s Setup) ValidateInstalled() error { return s.validate(true) } +// ValidEnvironmentEntry reports whether an environment variable may be set. +func ValidEnvironmentEntry(name, value string) bool { + // The first three reservations are explicitly part of the public guide; + // OAC_* identifies the actual deployment authority and binding. + return environmentName.MatchString(name) && name != "PATH" && name != "OPENAI_API_KEY" && !strings.HasPrefix(name, "CODEX_") && !strings.HasPrefix(name, "OAC_") && !strings.ContainsRune(value, 0) +} + func (s Setup) validate(installed bool) error { if validateSkills(s.Skills, installed) != nil || ValidatePlugins(s.Plugins) != nil || proto.ValidateSourceDirectories(s.CapabilityDirectories) != nil { return ErrInvalid @@ -57,9 +64,7 @@ func (s Setup) validate(installed bool) error { return ErrInvalid } for name, value := range s.Env { - // The first three reservations are explicitly part of the public guide; - // OAC_* identifies the actual deployment authority and binding. - if !environmentName.MatchString(name) || name == "PATH" || name == "OPENAI_API_KEY" || strings.HasPrefix(name, "CODEX_") || strings.HasPrefix(name, "OAC_") || strings.ContainsRune(value, 0) { + if !ValidEnvironmentEntry(name, value) { return ErrInvalid } } diff --git a/services/core/tests/official_session_metadata.py b/services/core/tests/official_session_metadata.py index 6b37c4cfd..e99136752 100644 --- a/services/core/tests/official_session_metadata.py +++ b/services/core/tests/official_session_metadata.py @@ -51,13 +51,14 @@ def assert_metadata(session, expected): expect_error(ConflictError, lambda: sessions.create(**spec, metadata=metadata, extra_headers=retry)) invalid_fields = [ - {"metadata": []}, {"metadata": "value"}, {"metadata": False}, - {"agent": spec["agent"]}, {"environment": spec["environment"]}, - {"tenant_id": str(uuid.uuid4())}, {"Metadata": {}}, + ({"metadata": []}, "metadata"), ({"metadata": "value"}, "metadata"), ({"metadata": False}, "metadata"), + ({"agent": spec["agent"]}, "agent"), ({"environment": spec["environment"]}, "environment"), + ({"tenant_id": str(uuid.uuid4())}, "tenant_id"), ({"Metadata": {}}, "Metadata"), ] - for fields in invalid_fields: + for fields, param in invalid_fields: response = raw.post(url, headers=headers, json=fields) - assert response.status_code == 400 and response.json()["error"]["code"] == "invalid_request" + assert response.status_code == 400 and response.json()["error"]["code"] == "invalid_request_error" + assert response.json()["error"]["param"] == param, response.text expect_error(BadRequestError, lambda: sessions.update(first.id, extra_body=fields)) assert sessions.retrieve(first.id) == current # Metadata values and limits report the official code, param and message. diff --git a/services/core/tests/official_session_requests.py b/services/core/tests/official_session_requests.py index f2fc66020..70d7087fc 100644 --- a/services/core/tests/official_session_requests.py +++ b/services/core/tests/official_session_requests.py @@ -11,16 +11,16 @@ def verify_session_create_requests(client, spec): # agent_id is str and stream is a boolean literal union without None. sessions = client.beta.agents.sessions before = {session.id for session in sessions.list()} - # Non-string metadata values use the official code and metadata. param. + # Field errors use the official code and the field path as param. invalid = [ - ({"stream": None}, None), ({"stream": "false"}, None), ({"stream": 0}, None), - ({"agent_id": None}, None), ({"agent_id": 0}, None), + ({"stream": None}, "stream"), ({"stream": "false"}, "stream"), ({"stream": 0}, "stream"), + ({"agent_id": None}, "agent_id"), ({"agent_id": 0}, "agent_id"), ({"metadata": {"label": None}}, "metadata.label"), ({"metadata": {"empty": "", "label": None}}, "metadata.label"), - ({"metadata": {"label": 0}}, "metadata.label"), ({"metadata": []}, None), + ({"metadata": {"label": 0}}, "metadata.label"), ({"metadata": []}, "metadata"), # Member names match exactly: a case variant is an unknown member, not an # alias that replaces the field (req_6ba2a50c71a4410f87a1baac855e82df). - ({"Metadata": {"label": "case"}}, None), ({"Input": "Case variant."}, None), ({"STREAM": False}, None), + ({"Metadata": {"label": "case"}}, "Metadata"), ({"Input": "Case variant."}, "Input"), ({"STREAM": False}, "STREAM"), ({"environment": {**spec["environment"], "Type": "self_hosted"}}, None), ] headers = {"Authorization": f"Bearer {client.api_key}", "OpenAI-Beta": "agents=v1"} From 97679bb3bc661a695b705dbfe6929c9043f21ce9 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 10:48:25 +0800 Subject: [PATCH 03/84] Reject input whose selected Credential was deleted (#863) * Reject input whose selected Credential was deleted * Let admission decide any reused input key before the Credential check --- contracts/agents-api/index.md | 1 - contracts/agents-api/sessions-events.md | 5 +- contracts/agents-api/vaults.md | 2 +- contracts/agents-api/zh/index.md | 3 +- contracts/agents-api/zh/sessions-events.md | 7 +- contracts/agents-api/zh/vaults.md | 4 +- services/core/internal/api/errors_sessions.go | 4 + .../core/internal/execution/dispatcher.go | 3 +- .../internal/execution/mcp_support_test.go | 4 + services/core/internal/execution/worker.go | 30 +++++++ services/core/internal/sessions/inputs.go | 21 +++++ services/core/internal/vaults/service.go | 36 +++++++++ .../integration/mcp_credential_input_test.go | 81 +++++++++++++++++++ 13 files changed, 189 insertions(+), 12 deletions(-) create mode 100644 services/core/tests/integration/mcp_credential_input_test.go diff --git a/contracts/agents-api/index.md b/contracts/agents-api/index.md index e8784cfff..0d15252d8 100644 --- a/contracts/agents-api/index.md +++ b/contracts/agents-api/index.md @@ -158,7 +158,6 @@ Each item is Core's deliberate or native behavior where the official service beh - There is no storage-key rotation or re-encryption. - OAuth refresh happens only at dispatch: there is no refresh on a provider 401, no mid-Turn replacement and no withdrawal of a token already sent to a Runtime. -- Input sent to a Session whose selected Credential was deleted is admitted and then fails at dispatch. - Credential creation takes no `Idempotency-Key`. **Sessions** diff --git a/contracts/agents-api/sessions-events.md b/contracts/agents-api/sessions-events.md index 88ebb0f37..db1414183 100644 --- a/contracts/agents-api/sessions-events.md +++ b/contracts/agents-api/sessions-events.md @@ -61,7 +61,7 @@ On `openai_hosted` and `self_hosted` Sessions, messages sent while a Turn runs j ### Input errors -Checks run in this order: [request validation](./wire-semantics.md#configuration-validation), whose paths start with `events[i]`, Session lookup, retry lookup, the Environment file-write gate for batches with a message, the pending-input gate, then each event in batch order. A rejected batch writes nothing and leaves any pending action unchanged. Every 409 has type `conflict_error` ([error envelope](./wire-semantics.md)). +Checks run in this order: [request validation](./wire-semantics.md#configuration-validation), whose paths start with `events[i]`, Session lookup, the Harness input check, retry lookup, the Credential check for a message that starts a Turn, the Environment file-write gate for batches with a message, the pending-input gate, then each event in batch order. A rejected batch writes nothing and leaves any pending action unchanged. Every 409 has type `conflict_error` ([error envelope](./wire-semantics.md)). | Case | Status and code | Message | | --- | --- | --- | @@ -76,9 +76,10 @@ Checks run in this order: [request validation](./wire-semantics.md#configuration | A reserved batch cancelled because an administrator archived the Session or reset its deployment | 409 `environment_input_cancelled` | "The environment input was cancelled before admission." | | New input after an `openai_hosted` Environment failed to provision | 409 `conflict_error` | "the hosted environment failed to provision" | | New input after a `self_hosted` Environment failed, input already waiting when the Environment failed, or an expired Environment | 409 `environment_unavailable` | "The environment is no longer available for new input." | +| A message that would start a Turn on a Session whose bound MCP Credential, or its Vault, was deleted | 400 `invalid_request_error`, param null | "MCP credential_id {id} was not found in an attached vault" | | A message the Session's Harness cannot take, such as whitespace-only text on MiniMax Code | 400 `unsupported_or_invalid_configuration` | See [whitespace-only text](./message-content.md#whitespace-only-text) | -An empty `turn_id` or blank `call_id` is the generic 400 `invalid_request`. Apart from the unknown tool call message, which names its `call_id` as the official SDK expects, error messages never repeat caller input or internal identifiers. +An empty `turn_id` or blank `call_id` is the generic 400 `invalid_request`. Apart from the unknown tool call message, which names its `call_id` as the official SDK expects, and the Credential message, which names the Credential as Session creation does, error messages never repeat caller input or internal identifiers. ## Initial input at Session creation diff --git a/contracts/agents-api/vaults.md b/contracts/agents-api/vaults.md index bd43c2cfa..56c611f33 100644 --- a/contracts/agents-api/vaults.md +++ b/contracts/agents-api/vaults.md @@ -145,4 +145,4 @@ An unreadable or malformed key file stops Core at startup. Losing or replacing t Deleting a Credential, or its Vault, removes the credential rows. It does not erase secrets from PostgreSQL pages, write-ahead logs, backups or native history. Afterwards its reads, updates and repeated deletion return 404, lists omit it, new Sessions cannot select it and new Credentials cannot be created in a deleted Vault. -Existing Sessions keep their frozen attachments and selections, and their history stays readable. The next dispatch that needs a deleted Credential fails; Core neither selects another Credential nor connects anonymously. Deletion does not cancel running work, withdraw a token already sent to a Runtime or revoke the grant at its provider: cancel the Session and revoke the grant yourself when needed. Revoked or invalid OAuth grants likewise fail until replaced. +Existing Sessions keep their frozen attachments and selections, and their history stays readable. A message that would start a Turn is rejected with 400 `invalid_request_error`, as at creation, and creates no Turn; a request under an `Idempotency-Key` the Session already used replays or conflicts as before. A deletion between that check and dispatch, and any other input, still fails at the next dispatch that needs the deleted Credential. Core neither selects another Credential nor connects anonymously. Deletion does not cancel running work, withdraw a token already sent to a Runtime or revoke the grant at its provider: cancel the Session and revoke the grant yourself when needed. Revoked or invalid OAuth grants likewise fail until replaced. diff --git a/contracts/agents-api/zh/index.md b/contracts/agents-api/zh/index.md index 42c5abbee..2b1349bb2 100644 --- a/contracts/agents-api/zh/index.md +++ b/contracts/agents-api/zh/index.md @@ -1,7 +1,7 @@ --- title: "OpenAI 兼容性" source: contracts/agents-api/index.md -source_hash: afb241cb659061b9f5c50c5db88c83080d02d07eab37ffb2f1c70d5e2386c96e +source_hash: 007c0a43dce8af3d21c5a4afb196ad2f62fad8b697ac3ba38eaab6ce955e0f88 --- Core 实现下方固定版本的 OpenAI Agents API。本台账列出各项资源的覆盖情况、相对于官方服务的所有差异以及已知缺口。 @@ -161,7 +161,6 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - 没有存储密钥轮换或重新加密。 - OAuth 刷新仅在派发时执行:提供商返回 401 时不会刷新,不会在 Turn 中途替换令牌,也不会撤回已发送给 Runtime 的令牌。 -- 发送到所选 Credential 已被删除的 Session 的输入会先通过准入,随后在派发时失败。 - 创建 Credential 时不接受 `Idempotency-Key`。 **Sessions** diff --git a/contracts/agents-api/zh/sessions-events.md b/contracts/agents-api/zh/sessions-events.md index 618f0b60b..eca247040 100644 --- a/contracts/agents-api/zh/sessions-events.md +++ b/contracts/agents-api/zh/sessions-events.md @@ -1,7 +1,7 @@ --- title: "Session、事件和历史" source: contracts/agents-api/sessions-events.md -source_hash: 39fe5deab865e778bd8d3fa50a5d66707e10df4652b868e47f17126d962291eb +source_hash: ffddefb51fd2dcd04532d210f658caf96a6f825057c9025c3c18dbf8eb3ddc5a --- 本契约涵盖 Session 内部发生的事情:发送输入、实时事件流,以及读取 Turn、Item 和使用量的持久化历史。Session 资源本身(创建配置、重试标识、更新、列出和删除)见 [API 行为](wire-semantics.md)。消息和函数结果内容见[消息内容](message-content.md)。[Agents API 指南](../../../docs/zh/api/public-agent-api.md)展示了使用 SDK 和 HTTP 的调用方式。 @@ -63,7 +63,7 @@ Turn 失败后 Session 仍可使用:新输入会启动一个新 Turn。后来 ### 输入错误 {#input-errors} -检查按以下顺序执行:[请求验证](wire-semantics.md#configuration-validation)(路径以 `events[i]` 开头)、Session 查找、重试查找、针对包含消息的批次的 Environment 文件写入门控、待处理输入门控,最后按批次顺序检查每个事件。被拒绝的批次不会写入任何内容,也不会改变任何待处理操作。所有 409 响应的 `type` 都是 `conflict_error`([错误封装](wire-semantics.md))。 +检查按以下顺序执行:[请求验证](wire-semantics.md#configuration-validation)(路径以 `events[i]` 开头)、Session 查找、Harness 输入检查、重试查找、针对会启动 Turn 的消息的 Credential 检查、针对包含消息的批次的 Environment 文件写入门控、待处理输入门控,最后按批次顺序检查每个事件。被拒绝的批次不会写入任何内容,也不会改变任何待处理操作。所有 409 响应的 `type` 都是 `conflict_error`([错误封装](wire-semantics.md))。 | 情况 | 状态和代码 | 消息 | | --- | --- | --- | @@ -78,9 +78,10 @@ Turn 失败后 Session 仍可使用:新输入会启动一个新 Turn。后来 | 预留的批次因管理员归档 Session 或重置其部署而被取消 | 409 `environment_input_cancelled` | "The environment input was cancelled before admission." | | `openai_hosted` Environment 预配失败后提交新输入 | 409 `conflict_error` | "the hosted environment failed to provision" | | `self_hosted` Environment 失败后提交新输入、Environment 失败时输入已在等待,或 Environment 已过期 | 409 `environment_unavailable` | "The environment is no longer available for new input." | +| 会在其所绑定 MCP Credential 或其 Vault 已删除的 Session 上启动 Turn 的消息 | 400 `invalid_request_error`,param 为 null | "MCP credential_id {id} was not found in an attached vault" | | Session Harness 无法处理的消息,例如 MiniMax Code 上仅含空白的文本 | 400 `unsupported_or_invalid_configuration` | 见[仅含空白的文本](message-content.md#whitespace-only-text) | -`turn_id` 为空或 `call_id` 为空白时,会返回通用的 400 `invalid_request`。除未知工具调用的消息按官方 SDK 的预期给出其 `call_id` 外,错误消息绝不会重复调用方输入或内部标识符。 +`turn_id` 为空或 `call_id` 为空白时,会返回通用的 400 `invalid_request`。除未知工具调用的消息按官方 SDK 的预期给出其 `call_id`、Credential 消息像 Session 创建时一样给出该 Credential 外,错误消息绝不会重复调用方输入或内部标识符。 ## 创建 Session 时的初始输入 {#initial-input-at-session-creation} diff --git a/contracts/agents-api/zh/vaults.md b/contracts/agents-api/zh/vaults.md index 9aee59336..9ccb10475 100644 --- a/contracts/agents-api/zh/vaults.md +++ b/contracts/agents-api/zh/vaults.md @@ -1,7 +1,7 @@ --- title: "Vault 与 Credential" source: contracts/agents-api/vaults.md -source_hash: 1a57ba70173f8a000b6b0cb74eb7fa6a6c688b4f71d7e617b4fdfb60e6d6fef5 +source_hash: 3ef927a873326ca5a14720843269c8c05053331e616305fcccfdf0e4367f4be2 --- Vault 是项目所有的 Credential 容器。Credential 保存一个 HTTPS MCP server 的秘密:`static_bearer` token 或 `mcp_oauth` grant。Session 在 `vault_ids` 中关联 Vault;Core 在创建 Session 时为每个 HTTP MCP server 选择一个 Credential,只在分派工作时将解密 token 交给 Runtime。秘密只能写入:任何读取都不返回 token、refresh token、client secret 或密文。 @@ -147,4 +147,4 @@ key 文件不可读或格式错误会使 Core 启动失败。丢失或替换 key 删除 Credential 或其 Vault 会移除凭据行,但不会擦除 PostgreSQL 页面、WAL、备份或原生历史中的秘密。此后查询、更新和重复删除返回 404;列表不再包含它;新 Session 不能选择它;不能在已删除 Vault 中创建新 Credential。 -现有 Session 保留固定的关联和选择,历史仍可读。下一次需要已删除 Credential 的分派失败;Core 不选择其他 Credential,也不匿名连接。删除不取消运行中的工作、不收回已发送 Runtime 的 token,也不在服务方撤销 grant;需要时自行取消 Session 并撤销 grant。已撤销或无效 OAuth grant 同样失败,直到被替换。 +现有 Session 保留固定的关联和选择,历史仍可读。会启动 Turn 的消息与创建时一样返回 400 `invalid_request_error`,且不创建 Turn;使用 Session 已用过的 `Idempotency-Key` 的请求照常重放或冲突。该检查与分派之间发生的删除以及其他输入,仍在下一次需要已删除 Credential 的分派时失败。Core 不选择其他 Credential,也不匿名连接。删除不取消运行中的工作、不收回已发送 Runtime 的 token,也不在服务方撤销 grant;需要时自行取消 Session 并撤销 grant。已撤销或无效 OAuth grant 同样失败,直到被替换。 diff --git a/services/core/internal/api/errors_sessions.go b/services/core/internal/api/errors_sessions.go index e69ec141b..5f2ee9ec3 100644 --- a/services/core/internal/api/errors_sessions.go +++ b/services/core/internal/api/errors_sessions.go @@ -8,13 +8,17 @@ import ( "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/execution" "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/projects" "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/sessions" + "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/vaults" ) // writeInputError reports Session input admission failures. Input that the // Session cannot accept in its current state is the official conflict_error; // Idempotency-Key reuse keeps Core's local idempotency_conflict code. func writeInputError(w http.ResponseWriter, r *http.Request, err error) { + var selection *vaults.MCPCredentialSelectionError switch { + case errors.As(err, &selection): + writeVaultsError(w, r, err) case errors.Is(err, sessions.ErrInputPending): writeError(w, http.StatusConflict, "conflict_error", "Earlier input to this Session is still pending.") case errors.Is(err, sessions.ErrTurnConflict): diff --git a/services/core/internal/execution/dispatcher.go b/services/core/internal/execution/dispatcher.go index 0b647f820..1f0c5879a 100644 --- a/services/core/internal/execution/dispatcher.go +++ b/services/core/internal/execution/dispatcher.go @@ -57,8 +57,9 @@ type Dispatcher struct { } // Credentials opens the bearer token of a Session's frozen MCP credential -// binding. +// binding and checks that the bound Credentials still exist. type Credentials interface { + CheckMCPCredentials(context.Context, vaults.CheckMCPCredentials) error MCPBearerToken(context.Context, vaults.MCPBearerToken) (string, error) } diff --git a/services/core/internal/execution/mcp_support_test.go b/services/core/internal/execution/mcp_support_test.go index 725ccee36..be2ced897 100644 --- a/services/core/internal/execution/mcp_support_test.go +++ b/services/core/internal/execution/mcp_support_test.go @@ -187,3 +187,7 @@ func TestMCPStdioAdmission(t *testing.T) { t.Fatal(err, servers.MCP) } } + +func (c *recordingCredentials) CheckMCPCredentials(context.Context, vaults.CheckMCPCredentials) error { + return nil +} diff --git a/services/core/internal/execution/worker.go b/services/core/internal/execution/worker.go index b0068f5ad..0d48162cc 100644 --- a/services/core/internal/execution/worker.go +++ b/services/core/internal/execution/worker.go @@ -4,12 +4,14 @@ import ( "context" "encoding/json" "errors" + "slices" "sync" "time" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" "github.com/MiniMax-AI/OpenAgentCore/internal/obs/log" "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/sessions" + "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/vaults" ) const DefaultExecutionConcurrency = 4 @@ -118,6 +120,9 @@ func (w *Worker) SubmitInputs(ctx context.Context, tenant, session, key string, if err := w.dispatcher.validateEngineInputs(value.Engine, value.Configuration, inputs); err != nil { return nil, err } + if err := w.checkInputCredentials(ctx, value, key, inputs); err != nil { + return nil, err + } if preparedEnvironmentConfiguration(value.Configuration) { return w.submitEnvironmentInputs(ctx, value, key, inputs) } @@ -127,6 +132,31 @@ func (w *Worker) SubmitInputs(ctx context.Context, tenant, session, key string, return w.admitInputs(ctx, tenant, session, key, inputs) } +// checkInputCredentials rejects a message that would start a Turn whose +// Session's frozen MCP Credential was deleted, as creation rejects an absent +// one. It runs before and outside the admission transaction, and never rejects +// a key the Session already used: admission replays that batch or reports the +// key conflict. A deletion after the check still fails at dispatch. +func (w *Worker) checkInputCredentials(ctx context.Context, session sessions.Session, key string, inputs []sessions.Input) error { + if (session.LastTurn != nil && !sessions.TerminalStatus(session.LastTurn.Status)) || + !slices.ContainsFunc(inputs, func(input sessions.Input) bool { return input.Kind == "message" }) { + return nil + } + var snapshot Snapshot + if json.Unmarshal(session.Configuration, &snapshot) != nil || len(snapshot.MCPCredentials) == 0 { + return nil + } + err := w.dispatcher.Credentials.CheckMCPCredentials(ctx, vaults.CheckMCPCredentials{TenantID: session.TenantID, VaultIDs: snapshot.VaultIDs, Bindings: snapshot.MCPCredentials}) + var selection *vaults.MCPCredentialSelectionError + if !errors.As(err, &selection) { + return err + } + if used, probeErr := w.dispatcher.Sessions.InputKeyUsed(ctx, session.TenantID, session.ID, key, inputs); probeErr != nil || used { + return probeErr + } + return err +} + // CreateSession validates execution support before the pooled Session // creation reserves or admits initial work, and wakes the scheduler once that // creation commits. diff --git a/services/core/internal/sessions/inputs.go b/services/core/internal/sessions/inputs.go index c4bb79be9..ce474d558 100644 --- a/services/core/internal/sessions/inputs.go +++ b/services/core/internal/sessions/inputs.go @@ -372,6 +372,27 @@ func (s *Service) SubmitInputs(ctx context.Context, tenant, session, key string, return receipts, nil } +// InputKeyUsed reports whether the Session already used key, by direct +// admission or an Environment input reservation, so that admission decides +// between a replay and a key conflict. +func (s *Service) InputKeyUsed(ctx context.Context, tenant, session, key string, inputs []Input) (bool, error) { + _, encoded, err := ValidateInputs(inputs) + if err != nil { + return false, err + } + var used bool + err = s.storage.WithInputs(ctx, tenant, session, func(ctx context.Context, tx InputTx) error { + receipts, _, err := tx.LoadInputBatch(ctx, key, encoded) + if err != nil { + return err + } + _, reserved, err := tx.FindInputReservation(ctx, key, encoded) + used = len(receipts) > 0 || reserved + return err + }) + return used, err +} + // FunctionCall retains public identity and its opaque execution-adapter reference. type FunctionCall struct { CallID, ExecutorCallID, Name string diff --git a/services/core/internal/vaults/service.go b/services/core/internal/vaults/service.go index 6143432ea..5c189e72d 100644 --- a/services/core/internal/vaults/service.go +++ b/services/core/internal/vaults/service.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "slices" "time" "github.com/google/uuid" @@ -226,6 +227,41 @@ func (s *Service) ResolveMCPCredentials(ctx context.Context, command ResolveMCPC return bindings, nil } +// CheckMCPCredentials asks whether the Credentials a Session's frozen bindings +// name still exist in its attached Vaults. +type CheckMCPCredentials struct { + TenantID string + VaultIDs []string + Bindings []MCPCredentialBinding +} + +// CheckMCPCredentials reads metadata only. A binding whose Credential, or whose +// Vault, was deleted reports the creation-time selection error for a +// Credential absent from the attached Vaults. +func (s *Service) CheckMCPCredentials(ctx context.Context, command CheckMCPCredentials) error { + tenant, ok := canonicalID(command.TenantID) + if !ok { + return ErrInvalidInput + } + attached, err := attachedVaultIDs(command.VaultIDs) + if err != nil { + return err + } + for _, binding := range command.Bindings { + if binding.CredentialID == "" { + continue + } + matches, err := s.storage.FindMCPCredentials(ctx, MCPCredentialQuery{TenantID: tenant, VaultIDs: attached, ServerURL: binding.ServerURL, CredentialID: binding.CredentialID}) + if err != nil { + return err + } + if !slices.ContainsFunc(matches, func(match MCPCredentialMatch) bool { return match.VaultID == binding.VaultID }) { + return mcpCredentialNotAttached(binding.CredentialID) + } + } + return nil +} + // MCPBearerToken asks for the bearer token of a Session's frozen binding. type MCPBearerToken struct { TenantID string diff --git a/services/core/tests/integration/mcp_credential_input_test.go b/services/core/tests/integration/mcp_credential_input_test.go new file mode 100644 index 000000000..a212b81e8 --- /dev/null +++ b/services/core/tests/integration/mcp_credential_input_test.go @@ -0,0 +1,81 @@ +package integration + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" + "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto/prototest" + "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/execution" + "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/sessions" + "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/vaults" +) + +// A message that would start a Turn is rejected once the Credential its +// Session bound is deleted, whether the tool named it or creation selected +// it, but a key the Session already used still replays or conflicts. +func TestWorkerRejectsInputWhoseCredentialWasDeleted(t *testing.T) { + for _, mode := range []string{"auto-selected", "explicit"} { + t.Run(mode, func(t *testing.T) { + h := newFunctionHarnessWith(t, functionConfiguration) + configuration, _ := mcpBearerWorkerConfiguration(t, h) + var snapshot execution.Snapshot + if err := json.Unmarshal([]byte(configuration), &snapshot); err != nil { + t.Fatal(err) + } + binding := snapshot.MCPCredentials[0] + if mode == "explicit" { + configuration = strings.Replace(configuration, `"credential_id":null`, `"credential_id":"`+binding.CredentialID+`"`, 1) + } + var err error + h.session, err = h.s.CreateSession(t.Context(), h.tenant, sessions.CreateSession{Creator: FixtureCreator(), Engine: "codex", IdempotencyKey: "bound", Configuration: json.RawMessage(configuration)}) + if err != nil { + t.Fatal(err) + } + h.write("", proto.TypeHeartbeat, proto.HeartbeatPayload{SupportedAgentKinds: []proto.SupportedAgentKind{{Kind: "codex", Available: true, Capabilities: prototest.Capabilities(proto.AgentKindCapabilities{ + Streaming: proto.CapabilitySupported, DurableTurns: proto.CapabilitySupported, DurableInputReceipts: proto.CapabilitySupported, EnvironmentNone: proto.CapabilitySupported, + ExecutionControls: proto.CapabilitySupported, SubagentControl: proto.CapabilitySupported, ToolObservations: proto.CapabilitySupported, Preparation: proto.CapabilitySupported, + MCPHTTPTools: proto.CapabilitySupported, MCPHTTPBearerAuth: proto.CapabilitySupported, MCPHTTPRequired: proto.CapabilitySupported})}}}) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + worker := startWorker(t, ctx, h.s, h.d) + done := make(chan error, 1) + go func() { done <- worker.Run(ctx) }() + defer func() { + cancel() + <-done + }() + first, err := worker.SubmitInputs(ctx, h.tenant, h.session.ID, "first", []sessions.Input{messageInput("one")}) + if err != nil { + t.Fatal(err) + } + transition(t, h.s, h.tenant, h.session.ID, first[0].TurnID, sessions.TurnQueued, sessions.TurnCancelled) + _, vaultService, err := fixtureVaults(h.s) + if err != nil { + t.Fatal(err) + } + if _, err := vaultService.DeleteCredential(ctx, vaults.DeleteCredential{TenantID: h.tenant, VaultID: binding.VaultID, CredentialID: binding.CredentialID}); err != nil { + t.Fatal(err) + } + var turns int + _, err = worker.SubmitInputs(ctx, h.tenant, h.session.ID, "second", []sessions.Input{messageInput("two")}) + var selection *vaults.MCPCredentialSelectionError + if !errors.As(err, &selection) || selection.Conflict { + t.Fatal("input after deletion was admitted", err) + } + if err := h.s.pool.QueryRow(ctx, "SELECT count(*) FROM turns WHERE session_id=$1", h.session.ID).Scan(&turns); err != nil || turns != 1 { + t.Fatal("rejected input created a Turn", turns, err) + } + replay, err := worker.SubmitInputs(ctx, h.tenant, h.session.ID, "first", []sessions.Input{messageInput("one")}) + if err != nil || len(replay) != 1 || replay[0].TurnID != first[0].TurnID { + t.Fatal("retry of an admitted batch changed", replay, err) + } + if _, err := worker.SubmitInputs(ctx, h.tenant, h.session.ID, "first", []sessions.Input{messageInput("other")}); !errors.Is(err, sessions.ErrIdempotencyConflict) { + t.Fatal("reused key with another batch", err) + } + }) + } +} From e546b97e76c5700b9579d6b6f3ad168a0b71a9ff Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 10:51:32 +0800 Subject: [PATCH 04/84] Record the remaining official API differences (#864) --- contracts/agents-api/index.md | 21 ++++++++++++++++++--- contracts/agents-api/zh/index.md | 23 +++++++++++++++++++---- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/contracts/agents-api/index.md b/contracts/agents-api/index.md index 0d15252d8..0e69b86a0 100644 --- a/contracts/agents-api/index.md +++ b/contracts/agents-api/index.md @@ -58,6 +58,7 @@ Each item is Core's deliberate or native behavior where the official service beh - Not-found messages never name the resource; Core quotes a full metadata key where the official message abbreviates it. - UUID identifiers also resolve in other spellings, such as uppercase or braces. - The Files routes keep a local `unsupported_parameter` code for a repeated query key. +- Core has no CORS handling; the official service sends CORS headers. **Lists** ([lists](./wire-semantics.md#lists)) @@ -82,7 +83,10 @@ Each item is Core's deliberate or native behavior where the official service beh - A `stdio` MCP server needs a workspace placement and the origin `environment`. Claude Code starts the server in its workspace directory, so `cwd` must equal it, with its whole process environment, which also holds the model provider key and other servers' Vault bearer tokens, and it needs `allowed_tools` null. MiniMax Code starts the server in its private home directory, so it rejects every `stdio` server ([MCP](./execution-tools.md#mcp)). - Core rejects nonempty MCP `request_metadata`, which no Harness can send, as well as a `stdio` server whose `connection_origin` is `service`, an empty `credential_id` and an empty `allowed_tools` name, which the pinned schema allows without defining their meaning (400 with the reason). - Claude rejects an MCP `server_url` or `headers` value containing `${`, because the native client expands `${VAR}` in both from a process environment that holds Core-held credentials. +- Each Harness rejects the MCP labels its native client reserves, such as `functions` on Claude Code ([MCP](./execution-tools.md#mcp)). +- An MCP server that cannot be reached is handled natively: an optional server's tools are missing and a required one fails the start ([MCP](./execution-tools.md#mcp)). The official Item and Turn failure shapes are not reproduced. - Deleting a Session right after an events 202 returns 409, because Core admits the Turn in the same transaction; the official service returns 200. +- Deleting a Session while its hosted Environment runs setup succeeds when no input is pending; the official service returns 409. **Input, events and history** ([Sessions, events and history](./sessions-events.md), [message content](./message-content.md)) @@ -100,12 +104,19 @@ Each item is Core's deliberate or native behavior where the official service beh - U+0000 in Harness output, such as command output, reads as U+FFFD; the official service keeps it. - A `reasoning` Item carries what the Harness shows of its native reasoning: its native summary when it produces one, otherwise its native reasoning text, such as Codex raw reasoning or the thinking text the model API returns to Claude Code. Each native part is one `summary_text` part, and native reasoning without text is not reported, so Claude Code with the model provider's `thinking.display` `omitted` reports none. Codex streams the first native channel an item delivers, its summary or its raw reasoning text. +**Environments and Templates** ([Environments](./environments.md)) + +- `openai_hosted` and Template `capability_directories` must lie inside `/workspace`; the official service also accepts system paths such as `/etc` ([capability directories](./environments.md#plugins-and-capability-directories)). +- `env` cannot set `OPENAI_API_KEY`, which Core reserves ([env](./environments.md#env-and-setup-commands)); the official service accepts it. + **Files, Skills, Environment files and Artifacts** ([Files and Skills](./source-files.md), [Environment files and Artifacts](./environment-files.md)) - File uploads hold up to 512 MiB; the official limit is 512 MB. A `purpose` filter other than `user_data` returns an empty page. - Skill version numbers are never reused, and uploads and deletions of one Skill run one at a time. - Environment files work on `self_hosted` Environments, which the official service refuses. - Creating an Environment file over an existing regular file returns the "must not traverse symlinks or overwrite existing files" message. A parent symbolic link that stays inside the workspace is followed, and a parent that escapes the workspace or is a regular file gets a generic 400; the official service rejects symbolic-link parents. +- File names hold 1–1,024 bytes; the official service accepts empty and longer names. +- A `SKILL.md` front-matter key other than `name`, `description`, `license`, `compatibility` and `metadata` is rejected; the official service accepts unknown keys ([upload a bundle](./source-files.md#upload-a-bundle)). - Artifact IDs are UUIDs. **Vaults and Credentials** ([Vaults and Credentials](./vaults.md)) @@ -117,6 +128,7 @@ Each item is Core's deliberate or native behavior where the official service beh - An explicit `null` for OAuth `access_token`, `refresh` or `token_endpoint_auth` in an update keeps the stored value. - A static token must be an RFC 6750 `b64token` to run; other stored tokens fail at dispatch. - Vault metadata has a 64 KiB bound and no pair or length limits; names are 1–256 bytes after trimming. +- A Credential's `mcp_server_url` is stored and matched as sent; the official service lowercases its scheme and host. ## Known gaps @@ -146,6 +158,7 @@ Each item is Core's deliberate or native behavior where the official service beh - MiniMax Code does not declare `retained_native_history`, so it cannot run on microsandbox, which keeps every Environment on workspace storage; Core rejects the Session ([Harness capabilities](./harness-capabilities.md)). - Only `enabled` networking runs, so Sessions that need `disabled` or `restricted` are rejected ([restricted network policy](./environments.md#restricted-network)). - `packages.system` other than null or an empty list is rejected; system packages must be preinstalled. +- `Environment.files` lists the files recorded at Session creation; files created later through the Environment files API do not appear. - Cold continuation does not restore process memory, background processes or temporary system-disk changes, and completed setup is not replayed ([Environment persistence](./environments.md#runtime-capability-preparation)). On compatible microsandbox nodes with retained NFS storage, Codex and Claude Code are qualified for [checkpoint transfer](../../docs/sandbox-provider.md#checkpoint-transfer) and for continuation after [confirmed compute loss](../../docs/sandbox-provider.md#confirmed-compute-loss). Takeover of an unconfirmed old writer, host-crash durability and arbitrary crash-damaged history are unqualified. **Files and Environment files** @@ -171,11 +184,13 @@ Each item is Core's deliberate or native behavior where the official service beh - A Subagent's function call: Core makes it a required action of the root Turn that runs the child, with `turn_id` set to that Turn, and publishes the child's `function_call` Item once as `agent.session.turn.item.added` with the child Turn ID and a null `output_index`; a result may name either Turn. The Turn is `waiting` and the Session `requires_action` while root output may continue, and the `call_id` equals the `call_id` of the child's `function_call` Item. Claude Code publishes the child's Items when the root Turn settles, after the required action. - Whether Subagent child Turns and pending Environment file writes block Session deletion. - The official order between the pending-input error and an unknown result target. +- Whether a Session whose latest Turn failed accepts new input: Core starts a new Turn, and one official sample rejected the input. +- The event order when a waiting Turn resumes or is cancelled. - Failure reasons for npm, initial-file and Skill installation have no official sample. - Codex behavior for an empty text part beside text, and for images in failed function results or as remote references. - Official `HEAD` behavior on the routes where Core returns 405. - Environment Template hostname forms beyond exact hosts, and `disabled` combined with domains. -- Files purpose filtering and pagination while Files change; official Skill upload limits and error timing. -- Environment file list defaults (limit 20, the workspace root as the default path, no recursion, page-token invalidation), the 50 MiB `file_id` copy limit and the check order on create. +- Files purpose filtering and pagination while Files change; official Skill upload limits and error timing, and the error for a malformed Skill version. +- Environment file list defaults (limit 20, the workspace root as the default path, page-token invalidation), the 50 MiB `file_id` copy limit and the check order on create. - Artifact capture of hard links, special files and a linked `outputs` directory, republication after changed bytes, and content headers and ranges. -- Vault and Credential error and retry semantics, pagination under concurrent writes, visibility after deletion, exact-URL matching against the official normalization, OAuth refresh timing and errors, and restricted-key scopes. +- Vault and Credential error and retry semantics, pagination under concurrent writes, visibility after deletion, OAuth refresh timing and errors, and restricted-key scopes. diff --git a/contracts/agents-api/zh/index.md b/contracts/agents-api/zh/index.md index 2b1349bb2..7f347316b 100644 --- a/contracts/agents-api/zh/index.md +++ b/contracts/agents-api/zh/index.md @@ -1,7 +1,7 @@ --- title: "OpenAI 兼容性" source: contracts/agents-api/index.md -source_hash: 007c0a43dce8af3d21c5a4afb196ad2f62fad8b697ac3ba38eaab6ce955e0f88 +source_hash: ab06803446379f5a4e3525070360654f67d2bf6e4285ae10af9ef1dd551f25ff --- Core 实现下方固定版本的 OpenAI Agents API。本台账列出各项资源的覆盖情况、相对于官方服务的所有差异以及已知缺口。 @@ -61,6 +61,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - 未找到消息从不会指明具体资源;Core 会给完整的元数据键加引号,而官方消息会将其缩略。 - UUID 标识符也可按其他拼写形式解析,例如大写形式或带花括号的形式。 - 对于重复的查询键,Files 路由会保留本地 `unsupported_parameter` 代码。 +- Core 不处理 CORS;官方服务会发送 CORS 标头。 **列表**([lists](wire-semantics.md#lists)) @@ -85,7 +86,10 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - `stdio` MCP 服务器需要工作区部署位置和 `environment` 来源。Claude Code 在其工作区目录中启动服务器,因此 `cwd` 必须与之相同;服务器继承整个进程环境,其中也有模型提供方密钥和其他服务器的 Vault bearer 令牌;且 `allowed_tools` 须为 null。MiniMax Code 在其私有主目录中启动服务器,因此拒绝所有 `stdio` 服务器([MCP](execution-tools.md#mcp))。 - Core 拒绝非空的 MCP `request_metadata`,因为没有 Harness 能发送它;同样拒绝 `connection_origin` 为 `service` 的 `stdio` 服务器,以及空的 `credential_id` 和空的 `allowed_tools` 名称,固定版本的 schema 允许这些值但没有定义其含义(400,并说明原因)。 - Claude 会拒绝包含 `${` 的 MCP `server_url` 或 `headers` 值,因为原生客户端会从持有 Core 所持凭据的进程环境中展开这两处的 `${VAR}`。 +- 每个 Harness 都会拒绝其原生客户端保留的 MCP 标签,例如 Claude Code 上的 `functions`([MCP](execution-tools.md#mcp))。 +- 无法连接的 MCP 服务器由原生方式处理:可选服务器的工具缺失,必需服务器使启动失败([MCP](execution-tools.md#mcp))。Core 不复现官方的 Item 和 Turn 失败形态。 - 在 events 202 之后立即删除 Session 会返回 409,因为 Core 会在同一事务中准入该 Turn;官方服务返回 200。 +- hosted Environment 运行 setup 期间,若没有待处理输入,删除 Session 会成功;官方服务返回 409。 **输入、事件和历史**([Sessions, events and history](sessions-events.md)、[message content](message-content.md)) @@ -103,12 +107,19 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - Harness 输出(例如命令输出)中的 U+0000 读取时为 U+FFFD;官方服务会保留该字符。 - `reasoning` Item 携带 Harness 对其原生推理所展示的内容:Harness 产生原生摘要时为该摘要,否则为其原生推理文本,例如 Codex 的原始推理,或模型 API 返回给 Claude Code 的 thinking 文本。每个原生部分对应一个 `summary_text` 部分,没有文本的原生推理不会上报,因此模型提供方的 `thinking.display` 为 `omitted` 时,Claude Code 不上报推理。Codex 流式输出一个 item 先送达的原生通道,即摘要或原始推理文本。 +**Environments 和模板**([Environments](environments.md)) + +- `openai_hosted` 和模板的 `capability_directories` 必须位于 `/workspace` 内;官方服务也接受 `/etc` 等系统路径([能力目录](environments.md#plugins-and-capability-directories))。 +- `env` 不能设置 Core 保留的 `OPENAI_API_KEY`([env](environments.md#env-and-setup-commands));官方服务接受该变量。 + **Files、Skills、Environment files 和 Artifacts**([Files and Skills](source-files.md)、[Environment files and Artifacts](environment-files.md)) - 文件上传上限为 512 MiB;官方上限为 512 MB。`purpose` 过滤值不是 `user_data` 时会返回空页面。 - Skill 版本号绝不复用,并且针对某个 Skill 的上传和删除会串行执行。 - Environment files 可用于 `self_hosted` Environments,而官方服务会拒绝。 - 在已有常规文件上创建 Environment file 会返回 "must not traverse symlinks or overwrite existing files" 消息。若父级符号链接仍位于工作区内,则会跟随该链接;若父级逸出工作区或父级本身是常规文件,则会返回通用 400;官方服务会拒绝父级符号链接。 +- 文件名长度为 1–1,024 字节;官方服务接受空文件名和更长的文件名。 +- `SKILL.md` front matter 中 `name`、`description`、`license`、`compatibility` 和 `metadata` 以外的键会被拒绝;官方服务接受未知键([上传 bundle](source-files.md#upload-a-bundle))。 - Artifact ID 均为 UUID。 **Vaults 和 Credentials**([Vaults and Credentials](vaults.md)) @@ -120,6 +131,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - 更新时显式为 OAuth `access_token`、`refresh` 或 `token_endpoint_auth` 指定 `null`,会保留已存储的值。 - 静态令牌要成功运行,必须是 RFC 6750 `b64token`;其他已存储令牌会在派发时失败。 - Vault 元数据上限为 64 KiB,且没有键对或长度限制;名称去除首尾空白后为 1–256 字节。 +- Credential 的 `mcp_server_url` 按原样存储和匹配;官方服务会把其 scheme 和 host 转为小写。 ## 已知缺口 {#known-gaps} @@ -149,6 +161,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - MiniMax Code 未声明 `retained_native_history`,因此无法在 microsandbox 上运行(其每个 Environment 都使用工作区存储);Core 会拒绝该 Session([Harness 能力](./harness-capabilities.md))。 - 只有 `enabled` 网络可以运行,因此需要 `disabled` 或 `restricted` 的 Session 会被拒绝([restricted network policy](environments.md#restricted-network))。 - 除 null 或空列表以外的 `packages.system` 都会被拒绝;系统软件包必须预先安装。 +- `Environment.files` 列出 Session 创建时记录的文件;之后通过 Environment files API 创建的文件不会出现。 - 冷续接不恢复进程内存、后台进程或临时系统盘修改,已完成的 setup 不会重放(参见 [Environment 持久化](environments.md#runtime-capability-preparation))。在使用保留 NFS 存储的兼容 microsandbox 节点上,Codex 和 Claude Code 已通过[检查点转移](../../../docs/zh/sandbox-provider.md#checkpoint-transfer)以及[已确认的计算丢失](../../../docs/zh/sandbox-provider.md#confirmed-compute-loss)后续接的资格验证。接管未确认停止的旧写入者、主机崩溃时的持久性及任意崩溃受损历史的完整性仍未通过资格验证。 **Files 和 Environment files** @@ -174,11 +187,13 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - Subagent 的函数调用:Core 将其作为运行该子级的根 Turn 的待执行操作,`turn_id` 为该 Turn,并把子级的 `function_call` Item 以 `agent.session.turn.item.added` 发布一次,`turn_id` 为子级 Turn ID,`output_index` 为 null;结果可以指定其中任一 Turn。该 Turn 为 `waiting`、Session 为 `requires_action`,根输出可继续,`call_id` 等于该子级 `function_call` Item 的 `call_id`。Claude Code 在根 Turn 收敛时才发布子级的 Item,晚于该待执行操作。 - Subagent 子级 Turns 和待处理的 Environment file 写入是否会阻止 Session 删除。 - 官方服务在待处理输入错误与未知结果目标之间的先后顺序。 +- 最新 Turn 失败的 Session 是否接受新输入:Core 会开始新的 Turn,而一个官方样本拒绝了该输入。 +- 等待中的 Turn 恢复或被取消时的事件顺序。 - npm、initial-file 和 Skill 安装的失败原因没有官方样本。 - Codex 对文本旁的空文本部分、失败函数结果中的图像或远程引用图像的行为。 - 在 Core 返回 405 的路由上,官方服务的 `HEAD` 行为。 - 精确主机名之外的 Environment 模板主机名形式,以及 `disabled` 与域结合使用的情况。 -- Files 发生变化时的 purpose 筛选和分页;官方 Skill 上传限制和错误时机。 -- Environment file 列表的默认值(limit 为 20、默认路径为工作区根目录、不递归、page-token 失效)、50 MiB 的 `file_id` 复制上限,以及创建时的检查顺序。 +- Files 发生变化时的 purpose 筛选和分页;官方 Skill 上传限制和错误时机,以及 Skill 版本号格式错误时的错误。 +- Environment file 列表的默认值(limit 为 20、默认路径为工作区根目录、page-token 失效)、50 MiB 的 `file_id` 复制上限,以及创建时的检查顺序。 - Artifact 对硬链接、特殊文件和链接形式的 `outputs` 目录的捕获,内容字节变化后的重新发布,以及内容标头和范围。 -- Vault 和 Credential 的错误与重试语义、并发写入下的分页、删除后的可见性、依据官方规范化处理进行精确 URL 匹配、OAuth 刷新的时机和错误,以及受限密钥范围。 +- Vault 和 Credential 的错误与重试语义、并发写入下的分页、删除后的可见性、OAuth 刷新的时机和错误,以及受限密钥范围。 From 522ed0d86bbe005c8fed870aa1bb16dd17321a10 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 12:51:06 +0800 Subject: [PATCH 05/84] Ship the Codex code-mode host in the Runtime image (#865) Native code_mode runs model-written scripts in codex-code-mode-host, which Codex 0.153.4 looks for beside its executable. The Runtime image carried only the codex executable, so programmatic tool calling on Codex failed in every Docker, microsandbox and E2B Environment. The native installer already ships the whole package. --- deploy/distribution/Runtime.Dockerfile | 2 +- docs/maintainers.md | 2 +- docs/zh/maintainers.md | 2 +- scripts/build-codex-runtime.sh | 4 ++-- services/core/deploy/codex/Dockerfile | 4 +++- services/core/deploy/codex/README.md | 6 +++--- 6 files changed, 11 insertions(+), 9 deletions(-) diff --git a/deploy/distribution/Runtime.Dockerfile b/deploy/distribution/Runtime.Dockerfile index 886bc08d5..8487bcd34 100644 --- a/deploy/distribution/Runtime.Dockerfile +++ b/deploy/distribution/Runtime.Dockerfile @@ -9,7 +9,7 @@ FROM ${MCODE_IMAGE} # Keep the shared daemon and dependencies from the MiniMax base. # Native harness packages remain outside the workspace. -COPY --from=codex /usr/local/bin/codex /usr/local/bin/codex +COPY --from=codex /usr/local/bin/codex /usr/local/bin/codex-code-mode-host /usr/local/bin/ COPY --from=codex /usr/local/codex-resources /usr/local/codex-resources COPY --from=claude /opt/claude-sdk /opt/claude-sdk diff --git a/docs/maintainers.md b/docs/maintainers.md index 4ba321ec6..d67aaa308 100644 --- a/docs/maintainers.md +++ b/docs/maintainers.md @@ -95,7 +95,7 @@ docker build --platform linux/amd64 -t oac-runtime:mcode "${OAC_DEV_HOME:-$HOME/ `scripts/prepare-release-runtimes.sh` runs the companion build from the pins. -The distribution combines the three Harness images into one Runtime image (`deploy/distribution/Runtime.Dockerfile`): the MiniMax Code image, which carries the daemon, with the Codex executable and resources and the Claude Code bundle copied in. It verifies that each image carries the daemon built from the same commit. +The distribution combines the three Harness images into one Runtime image (`deploy/distribution/Runtime.Dockerfile`): the MiniMax Code image, which carries the daemon, with the Codex executables and resources and the Claude Code bundle copied in. It verifies that each image carries the daemon built from the same commit. **E2B helper.** diff --git a/docs/zh/maintainers.md b/docs/zh/maintainers.md index 0a542a927..24908cbf9 100644 --- a/docs/zh/maintainers.md +++ b/docs/zh/maintainers.md @@ -1,7 +1,7 @@ --- title: "构建并发布 OpenAgentCore" source: docs/maintainers.md -source_hash: 4f856b71fa88a18950c6830dc906ef060ccf79f7514585606f0fdc9df94a89b5 +source_hash: 6f1b4534b4b473c47175560c24ca6e1d1fe2ff4c5e764f204d1022939e4178b3 --- 本指南面向负责构建和发布 OpenAgentCore 的维护者。要安装 Core 和 Web,请按 [安装 Core 和 Web](getting-started/install.md) 操作。安装程序代码遵循的规则见 [部署](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/deploy/README.md) 和 [节点安装程序](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/deploy/node/README.md);必需检查见 [CONTRIBUTING](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/CONTRIBUTING.md#required-checks)。 diff --git a/scripts/build-codex-runtime.sh b/scripts/build-codex-runtime.sh index 8269cd07c..9d650269f 100755 --- a/scripts/build-codex-runtime.sh +++ b/scripts/build-codex-runtime.sh @@ -18,7 +18,7 @@ package = json.load(open(sys.argv[1])) assert package['name'] == '@openai/codex' and package['version'] == '0.153.4-linux-x64', 'Expected pinned official Linux x64 package' PY native_dir="$package_dir/vendor/x86_64-unknown-linux-musl" -for executable in "$native_dir/bin/codex"; do +for executable in "$native_dir/bin/codex" "$native_dir/bin/codex-code-mode-host"; do test -x "$executable" || { printf 'Missing executable: %s\n' "$executable" >&2; exit 1; } done test -d "$native_dir/codex-resources" @@ -30,7 +30,7 @@ trap 'rm -rf "$context"' EXIT CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -mod=readonly -trimpath \ -o "$context/oac-daemon" ./apps/daemon/cmd/oac-daemon ) -cp "$native_dir/bin/codex" "$context/codex" +cp "$native_dir/bin/codex" "$native_dir/bin/codex-code-mode-host" "$context/" cp -R "$native_dir/codex-resources" "$context/codex-resources" cp "$repo_root/services/core/deploy/codex/Dockerfile" "$context/Dockerfile" cp "$repo_root/services/core/deploy/runtime_profile.py" "$context/runtime_profile.py" diff --git a/services/core/deploy/codex/Dockerfile b/services/core/deploy/codex/Dockerfile index d84a54b22..5b798f653 100644 --- a/services/core/deploy/codex/Dockerfile +++ b/services/core/deploy/codex/Dockerfile @@ -10,7 +10,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && mkdir -p /environment/workspace /workspace /home/runtime COPY runtime_profile.py /tmp/oac-runtime-profile.py RUN python3 /tmp/oac-runtime-profile.py && rm /tmp/oac-runtime-profile.py -COPY --chmod=0555 oac-daemon codex /usr/local/bin/ +# Native code_mode runs model-written scripts in codex-code-mode-host, which +# Codex finds beside its executable. +COPY --chmod=0555 oac-daemon codex codex-code-mode-host /usr/local/bin/ COPY codex-resources /usr/local/codex-resources ENV HOME=/home/runtime OAC_RUNTIME_HOME=/home/runtime/.oac \ OAC_RUNTIME_CODEX_BIN=/usr/local/bin/codex \ diff --git a/services/core/deploy/codex/README.md b/services/core/deploy/codex/README.md index 16eb3f4dc..64896f3ce 100644 --- a/services/core/deploy/codex/README.md +++ b/services/core/deploy/codex/README.md @@ -62,16 +62,16 @@ Codex `0.153.4` reports a provider HTTP 400 as `other` and puts the provider's e ## Runtime image -[`Dockerfile`](Dockerfile) builds the Codex Runtime image from a prepared context that holds only `oac-daemon`, the unmodified `codex` executable and `codex-resources`. +[`Dockerfile`](Dockerfile) builds the Codex Runtime image from a prepared context that holds only `oac-daemon`, the unmodified `codex` and `codex-code-mode-host` executables and `codex-resources`. Native `code_mode` runs its scripts in `codex-code-mode-host`, which Codex finds beside its executable. | Item | Value | | --- | --- | | Base | The [shared Runtime base](../../../../docs/maintainers.md#runtime-images-and-helpers) | -| Programs | `/usr/local/bin/oac-daemon`, `/usr/local/bin/codex` (mode 0555) and `/usr/local/codex-resources` | +| Programs | `/usr/local/bin/oac-daemon`, `/usr/local/bin/codex`, `/usr/local/bin/codex-code-mode-host` (mode 0555) and `/usr/local/codex-resources` | | User | UID/GID 1000 with `HOME=/home/runtime` | | Environment | `OAC_RUNTIME_HOME=/home/runtime/.oac`, `OAC_RUNTIME_CODEX_BIN=/usr/local/bin/codex`, `OAC_RUNTIME_INITIALIZATION_DIRECTORY=/environment/initialization`, `OAC_RUNTIME_PACKAGE_DIRECTORY=/environment/packages`, `OAC_RUNTIME_STATE_DIRECTORY=/environment/runtime-state` | | Entry point | `oac-daemon connect --profile default`, working directory `/environment/workspace` | -The build fails unless `codex --version` reports the pinned version. The image holds no credentials, workspace data or product software. The distribution copies the Codex executable and resources into the combined Runtime image; see the [maintainer guide](../../../../docs/maintainers.md#runtime-images-and-helpers). +The build fails unless `codex --version` reports the pinned version. The image holds no credentials, workspace data or product software. The distribution copies the Codex executables and resources into the combined Runtime image; see the [maintainer guide](../../../../docs/maintainers.md#runtime-images-and-helpers). The [Docker adapter](../../../../docs/sandbox-provider.md#docker-adapter) owns the shared container lifecycle and isolation settings. From aa32099f7ebd4dab0aeffb78d4fa8d40e1e49ab9 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 13:28:59 +0800 Subject: [PATCH 06/84] Record the remaining board differences (#866) The old Feishu board held a few differences the ledger lacked: prefixed official IDs, the idle self_hosted switch to requires_action, and three unverified shapes (parallel pending calls, Subagent task text and nesting, Template and Session env). The ledger is their only home now. The Environment files guide also loses a Claude Code read fallback that no longer exists. --- contracts/agents-api/environment-files.md | 1 - contracts/agents-api/index.md | 6 +++++- contracts/agents-api/zh/environment-files.md | 3 +-- contracts/agents-api/zh/index.md | 8 ++++++-- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/contracts/agents-api/environment-files.md b/contracts/agents-api/environment-files.md index 67fcc1345..099f6d5bf 100644 --- a/contracts/agents-api/environment-files.md +++ b/contracts/agents-api/environment-files.md @@ -31,7 +31,6 @@ The response is `{"object": "page", "data": [...], "next": …, "has_more": …} - A `path` that does not exist, names a regular file, or passes through a symbolic link returns an empty page. Links are never followed. - Each page reads the directory again; there is no snapshot. If the directory's regular files (their names or sizes) or the request's parameters changed since the token was issued, the token is rejected. Unchanged names and sizes do not prove unchanged contents. - A directory with more than 1,024 entries of any kind returns 503 and no partial page. Permission errors, a missing workspace root and transport failures also return 503. -- When the daemon has no local workspace binding, the Claude Code adapter answers the read instead: a missing path returns 404, and a regular file or symbolic link returns 503. Query errors, all with type and code `invalid_request_error` and a null `param` unless noted: diff --git a/contracts/agents-api/index.md b/contracts/agents-api/index.md index 0e69b86a0..c938e5458 100644 --- a/contracts/agents-api/index.md +++ b/contracts/agents-api/index.md @@ -56,6 +56,7 @@ Each item is Core's deliberate or native behavior where the official service beh - A JSON array body is rejected; the official service reads `[]` as `{}`. - U+0000 in a stored string returns 400; the official service stores it. - Not-found messages never name the resource; Core quotes a full metadata key where the official message abbreviates it. +- Resource IDs are UUIDs; official IDs carry a type prefix, such as `sess_` for Sessions. - UUID identifiers also resolve in other spellings, such as uppercase or braces. - The Files routes keep a local `unsupported_parameter` code for a repeated query key. - Core has no CORS handling; the official service sends CORS headers. @@ -108,6 +109,7 @@ Each item is Core's deliberate or native behavior where the official service beh - `openai_hosted` and Template `capability_directories` must lie inside `/workspace`; the official service also accepts system paths such as `/etc` ([capability directories](./environments.md#plugins-and-capability-directories)). - `env` cannot set `OPENAI_API_KEY`, which Core reserves ([env](./environments.md#env-and-setup-commands)); the official service accepts it. +- A `self_hosted` Session without pending input requests no connection ([activity](./environments.md#activity-and-required-actions)); one unused official Session switched to `requires_action` with `environment_connection` about five minutes after creation, and its deletion then returned 409. **Files, Skills, Environment files and Artifacts** ([Files and Skills](./source-files.md), [Environment files and Artifacts](./environment-files.md)) @@ -117,7 +119,6 @@ Each item is Core's deliberate or native behavior where the official service beh - Creating an Environment file over an existing regular file returns the "must not traverse symlinks or overwrite existing files" message. A parent symbolic link that stays inside the workspace is followed, and a parent that escapes the workspace or is a regular file gets a generic 400; the official service rejects symbolic-link parents. - File names hold 1–1,024 bytes; the official service accepts empty and longer names. - A `SKILL.md` front-matter key other than `name`, `description`, `license`, `compatibility` and `metadata` is rejected; the official service accepts unknown keys ([upload a bundle](./source-files.md#upload-a-bundle)). -- Artifact IDs are UUIDs. **Vaults and Credentials** ([Vaults and Credentials](./vaults.md)) @@ -186,6 +187,9 @@ Each item is Core's deliberate or native behavior where the official service beh - The official order between the pending-input error and an unknown result target. - Whether a Session whose latest Turn failed accepts new input: Core starts a new Turn, and one official sample rejected the input. - The event order when a waiting Turn resumes or is cancelled. +- A Turn with several pending function calls: Core lists them all in one `requires_action`; no official sample had parallel calls. +- Subagent task text and nesting: Core puts the native task prompt in the `create_subagent_call` content, while one official sample left it out; the `agent_id` of a nested child and the child's input Item have no official sample. +- Template `env` beside Session `env`: Core merges by key and the Session value wins ([inheritance](./environments.md#inheritance)). - Failure reasons for npm, initial-file and Skill installation have no official sample. - Codex behavior for an empty text part beside text, and for images in failed function results or as remote references. - Official `HEAD` behavior on the routes where Core returns 405. diff --git a/contracts/agents-api/zh/environment-files.md b/contracts/agents-api/zh/environment-files.md index e9264a806..7aa6205da 100644 --- a/contracts/agents-api/zh/environment-files.md +++ b/contracts/agents-api/zh/environment-files.md @@ -1,7 +1,7 @@ --- title: "Environment 文件与 Artifact" source: contracts/agents-api/environment-files.md -source_hash: b6c51bd066cf70b6cce4c38ba1403dc3463574fcbc254bf64f8c98b6aeca9b93 +source_hash: ad6e0c122104ff5600d07305902871253c81aef0525e12358a5cc8abdc42600a --- Session 工作区保存由 agent 及其工具修改的实时文件。`/agents/environments/{environment_id}/files` 列出一个工作区目录,并在其中创建文件。Turn 完成时,Core 将工作区 `outputs/` 目录中的文件复制为不可变 Artifact,通过 `/agents/sessions/{session_id}/artifacts` 读取。Artifact 的生命周期长于 Environment;工作区文件则不是。 @@ -33,7 +33,6 @@ Session 工作区保存由 agent 及其工具修改的实时文件。`/agents/en - `path` 不存在、指向普通文件或经过符号链接时返回空页。不跟随链接。 - 每页重新读取目录,不提供快照。token 签发后目录普通文件(名称或大小)或请求参数改变时,token 被拒绝。名称和大小未变不证明内容未变。 - 目录中任何类型条目合计超过 1,024 个时返回 503,不返回部分页。权限错误、工作区根缺失和传输失败也返回 503。 -- daemon 无本地工作区绑定时,改由 Claude Code 适配器回答读取:路径缺失返回 404,普通文件或符号链接返回 503。 查询错误的 type 和 code 均为 `invalid_request_error`,除另有说明外 `param` 为 null: diff --git a/contracts/agents-api/zh/index.md b/contracts/agents-api/zh/index.md index 7f347316b..f545637d7 100644 --- a/contracts/agents-api/zh/index.md +++ b/contracts/agents-api/zh/index.md @@ -1,7 +1,7 @@ --- title: "OpenAI 兼容性" source: contracts/agents-api/index.md -source_hash: ab06803446379f5a4e3525070360654f67d2bf6e4285ae10af9ef1dd551f25ff +source_hash: 09fcf64102a376e53b2881621c21647afb7187e3899ef6c4b9f350fa7a2d95fe --- Core 实现下方固定版本的 OpenAI Agents API。本台账列出各项资源的覆盖情况、相对于官方服务的所有差异以及已知缺口。 @@ -59,6 +59,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - JSON 数组请求体会被拒绝;官方服务会将 `[]` 读取为 `{}`。 - 存储的字符串中含有 U+0000 时会返回 400;官方服务会存储该字符。 - 未找到消息从不会指明具体资源;Core 会给完整的元数据键加引号,而官方消息会将其缩略。 +- 资源 ID 均为 UUID;官方 ID 带有类型前缀,例如 Session 的 `sess_`。 - UUID 标识符也可按其他拼写形式解析,例如大写形式或带花括号的形式。 - 对于重复的查询键,Files 路由会保留本地 `unsupported_parameter` 代码。 - Core 不处理 CORS;官方服务会发送 CORS 标头。 @@ -111,6 +112,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - `openai_hosted` 和模板的 `capability_directories` 必须位于 `/workspace` 内;官方服务也接受 `/etc` 等系统路径([能力目录](environments.md#plugins-and-capability-directories))。 - `env` 不能设置 Core 保留的 `OPENAI_API_KEY`([env](environments.md#env-and-setup-commands));官方服务接受该变量。 +- 没有待处理输入的 `self_hosted` Session 不会请求连接([活动状态](environments.md#activity-and-required-actions));一个未使用的官方 Session 在创建约五分钟后转为 `requires_action`,原因为 `environment_connection`,之后删除它返回 409。 **Files、Skills、Environment files 和 Artifacts**([Files and Skills](source-files.md)、[Environment files and Artifacts](environment-files.md)) @@ -120,7 +122,6 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - 在已有常规文件上创建 Environment file 会返回 "must not traverse symlinks or overwrite existing files" 消息。若父级符号链接仍位于工作区内,则会跟随该链接;若父级逸出工作区或父级本身是常规文件,则会返回通用 400;官方服务会拒绝父级符号链接。 - 文件名长度为 1–1,024 字节;官方服务接受空文件名和更长的文件名。 - `SKILL.md` front matter 中 `name`、`description`、`license`、`compatibility` 和 `metadata` 以外的键会被拒绝;官方服务接受未知键([上传 bundle](source-files.md#upload-a-bundle))。 -- Artifact ID 均为 UUID。 **Vaults 和 Credentials**([Vaults and Credentials](vaults.md)) @@ -189,6 +190,9 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - 官方服务在待处理输入错误与未知结果目标之间的先后顺序。 - 最新 Turn 失败的 Session 是否接受新输入:Core 会开始新的 Turn,而一个官方样本拒绝了该输入。 - 等待中的 Turn 恢复或被取消时的事件顺序。 +- 有多个待处理函数调用的 Turn:Core 在同一个 `requires_action` 中列出全部调用;官方样本中没有并行调用。 +- Subagent 的任务文本和嵌套:Core 把原生任务提示放在 `create_subagent_call` 的内容中,而一个官方样本省略了它;嵌套子级的 `agent_id` 和子级的输入 Item 没有官方样本。 +- 模板 `env` 与 Session `env` 并存:Core 按键合并,以 Session 的值为准([继承](environments.md#inheritance))。 - npm、initial-file 和 Skill 安装的失败原因没有官方样本。 - Codex 对文本旁的空文本部分、失败函数结果中的图像或远程引用图像的行为。 - 在 Core 返回 405 的路由上,官方服务的 `HEAD` 行为。 From 27397cdf09e9c08ccaa3ec16a28276a98a8e7db1 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 13:52:38 +0800 Subject: [PATCH 07/84] Keep the console route when skipping to content (#867) The skip link and the console router both use the URL fragment, so following #main-content sent every page to Overview and dropped its parameters. The link now moves focus to the main element without navigating. Closes #421. --- apps/web/e2e/unified-settings.spec.ts | 12 ++++++++++++ apps/web/src/ConsoleApp.tsx | 6 +++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/apps/web/e2e/unified-settings.spec.ts b/apps/web/e2e/unified-settings.spec.ts index 549e8495e..d1c1cf434 100644 --- a/apps/web/e2e/unified-settings.spec.ts +++ b/apps/web/e2e/unified-settings.spec.ts @@ -151,3 +151,15 @@ test("a phone scrolls wide tables inside their frames and keeps every Settings t await expect(page.getByRole("table", { name: "Startup settings" }).getByRole("columnheader", { name: "Restarts", exact: true })).toBeInViewport({ ratio: 1 }); expect(await pageScrollsSideways()).toBe(false); }); + +test("skip to content moves focus to the page and keeps its route", async ({ page, request }) => { + await openConsole(page, request, "settings?id=storage"); + const current = page.getByRole("navigation").getByRole("button", { name: "Workspace storage", exact: true }); + await expect(current).toHaveAttribute("aria-current", "page"); + await page.keyboard.press("Tab"); + await expect(page.getByRole("link", { name: "Skip to main content" })).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(page.locator("#main-content")).toBeFocused(); + await expect(current).toHaveAttribute("aria-current", "page"); + expect(new URL(page.url()).hash).toBe("#settings?id=storage"); +}); diff --git a/apps/web/src/ConsoleApp.tsx b/apps/web/src/ConsoleApp.tsx index 8e55c738e..e661d0103 100644 --- a/apps/web/src/ConsoleApp.tsx +++ b/apps/web/src/ConsoleApp.tsx @@ -120,7 +120,11 @@ function ConsoleShell() {
- {t("skipToContent")} + {/* The router owns the URL fragment, so the link moves focus instead of navigating. */} + { + event.preventDefault(); + document.getElementById("main-content")?.focus(); + }}>{t("skipToContent")} navigate(view)} onIntent={prefetch} onGettingStarted={() => navigate("overview", {}, "getting-started")} />
From da66c0bb109fc20b8fd89156b12441f149b12eed Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 13:54:41 +0800 Subject: [PATCH 08/84] Stop publishing unused release archives (#869) * Leave build-only files out of native installers The node component omits the CI runner's global pnpm and the minimax component omits better-sqlite3's deps, src and binding.gyp. Neither is loaded at run time. linux-amd64 archives shrink by 4.6 MB (node) and 2.7 MB (minimax) compressed. * Stop publishing unused release archives The control archives carry the Core, Web and ingress images and the native catalog from the build to the publisher, which pushes the images to GHCR. No install path downloads them, so the publisher no longer uploads them as release assets (337 MB per release). --- docs/maintainers.md | 4 ++-- docs/zh/maintainers.md | 6 +++--- scripts/build-native-installer.mjs | 13 +++++++++++-- scripts/build-native-installer.test.mjs | 12 ++++++++++++ scripts/publish-core-release.py | 4 ++++ scripts/publish-core-release.test.py | 8 +++++--- 6 files changed, 37 insertions(+), 10 deletions(-) diff --git a/docs/maintainers.md b/docs/maintainers.md index d67aaa308..63ee61bdb 100644 --- a/docs/maintainers.md +++ b/docs/maintainers.md @@ -6,7 +6,7 @@ This guide is for maintainers who build and publish OpenAgentCore. To install Co ## Build a distribution -A distribution is a matched set of release assets built from one commit: the control archive (the installer, the `oac` command, and the Core, Web, ingress and PostgreSQL images), the Runtime image and node artifacts as separate files, and the native installers. +A distribution is a matched set of release assets built from one commit: the Runtime image and node artifacts as separate files, and the native installers. The build also writes a control archive per architecture (the installer, the `oac` command, and the Core, Web, ingress and PostgreSQL images). The publisher reads the images and the native catalog from it; nothing installs from it, so it is not a release asset. Core, Web and ingress images are published as verified Linux amd64/arm64 indexes. The arm64 control archive contains those three images; Node, hosted Runtime and offline payloads use Linux amd64. Release builders use QEMU for ARM image steps, including the E2B helper. Host `oac` binaries are built from the same command for Linux amd64/arm64, macOS amd64/arm64 and Windows amd64; launchers only select, verify and invoke them. Each version index is checked against its platform archives before floating tags move. @@ -53,7 +53,7 @@ node scripts/build-native-catalog.mjs INPUT_DIR OUTPUT_DIR export OAC_NATIVE_INSTALLER_BUILD_DIR=OUTPUT_DIR ``` -Each platform has a small base archive `-.tar.gz` (`oac-daemon` and `bundle.json`, which lists every component with the SHA-256 of each file) and one archive per component, `--node` and `--` (MiniMax Code is not built for Windows). `build-native-installer.mjs` writes them. Core serves these artifacts by name and knows nothing of their content; `oac-daemon install` downloads the components it needs. +Each platform has a small base archive `-.tar.gz` (`oac-daemon` and `bundle.json`, which lists every component with the SHA-256 of each file) and one archive per component, `--node` and `--` (MiniMax Code is not built for Windows). `build-native-installer.mjs` writes them and leaves out files that only build or install tooling: the CI runner's global pnpm in `node`, and the compiler inputs of `better-sqlite3` in `minimax`. Core serves these artifacts by name and knows nothing of their content; `oac-daemon install` downloads the components it needs. The catalog records the commit, the Runtime protocol version, each artifact's SHA-256 and, with a release base, its versioned URL. The control archive and Core image carry only `native-installers/catalog.json`; the archives become separate `oac-native--.tar.gz` release assets, and the offline archive holds a copy of every Linux amd64 archive outside the Core image, which its `install.py` copies into the installation for Core to serve. Core redirects the other platforms to their release assets; a catalog without a release base has no such URL, so its offline archive holds every archive. Without a catalog, Sessions report the install command as unavailable, and the release workflow refuses to publish. diff --git a/docs/zh/maintainers.md b/docs/zh/maintainers.md index 24908cbf9..32e882a5a 100644 --- a/docs/zh/maintainers.md +++ b/docs/zh/maintainers.md @@ -1,14 +1,14 @@ --- title: "构建并发布 OpenAgentCore" source: docs/maintainers.md -source_hash: 6f1b4534b4b473c47175560c24ca6e1d1fe2ff4c5e764f204d1022939e4178b3 +source_hash: 0b605c6f5df332a2eb9831d3026b4bcde4ae6d7a2e2cb7bd8b3ce3a21704a7db --- 本指南面向负责构建和发布 OpenAgentCore 的维护者。要安装 Core 和 Web,请按 [安装 Core 和 Web](getting-started/install.md) 操作。安装程序代码遵循的规则见 [部署](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/deploy/README.md) 和 [节点安装程序](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/deploy/node/README.md);必需检查见 [CONTRIBUTING](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/CONTRIBUTING.md#required-checks)。 ## 构建分发包 {#build-a-distribution} -分发包是从同一个提交构建的一组相互匹配的发布资源:控制归档(安装程序、`oac` 命令,以及 Core、Web、ingress 和 PostgreSQL 镜像)、作为独立文件的 Runtime 镜像和节点构件,以及原生安装程序。 +分发包是从同一个提交构建的一组相互匹配的发布资源:作为独立文件的 Runtime 镜像和节点构件,以及原生安装程序。构建还会为每种架构生成一个控制归档(安装程序、`oac` 命令,以及 Core、Web、ingress 和 PostgreSQL 镜像)。发布器从中读取镜像和原生目录;没有任何安装流程使用它,因此它不是发布资源。 Core、Web 和 ingress 镜像发布为经过校验的 Linux amd64/arm64 多架构索引。arm64 控制归档包含这三个镜像;Node、托管 Runtime 和离线包使用 Linux amd64。发行构建使用 QEMU 执行 ARM 镜像步骤,包括 E2B helper。主机 `oac` 从同一份实现构建为 Linux amd64/arm64、macOS amd64/arm64 和 Windows amd64 二进制;启动脚本只选择、校验并运行它们。所有版本索引校验通过后才更新浮动标签。 @@ -55,7 +55,7 @@ node scripts/build-native-catalog.mjs INPUT_DIR OUTPUT_DIR export OAC_NATIVE_INSTALLER_BUILD_DIR=OUTPUT_DIR ``` -每个平台有一个小型基础归档 `-.tar.gz`(`oac-daemon` 和 `bundle.json`,后者列出每个组件及其每个文件的 SHA-256),以及每个组件一个归档,即 `--node` 和 `--`(MiniMax Code 不为 Windows 构建)。`build-native-installer.mjs` 生成它们。Core 按名称提供这些制品,不了解其内容;`oac-daemon install` 下载所需的组件。 +每个平台有一个小型基础归档 `-.tar.gz`(`oac-daemon` 和 `bundle.json`,后者列出每个组件及其每个文件的 SHA-256),以及每个组件一个归档,即 `--node` 和 `--`(MiniMax Code 不为 Windows 构建)。`build-native-installer.mjs` 生成它们,并略去仅用于构建或安装的文件:`node` 中 CI 运行器全局安装的 pnpm,以及 `minimax` 中 `better-sqlite3` 的编译输入。Core 按名称提供这些制品,不了解其内容;`oac-daemon install` 下载所需的组件。 该目录会记录提交、Runtime 协议版本、每个制品的 SHA-256,并在提供发布基址时记录其带版本号的 URL。控制归档和 Core 镜像仅携带 `native-installers/catalog.json`;这些归档会成为独立的 `oac-native--.tar.gz` 发布资源,离线归档则会在 Core 镜像之外保留所有 Linux amd64 归档的一份副本,由其 `install.py` 复制到安装目录中供 Core 提供下载。其他平台由 Core 重定向到对应的发布资源;没有发布基址的目录没有这类 URL,因此其离线归档会保留所有归档。如果没有目录,Sessions 会将安装命令报告为不可用,并且发布工作流会拒绝发布。 diff --git a/scripts/build-native-installer.mjs b/scripts/build-native-installer.mjs index 474d73a34..168278947 100644 --- a/scripts/build-native-installer.mjs +++ b/scripts/build-native-installer.mjs @@ -27,11 +27,12 @@ async function outputRealPath(path) { // Flatten contained links, including directory links used by pnpm exports. Every // traversal checks its resolved target; active ancestors detect directory cycles. -export async function copyComponent(source, destination) { +export async function copyComponent(source, destination, omit = []) { const root = await realpath(source); if (!(await stat(root)).isDirectory()) throw new Error('Component source must be a directory'); const files = {}; async function visit(path, target, ancestors) { + if (omit.includes(relative(destination, target).split(sep).join('/'))) return; const resolved = await realpath(path); if (!inside(root, resolved)) throw new Error('Component link escapes its source'); const info = await stat(resolved); @@ -66,6 +67,14 @@ function probe(command, args, cwd, env) { if (result.error || result.status !== 0) throw new Error('Native component compatibility probe failed'); return result.stdout.trim(); } +// Files that only build or install tooling and that no Harness or the daemon loads at run time. +// pnpm is the CI runner's global install, not part of the Node distribution. better-sqlite3 loads only +// build/Release/better_sqlite3.node, with SQLite compiled in; deps/ and src/ are its compiler inputs. +// Names cover the Unix and Windows layouts. +const buildOnly = { + node: ['bin/pnpm', 'bin/pnpx', 'lib/node_modules/pnpm', 'node_modules/pnpm', 'pnpm', 'pnpm.cmd', 'pnpm.ps1', 'pnpx', 'pnpx.cmd', 'pnpx.ps1'], + minimax: ['native/node_modules/better-sqlite3/deps', 'native/node_modules/better-sqlite3/src', 'native/node_modules/better-sqlite3/binding.gyp'], +}; const json = async path => JSON.parse(await readFile(path, 'utf8')); const requireFile = async path => { if (!(await stat(path)).isFile()) throw new Error('Required component file is missing'); }; @@ -160,7 +169,7 @@ export async function buildBundle(options) { await copyFile(options.daemon, daemon); await chmod(daemon, 0o755); await mkdir(join(staging, 'components')); const components = {}; - for (const name of ['node', ...names]) components[name] = { version: pins[name], files: await copyComponent(options[name], join(staging, 'components', name)) }; + for (const name of ['node', ...names]) components[name] = { version: pins[name], files: await copyComponent(options[name], join(staging, 'components', name), buildOnly[name]) }; await prepareNodeEntrypoints(join(staging, 'components', 'node'), components.node.files); if (components.minimax) { const component = join(staging, 'components', 'minimax'); diff --git a/scripts/build-native-installer.test.mjs b/scripts/build-native-installer.test.mjs index 700ea462c..e9131568f 100644 --- a/scripts/build-native-installer.test.mjs +++ b/scripts/build-native-installer.test.mjs @@ -28,6 +28,18 @@ test('component preserves bytes and executable metadata with contained links fla assert.deepEqual(Object.keys(files).sort(), ['lib/native', 'linked/native']); }); +test('component leaves out the named build-only paths', async t => { + const { source, output } = await fixture(t); + await mkdir(join(source, 'pkg/deps'), { recursive: true }); + await mkdir(join(source, 'pkg/build'), { recursive: true }); + await writeFile(join(source, 'pkg/deps/sqlite3.c'), 'source'); + await writeFile(join(source, 'pkg/binding.gyp'), '{}'); + await writeFile(join(source, 'pkg/build/addon.node'), 'binary'); + const files = await copyComponent(source, output, ['pkg/deps', 'pkg/binding.gyp']); + assert.deepEqual(Object.keys(files), ['pkg/build/addon.node']); + await assert.rejects(lstat(join(output, 'pkg/deps'))); +}); + test('component rejects escaping directory links', async t => { const { root, source, output } = await fixture(t); await mkdir(join(root, 'outside')); await writeFile(join(root, 'outside/secret'), 'not bundled'); diff --git a/scripts/publish-core-release.py b/scripts/publish-core-release.py index 8f6308995..cb568d4b7 100644 --- a/scripts/publish-core-release.py +++ b/scripts/publish-core-release.py @@ -250,6 +250,9 @@ def publish(assets, repository, revision, tag, mode): files = sorted(assets.iterdir()) if not files or any(p.is_symlink() or not p.is_file() for p in files): raise ValueError("Expected a nonempty directory containing only regular asset files") + # The control archives carry the Core, Web and ingress images and the native + # catalog from the build to this script. Nothing installs from them, so they are not release assets. + control = {f"oac-{revision}-linux-{arch}.tar.gz{suffix}" for arch in ("amd64", "arm64") for suffix in ("", ".sha256")} # The builder validates the manifest and Runtime assets. Verify archives again # after the Actions artifact transfer between jobs. stem = "oac-" + revision + "-linux-amd64" @@ -296,6 +299,7 @@ def publish(assets, repository, revision, tag, mode): endpoint = "releases/" + str(release_id) # Keep every operation bound to the ID returned by creation. No tag lookup, # overwrite, deletion or automatic retry can select another release. + files = [p for p in files if p.name not in control] expected = {p.name: p.stat().st_size for p in files} def upload(path): print(f"Uploading {path.name} ({expected[path.name]} bytes)", flush=True) diff --git a/scripts/publish-core-release.test.py b/scripts/publish-core-release.test.py index 584b2e4b8..d2cd4b67e 100644 --- a/scripts/publish-core-release.test.py +++ b/scripts/publish-core-release.test.py @@ -68,7 +68,7 @@ def test_draft_publishes_images_and_stays_unpublished(self): self.publish(tag="build-" + self.revision, mode="draft") self.images.assert_called_once() self.assertTrue(self.release["draft"]) - self.assertEqual(len(self.release["assets"]), 28) + self.assertEqual(len(self.release["assets"]), 24) def test_missing_native_asset_refuses_release_creation(self): (self.assets / f"oac-native-{self.revision}-windows-amd64-codex.tar.gz").unlink() @@ -142,7 +142,7 @@ def response(repo, endpoint, *args): return result if endpoint == "releases/7": self.assertEqual(active, 0) - self.assertIn(len(self.release["assets"]), (26, 28)) + self.assertIn(len(self.release["assets"]), (22, 24)) return self.response(repo, endpoint, *args) self.api.side_effect = response self.publish() @@ -153,8 +153,10 @@ def test_version_tag_publishes_complete_fixed_id(self): self.publish() self.assertFalse(self.release["draft"]) self.assertFalse(self.release["prerelease"]) - self.assertEqual(len(self.release["assets"]), 28) + self.assertEqual(len(self.release["assets"]), 24) self.assertEqual({a["name"] for a in self.release["assets"] if a["name"].endswith(".yaml")}, {"compose.yaml"}) + self.assertFalse([a for a in self.release["assets"] if "-linux-amd64.tar.gz" in a["name"] and a["name"].startswith("oac-" + self.revision) + or "-linux-arm64.tar.gz" in a["name"] and a["name"].startswith("oac-" + self.revision)]) self.assertEqual(self.api.call_args.args[1:], ("releases/7", "--method", "PATCH", "-F", "draft=false")) From e8e658ea8ba2fe2e278caa58315a5d67e7a46a83 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 13:58:25 +0800 Subject: [PATCH 09/84] Emit Environment pending and ready events (#870) --- contracts/agents-api/environments.md | 1 + contracts/agents-api/index.md | 4 +++- contracts/agents-api/zh/environments.md | 3 ++- contracts/agents-api/zh/index.md | 6 ++++-- .../sessions/execution_environment.go | 20 +++++++++++++++++-- .../sessions/execution_environment_test.go | 10 +++++++--- ...sted_initialization_failure_public_test.go | 6 +++--- .../runtime_initialization_test.go | 13 ++++++++++++ 8 files changed, 51 insertions(+), 12 deletions(-) diff --git a/contracts/agents-api/environments.md b/contracts/agents-api/environments.md index 623ab7bb6..e99afc829 100644 --- a/contracts/agents-api/environments.md +++ b/contracts/agents-api/environments.md @@ -255,6 +255,7 @@ stateDiagram-v2 - Each file, Skill or Plugin transfer has a two-minute staging budget. Configure, package installation, setup commands and snapshot finalization share the whole initialization’s 30-minute budget, whose remaining duration Core carries on each operation and the Runtime enforces. Initial input keeps its five-minute admission deadline, so large installations should start from an idle Session. - A running initialization whose owner is lost, including across a Core restart, fails as unconfirmed; nothing is replayed. A completed Environment never reinstalls on reconnect or native recovery, so later user changes survive. - Failure is terminal for the Session but destroys neither compute nor files. +- An `openai_hosted` Environment journals `agent.session.environment.pending` in the transaction that starts its initialization and `agent.session.environment.ready` in the one that completes it, each exactly once. A `self_hosted` Environment emits neither. A failed initialization records the events and Session state that [Environment initialization failure](./sessions-events.md#environment-initialization-failure) defines. The reason names only the step and its exit status: diff --git a/contracts/agents-api/index.md b/contracts/agents-api/index.md index c938e5458..4cb29a291 100644 --- a/contracts/agents-api/index.md +++ b/contracts/agents-api/index.md @@ -110,6 +110,7 @@ Each item is Core's deliberate or native behavior where the official service beh - `openai_hosted` and Template `capability_directories` must lie inside `/workspace`; the official service also accepts system paths such as `/etc` ([capability directories](./environments.md#plugins-and-capability-directories)). - `env` cannot set `OPENAI_API_KEY`, which Core reserves ([env](./environments.md#env-and-setup-commands)); the official service accepts it. - A `self_hosted` Session without pending input requests no connection ([activity](./environments.md#activity-and-required-actions)); one unused official Session switched to `requires_action` with `environment_connection` about five minutes after creation, and its deletion then returned 409. +- A hosted Environment emits `ready` once, when its initialization completes, and not again before each later Turn as one official Session did. It also emits `connected` and `disconnected`, which that Session did not. **Files, Skills, Environment files and Artifacts** ([Files and Skills](./source-files.md), [Environment files and Artifacts](./environment-files.md)) @@ -141,7 +142,7 @@ Each item is Core's deliberate or native behavior where the official service beh **Execution and history** -- The stream does not emit Environment `pending` or `ready` events, or every pinned interim tool-output variant. +- The stream does not emit every pinned interim tool-output variant. - Native Item variants beyond those listed under [Turns and Items](./sessions-events.md#turns-and-items) are not projected, and Items cannot be modified. - A function result that cancellation prevents from being applied never appears as an Item. - Pinned Codex can lose command output emitted before its stream subscription. @@ -183,6 +184,7 @@ Each item is Core's deliberate or native behavior where the official service beh - The order of errors when one request has several faults, and error, default and payload-limit parity in general. - A Subagent's function call: Core makes it a required action of the root Turn that runs the child, with `turn_id` set to that Turn, and publishes the child's `function_call` Item once as `agent.session.turn.item.added` with the child Turn ID and a null `output_index`; a result may name either Turn. The Turn is `waiting` and the Session `requires_action` while root output may continue, and the `call_id` equals the `call_id` of the child's `function_call` Item. Claude Code publishes the child's Items when the root Turn settles, after the required action. +- Whether the official service emits Environment `pending` and when: Core emits it when a hosted Environment's initialization starts, and the one official sample showed only `ready`, about 29 s after creation. - Whether Subagent child Turns and pending Environment file writes block Session deletion. - The official order between the pending-input error and an unknown result target. - Whether a Session whose latest Turn failed accepts new input: Core starts a new Turn, and one official sample rejected the input. diff --git a/contracts/agents-api/zh/environments.md b/contracts/agents-api/zh/environments.md index d5a0d4d64..933cffb75 100644 --- a/contracts/agents-api/zh/environments.md +++ b/contracts/agents-api/zh/environments.md @@ -1,7 +1,7 @@ --- title: "Environment 与模板" source: contracts/agents-api/environments.md -source_hash: 15550304b85596e09cbeb4cc6d7253a4bdd64ffd6adc58a539511e0c939f7ad6 +source_hash: fa17eba20ecb905da36dfb1c0ffb8d9a86f49560f0688ddc6b9a3b59009fc4b4 --- Environment 是 Session 的执行资源,包括 Harness 运行所在的机器、工作区以及已完成准备的能力。Session 通过其 `environment` 配置创建 Environment;不存在独立的 create 调用。Environment 模板是 Session 创建时解析的可复用准备配置。本契约涵盖这两类资源、两种放置方式、输入接纳、能力准备、Skills、Plugins 和 MCP 连接来源。 @@ -257,6 +257,7 @@ stateDiagram-v2 - 每个文件、Skill 或 Plugin 传输的暂存预算为两分钟。configure、软件包安装、设置命令和快照最终确定共享整个初始化过程的 30 分钟预算,Core 在每项操作中携带剩余时长,由 Runtime 执行。初始输入仍保留其五分钟接纳期限,因此大型安装应从空闲 Session 开始。 - 正在运行且所有权丧失的初始化,包括跨 Core 重启丧失所有权,会作为未确认而失败;不会重播任何内容。已完成的 Environment 在重连或原生恢复时绝不会重新安装,因此用户后续更改会保留下来。 - 失败对 Session 而言是终止状态,但不会销毁计算资源或文件。 +- `openai_hosted` Environment 在开始初始化的事务中记录 `agent.session.environment.pending`,在完成初始化的事务中记录 `agent.session.environment.ready`,各恰好一次。`self_hosted` Environment 两者都不发出。 初始化失败时记录的事件和 Session 状态由 [Environment 初始化失败](sessions-events.md#environment-initialization-failure)定义。原因只指明步骤及其退出状态: diff --git a/contracts/agents-api/zh/index.md b/contracts/agents-api/zh/index.md index f545637d7..43691403b 100644 --- a/contracts/agents-api/zh/index.md +++ b/contracts/agents-api/zh/index.md @@ -1,7 +1,7 @@ --- title: "OpenAI 兼容性" source: contracts/agents-api/index.md -source_hash: 09fcf64102a376e53b2881621c21647afb7187e3899ef6c4b9f350fa7a2d95fe +source_hash: b6322e1f2733cd1e5b1486488c4341190ce72b3cd29bb4547ef3fc244893ff7c --- Core 实现下方固定版本的 OpenAI Agents API。本台账列出各项资源的覆盖情况、相对于官方服务的所有差异以及已知缺口。 @@ -113,6 +113,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - `openai_hosted` 和模板的 `capability_directories` 必须位于 `/workspace` 内;官方服务也接受 `/etc` 等系统路径([能力目录](environments.md#plugins-and-capability-directories))。 - `env` 不能设置 Core 保留的 `OPENAI_API_KEY`([env](environments.md#env-and-setup-commands));官方服务接受该变量。 - 没有待处理输入的 `self_hosted` Session 不会请求连接([活动状态](environments.md#activity-and-required-actions));一个未使用的官方 Session 在创建约五分钟后转为 `requires_action`,原因为 `environment_connection`,之后删除它返回 409。 +- hosted Environment 只在初始化完成时发出一次 `ready`,不会像一个官方 Session 那样在之后每个 Turn 之前再次发出;它还会发出 `connected` 和 `disconnected`,而该官方 Session 没有。 **Files、Skills、Environment files 和 Artifacts**([Files and Skills](source-files.md)、[Environment files and Artifacts](environment-files.md)) @@ -144,7 +145,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh **执行和历史** -- 流不会发出 Environment 的 `pending` 或 `ready` 事件,也不会覆盖固定版本中的所有临时 tool-output 变体。 +- 流不会覆盖固定版本中的所有临时 tool-output 变体。 - 除 [Turns and Items](sessions-events.md#turns-and-items) 中列出的变体外,其他原生 Item 变体不会被投影,而且 Items 无法修改。 - 如果取消导致函数结果无法应用,该结果将永远不会作为 Item 出现。 - 固定版本的 Codex 可能会丢失在订阅其流之前发出的命令输出。 @@ -186,6 +187,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - 当一个请求存在多项故障时的错误顺序,以及错误处理、默认值和载荷限制的总体一致性。 - Subagent 的函数调用:Core 将其作为运行该子级的根 Turn 的待执行操作,`turn_id` 为该 Turn,并把子级的 `function_call` Item 以 `agent.session.turn.item.added` 发布一次,`turn_id` 为子级 Turn ID,`output_index` 为 null;结果可以指定其中任一 Turn。该 Turn 为 `waiting`、Session 为 `requires_action`,根输出可继续,`call_id` 等于该子级 `function_call` Item 的 `call_id`。Claude Code 在根 Turn 收敛时才发布子级的 Item,晚于该待执行操作。 +- 官方服务是否发出 Environment `pending` 以及何时发出:Core 在 hosted Environment 初始化开始时发出,而仅有的一个官方样本只显示了创建约 29 秒后的 `ready`。 - Subagent 子级 Turns 和待处理的 Environment file 写入是否会阻止 Session 删除。 - 官方服务在待处理输入错误与未知结果目标之间的先后顺序。 - 最新 Turn 失败的 Session 是否接受新输入:Core 会开始新的 Turn,而一个官方样本拒绝了该输入。 diff --git a/services/core/internal/sessions/execution_environment.go b/services/core/internal/sessions/execution_environment.go index 8974f4955..942c08b60 100644 --- a/services/core/internal/sessions/execution_environment.go +++ b/services/core/internal/sessions/execution_environment.go @@ -175,17 +175,33 @@ func (o *ExecutionOperations) advanceInitialization(ctx context.Context, owner E // device. func (o *ExecutionOperations) ClaimEnvironmentInitialization(ctx context.Context, owner EnvironmentInitialization) error { return o.advanceInitialization(ctx, owner, func(ctx context.Context, tx InitializationTx, environment Environment) (bool, error) { - return tx.ClaimInitialization(ctx, environment.ID) + return journalInitialization(ctx, tx, environment, "pending", tx.ClaimInitialization) }) } // CompleteEnvironmentInitialization completes the claimed preparation. func (o *ExecutionOperations) CompleteEnvironmentInitialization(ctx context.Context, owner EnvironmentInitialization) error { return o.advanceInitialization(ctx, owner, func(ctx context.Context, tx InitializationTx, environment Environment) (bool, error) { - return tx.CompleteInitialization(ctx, environment.ID) + return journalInitialization(ctx, tx, environment, "ready", tx.CompleteInitialization) }) } +// journalInitialization applies one initialization transition and, when it +// applied to a hosted Environment, journals the matching +// agent.session.environment. change in the same transaction. Self-hosted +// Environments are prepared by the user and emit neither event. +func journalInitialization(ctx context.Context, tx InitializationTx, environment Environment, status string, transition func(context.Context, string) (bool, error)) (bool, error) { + kind, err := EnvironmentType(environment.Configuration) + if err != nil { + return false, err + } + applied, err := transition(ctx, environment.ID) + if err != nil || !applied || kind != "openai_hosted" { + return applied, err + } + return true, tx.AppendChanges(ctx, EnvironmentStateChange(environment.ID, kind, status)) +} + // FailEnvironmentInitialization records the failure of a preparation that did // not complete and fails the Environment, as FailEnvironment reports it. It // records state and settles work; it never destroys compute or a workspace. diff --git a/services/core/internal/sessions/execution_environment_test.go b/services/core/internal/sessions/execution_environment_test.go index 73461e26b..286673b55 100644 --- a/services/core/internal/sessions/execution_environment_test.go +++ b/services/core/internal/sessions/execution_environment_test.go @@ -163,6 +163,7 @@ func TestInitializationOwnerAndDeviceRules(t *testing.T) { } func TestInitializationTransitionsRunUnderTheListedDevice(t *testing.T) { + var journaled []SessionChange owner := EnvironmentInitialization{TenantID: "tenant", SessionID: "session", EnvironmentID: "environment", DeviceID: "device"} listed := func() (ExecutionDevice, bool, error) { return ExecutionDevice{ID: "device", EnvironmentID: "environment"}, true, nil @@ -176,15 +177,18 @@ func TestInitializationTransitionsRunUnderTheListedDevice(t *testing.T) { want error calls []string }{ - {"claim", fakeTx{loadEnvironment: returns(hostedEnvironment), loadSessionDevice: listed, claimInitialization: returns(true)}, + {"claim", fakeTx{loadEnvironment: returns(hostedEnvironment), loadSessionDevice: listed, claimInitialization: returns(true), appendChanges: collect(&journaled)}, + LockedSession{}, func(o *ExecutionOperations) error { return o.ClaimEnvironmentInitialization(t.Context(), owner) }, + nil, append(checked, "ClaimInitialization environment", "AppendChanges agent.session.environment.pending")}, + {"claim of a self-hosted Environment", fakeTx{loadEnvironment: returns(Environment{ID: "environment", Status: "pending", Configuration: []byte(`{"type":"self_hosted"}`)}), loadSessionDevice: listed, claimInitialization: returns(true)}, LockedSession{}, func(o *ExecutionOperations) error { return o.ClaimEnvironmentInitialization(t.Context(), owner) }, nil, append(checked, "ClaimInitialization environment")}, {"claim that did not apply", fakeTx{loadEnvironment: returns(hostedEnvironment), loadSessionDevice: listed, claimInitialization: returns(false)}, LockedSession{}, func(o *ExecutionOperations) error { return o.ClaimEnvironmentInitialization(t.Context(), owner) }, ErrTurnConflict, append(checked, "ClaimInitialization environment")}, - {"complete", fakeTx{loadEnvironment: returns(hostedEnvironment), loadSessionDevice: listed, completeInitialization: returns(true)}, + {"complete", fakeTx{loadEnvironment: returns(hostedEnvironment), loadSessionDevice: listed, completeInitialization: returns(true), appendChanges: collect(&journaled)}, LockedSession{}, func(o *ExecutionOperations) error { return o.CompleteEnvironmentInitialization(t.Context(), owner) }, - nil, append(checked, "CompleteInitialization environment")}, + nil, append(checked, "CompleteInitialization environment", "AppendChanges agent.session.environment.ready")}, {"device moved", fakeTx{loadEnvironment: returns(hostedEnvironment), loadSessionDevice: loads(ExecutionDevice{ID: "other", EnvironmentID: "environment"}, true)}, LockedSession{}, func(o *ExecutionOperations) error { return o.CompleteEnvironmentInitialization(t.Context(), owner) }, ErrTurnConflict, checked}, diff --git a/services/core/tests/integration/hosted_initialization_failure_public_test.go b/services/core/tests/integration/hosted_initialization_failure_public_test.go index c5805c4ed..06956d80d 100644 --- a/services/core/tests/integration/hosted_initialization_failure_public_test.go +++ b/services/core/tests/integration/hosted_initialization_failure_public_test.go @@ -187,8 +187,8 @@ func TestHostedInitializationFailureRecordsSafeSessionFailure(t *testing.T) { t.Fatal("Session list", page, err) } events, err := sessionAdapter(s).ListSessionEvents(t.Context(), tenant, session.ID, 0) - // Transport may connect while initialization is still running. - if len(events) > 0 && events[0].Event.Type == "agent.session.environment.connected" { + // Initialization starts and transport may connect before the failure. + for len(events) > 0 && (events[0].Event.Type == "agent.session.environment.pending" || events[0].Event.Type == "agent.session.environment.connected") { events = events[1:] } @@ -352,7 +352,7 @@ func TestHostedInitializationFailurePublicHTTP(t *testing.T) { t.Fatal("invalid frame", line) } bodies = append(bodies, data) - if frame["type"] == "agent.session.environment.connected" && len(frames) == 0 && len(names) == 1 { + if (frame["type"] == "agent.session.environment.pending" || frame["type"] == "agent.session.environment.connected") && len(frames) == 0 && len(names) == 1 { names = nil continue } diff --git a/services/core/tests/integration/runtime_initialization_test.go b/services/core/tests/integration/runtime_initialization_test.go index 3095a02c5..3fed7317b 100644 --- a/services/core/tests/integration/runtime_initialization_test.go +++ b/services/core/tests/integration/runtime_initialization_test.go @@ -202,4 +202,17 @@ func TestManagedRuntimePreparationAllOperationsUsePeer(t *testing.T) { if err != nil || initializationState(t, s, allocation.TenantID, allocation.EnvironmentID) != "complete" { t.Fatal("initialization incomplete", allocation, err) } + changes, err := sessionAdapter(s).ListSessionEvents(t.Context(), tenant, session.ID, 0) + if err != nil { + t.Fatal(err) + } + var lifecycle []string + for _, change := range changes { + if change.Event.Type == "agent.session.environment.pending" || change.Event.Type == "agent.session.environment.ready" { + lifecycle = append(lifecycle, change.Event.Type) + } + } + if !reflect.DeepEqual(lifecycle, []string{"agent.session.environment.pending", "agent.session.environment.ready"}) { + t.Fatal("initialization events", lifecycle) + } } From 87ebad0f0eae3b45f65045c731bae34dd108f901 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 14:21:21 +0800 Subject: [PATCH 10/84] Name the control archives as the platform image source (#872) --- docs/maintainers.md | 2 +- docs/zh/maintainers.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/maintainers.md b/docs/maintainers.md index 63ee61bdb..452f9caf6 100644 --- a/docs/maintainers.md +++ b/docs/maintainers.md @@ -144,7 +144,7 @@ Distribution and Runtime archives use `pigz` level 6 with at most four compressi ### Container registry -Version releases and manual `build-` drafts publish `ghcr.io/minimax-ai/openagentcore/:`, where `` is `core`, `web`, `runtime`, `ingress` or `postgres`. Core, Web and ingress indexes contain Linux amd64 and arm64 images; Runtime contains Linux amd64. Platform images use `-` tags and are loaded from the release archives. Existing version tags must match the release images and platform set. The publisher verifies every version index before updating `latest` for a stable release; prereleases and drafts leave `latest` unchanged. `postgres` is the official PostgreSQL index pinned in `deploy/compose/database-image.txt`, copied with all its platforms and its digest; the publisher refuses a registry tag that names another digest. To move PostgreSQL, change that file to a new digest of the same major version, which is the one place the template, the offline bundle and the mirror read. SemVer build metadata uses `_` in place of `+` in container tags; version strings are limited to 128 characters. After verifying the images, the publisher uploads the release's `compose.yaml` and checksum list. Compose pins Core, Web, ingress and PostgreSQL by their release index digests, and initialization checks its build revision against the Compose revision. +Version releases and manual `build-` drafts publish `ghcr.io/minimax-ai/openagentcore/:`, where `` is `core`, `web`, `runtime`, `ingress` or `postgres`. Core, Web and ingress indexes contain Linux amd64 and arm64 images; Runtime contains Linux amd64. Platform images use `-` tags and are loaded from the control archives. Existing version tags must match the release images and platform set. The publisher verifies every version index before updating `latest` for a stable release; prereleases and drafts leave `latest` unchanged. `postgres` is the official PostgreSQL index pinned in `deploy/compose/database-image.txt`, copied with all its platforms and its digest; the publisher refuses a registry tag that names another digest. To move PostgreSQL, change that file to a new digest of the same major version, which is the one place the template, the offline bundle and the mirror read. SemVer build metadata uses `_` in place of `+` in container tags; version strings are limited to 128 characters. After verifying the images, the publisher uploads the release's `compose.yaml` and checksum list. Compose pins Core, Web, ingress and PostgreSQL by their release index digests, and initialization checks its build revision against the Compose revision. The combined build/publication job uses `GITHUB_TOKEN` with `packages: write`. On the first publication, GitHub creates each container package as private: a package administrator must change all five packages (`core`, `web`, `runtime`, `ingress` and `postgres`) to **Public** in their package settings before users can pull anonymously. See [GitHub container visibility](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry). Verify an unauthenticated pull after changing visibility. Repository visibility alone does not make a new container package public. diff --git a/docs/zh/maintainers.md b/docs/zh/maintainers.md index 32e882a5a..1f363ebc0 100644 --- a/docs/zh/maintainers.md +++ b/docs/zh/maintainers.md @@ -1,7 +1,7 @@ --- title: "构建并发布 OpenAgentCore" source: docs/maintainers.md -source_hash: 0b605c6f5df332a2eb9831d3026b4bcde4ae6d7a2e2cb7bd8b3ce3a21704a7db +source_hash: abeea265e04f051163414749fd3e3a9be7b8680d17bec4431038533f9b2d2a3c --- 本指南面向负责构建和发布 OpenAgentCore 的维护者。要安装 Core 和 Web,请按 [安装 Core 和 Web](getting-started/install.md) 操作。安装程序代码遵循的规则见 [部署](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/deploy/README.md) 和 [节点安装程序](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/deploy/node/README.md);必需检查见 [CONTRIBUTING](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/CONTRIBUTING.md#required-checks)。 @@ -146,7 +146,7 @@ flowchart LR ### 容器注册表 {#container-registry} -版本发布和手动 `build-` 草稿使用 `ghcr.io/minimax-ai/openagentcore/:`,其中 `` 为 `core`、`web`、`runtime`、`ingress` 或 `postgres`。Core、Web 和 ingress 索引包含 Linux amd64 和 arm64 镜像,Runtime 包含 Linux amd64。各平台镜像使用 `-` 标签,从发行归档加载。已有版本标签必须与发行镜像及平台集合一致。发布器校验全部版本索引后,才为稳定版更新 `latest`;预发布版和草稿保持 `latest` 不变。`postgres` 是固定在 `deploy/compose/database-image.txt` 中的官方 PostgreSQL 索引,连同全部平台和原摘要一并复制;注册表中的标签若指向其他摘要,发布器会拒绝。要升级 PostgreSQL,请把该文件改为同一主版本的新摘要,模板、离线包和镜像复制都读取这一处。容器标签中的 SemVer 构建元数据用 `_` 替换 `+`,版本字符串上限为 128 个字符。镜像校验后,发布器上传该版本的 `compose.yaml` 和校验和清单。Compose 用对应发行版的索引摘要固定 Core、Web、ingress 和 PostgreSQL,初始化时检查其构建版本与 Compose 版本一致。 +版本发布和手动 `build-` 草稿使用 `ghcr.io/minimax-ai/openagentcore/:`,其中 `` 为 `core`、`web`、`runtime`、`ingress` 或 `postgres`。Core、Web 和 ingress 索引包含 Linux amd64 和 arm64 镜像,Runtime 包含 Linux amd64。各平台镜像使用 `-` 标签,从控制归档加载。已有版本标签必须与发行镜像及平台集合一致。发布器校验全部版本索引后,才为稳定版更新 `latest`;预发布版和草稿保持 `latest` 不变。`postgres` 是固定在 `deploy/compose/database-image.txt` 中的官方 PostgreSQL 索引,连同全部平台和原摘要一并复制;注册表中的标签若指向其他摘要,发布器会拒绝。要升级 PostgreSQL,请把该文件改为同一主版本的新摘要,模板、离线包和镜像复制都读取这一处。容器标签中的 SemVer 构建元数据用 `_` 替换 `+`,版本字符串上限为 128 个字符。镜像校验后,发布器上传该版本的 `compose.yaml` 和校验和清单。Compose 用对应发行版的索引摘要固定 Core、Web、ingress 和 PostgreSQL,初始化时检查其构建版本与 Compose 版本一致。 合并的构建/发布作业使用具有 `packages: write` 权限的 `GITHUB_TOKEN`。首次发布时,GitHub 会将每个容器软件包创建为私有:软件包管理员必须先在各自的软件包设置中将全部五个软件包(`core`、`web`、`runtime`、`ingress` 和 `postgres`)改为 **Public**,用户才能匿名拉取。请参阅 [GitHub container visibility](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)。更改可见性后,请验证未认证拉取。仅更改仓库可见性并不会使新的容器软件包变为公开。 From 170a4983db30540425bf455a2558b3d53fdda235 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 14:29:40 +0800 Subject: [PATCH 11/84] Report initialization step timing (#871) * Report initialization step timing * Address review of initialization step timing --- .../internal/dispatch/runtime_preparation.go | 2 + .../dispatch/runtime_preparation_test.go | 22 +++++ apps/web/e2e/fixture-console.mjs | 2 +- .../web/src/features/sessions/SessionPage.tsx | 3 +- .../sessions/session-diagnostics.test.tsx | 17 +++- .../features/sessions/session-diagnostics.tsx | 14 ++- apps/web/src/i18n/locales/en/diagnostics.ts | 15 +++- .../web/src/i18n/locales/zh-CN/diagnostics.ts | 15 +++- apps/web/src/lib/diagnostic-failure.ts | 3 + contracts/agents-api/core-errors.md | 2 +- contracts/agents-api/core.openapi.yaml | 29 +++++++ contracts/agents-api/session-diagnostics.md | 17 +++- contracts/agents-api/zh/core-errors.md | 4 +- .../agents-api/zh/session-diagnostics.md | 19 ++++- docs/runtime-protocol.md | 2 +- docs/zh/runtime-protocol.md | 4 +- internal/agentdaemon/proto/runtime_prepare.go | 6 ++ .../agentdaemon/proto/runtime_prepare_test.go | 16 ++++ internal/agentdaemon/proto/version.go | 2 +- .../agents-client/src/generated/core-api.ts | 11 ++- packages/agents-client/src/index.ts | 2 +- .../src/session-diagnostics.test.ts | 33 ++++--- .../agents-client/src/session-diagnostics.ts | 24 ++++-- scripts/ci_plan.py | 1 + .../core/internal/api/session_diagnostics.go | 19 ++++- .../internal/api/session_diagnostics_test.go | 26 ++++-- .../db/queries/environment_initialization.sql | 4 + .../db/sqlc/environment_initialization.sql.go | 15 ++++ .../core/internal/db/sqlc/environments.sql.go | 6 +- services/core/internal/db/sqlc/models.go | 17 ++-- .../core/internal/deployment/allocations.go | 2 +- .../execution/runtime_capabilities_test.go | 6 +- .../execution/runtime_initialization.go | 40 +++++++-- .../core/internal/execution/runtime_setup.go | 74 ++++++++++++++-- .../internal/execution/runtime_setup_test.go | 60 +++++++++++-- .../sessionpg/execution_environment.go | 16 ++++ .../postgres/sessionpg/session_reads.go | 3 + .../sessions/environment_termination.go | 4 + .../sessions/execution_environment.go | 11 +++ .../sessions/execution_environment_test.go | 4 + .../core/internal/sessions/provisioning.go | 85 +++++++++++++++++-- .../internal/sessions/provisioning_test.go | 25 +++++- services/core/internal/sessions/session.go | 3 + .../testdata/provisioning-categories.json | 10 +++ ...00009_environment_initialization_steps.sql | 4 + .../integration/session_diagnostics_test.go | 33 +++++++ 46 files changed, 645 insertions(+), 87 deletions(-) create mode 100644 services/core/internal/sessions/testdata/provisioning-categories.json create mode 100644 services/core/migrations/000009_environment_initialization_steps.sql diff --git a/apps/daemon/internal/dispatch/runtime_preparation.go b/apps/daemon/internal/dispatch/runtime_preparation.go index 926ddc5f9..a50d1d3b5 100644 --- a/apps/daemon/internal/dispatch/runtime_preparation.go +++ b/apps/daemon/internal/dispatch/runtime_preparation.go @@ -151,7 +151,9 @@ func (r *Router) runRuntimePreparationTransfer(ctx context.Context, u *runtimePr r.mu.Unlock() result := rejectedRuntimePreparation("invalid_request") if admitted { + started := time.Now() result = runtimePreparationResult(apply(ctx, u.request, data), u.request.SizeBytes) + result.DurationMS = time.Since(started).Milliseconds() } // Release the potentially large body before waiting on transport delivery. data = nil diff --git a/apps/daemon/internal/dispatch/runtime_preparation_test.go b/apps/daemon/internal/dispatch/runtime_preparation_test.go index cdd948ae6..6a6a8069a 100644 --- a/apps/daemon/internal/dispatch/runtime_preparation_test.go +++ b/apps/daemon/internal/dispatch/runtime_preparation_test.go @@ -441,3 +441,25 @@ func TestRuntimePreparationHonorsBeginBudgetDuringStaging(t *testing.T) { shutdownCapabilitiesRouter(t, r) }) } + +func TestRuntimePreparationReportsApplyDuration(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + r, sender, environment, session := capabilitiesTestRouter(t) + _, cancel := context.WithCancel(t.Context()) + id := uuid.NewString() + request := proto.RuntimePreparePayload{BudgetMS: 300000, Step: "begin", Action: "finalize", EnvironmentID: environment, SessionID: session, Sources: &proto.CapabilitySources{}} + owner := &runtimePreparationTransfer{envelope: capabilityEnvelope(t, id, request), request: request, ready: make(chan struct{}), cancel: cancel, finished: true, apply: true} + close(owner.ready) + r.runtimePreparation = owner + r.shutdownWG.Add(1) + go r.runRuntimePreparationTransfer(t.Context(), owner, func(context.Context, proto.RuntimePreparePayload, []byte) error { + time.Sleep(1500 * time.Millisecond) + return nil + }) + synctest.Wait() + got := capabilitiesReceipt(t, sender, id, "completed") + if got.DurationMS != 1500 || !proto.ValidRuntimePrepareResult(got, "completed", 0, 0) { + t.Fatalf("apply duration not reported: %+v", got) + } + }) +} diff --git a/apps/web/e2e/fixture-console.mjs b/apps/web/e2e/fixture-console.mjs index a6c92d720..79f5c5d46 100644 --- a/apps/web/e2e/fixture-console.mjs +++ b/apps/web/e2e/fixture-console.mjs @@ -293,7 +293,7 @@ function adminRead(response, path, url) { if (m[2] === "diagnostics") { const failedTurn = (state.turns.get(session.id) ?? []).findLast((turn) => turn.status === "failed"); return send(response, 200, { object: "core.session_diagnostics", session_id: session.id, status: session.status, - failure: session.status === "failed" ? { source: failedTurn ? "turn" : "environment_input", ...(failedTurn ? { turn_id: failedTurn.id } : {}), code: "internal_error", params: {}, failed_at: null } : null }); + failure: session.status === "failed" ? { source: failedTurn ? "turn" : "environment_input", ...(failedTurn ? { turn_id: failedTurn.id } : {}), code: "internal_error", params: {}, failed_at: null } : null, initialization_steps: [] }); } const diagnostics = m[2].match(/^turns\/([^/]+)\/diagnostics$/); if (diagnostics) { diff --git a/apps/web/src/features/sessions/SessionPage.tsx b/apps/web/src/features/sessions/SessionPage.tsx index 4187e3ddb..c72c20f71 100644 --- a/apps/web/src/features/sessions/SessionPage.tsx +++ b/apps/web/src/features/sessions/SessionPage.tsx @@ -16,7 +16,7 @@ import { sessionTitle } from "../../lib/session-title"; import { forgetDeleted } from "../resources/detail-queries"; import { ExecutorCredentialsSection } from "./ExecutorCredentialsSection"; import { SessionDeleteDialog, type SessionDeleteTarget } from "./SessionDeleteDialog"; -import { DiagnosticScope, SessionFailureDetails } from "./session-diagnostics"; +import { DiagnosticScope, InitializationSteps, SessionFailureDetails } from "./session-diagnostics"; import { sessionKey } from "./session-queries"; import { isSessionActive, turnAnchorId } from "./session-history"; import { environmentKind, isDeletable } from "./session-log"; @@ -150,6 +150,7 @@ export function SessionPage() { {session.vault_ids.length ? session.vault_ids.map((id) => ) : MISSING}
+ {waiting.length ?
{t("detail.waitingFor")}
{waiting.map((entry, index) => {entry})}{session.required_actions.some((action) => action.type === "function_call") ? {t("detail.applicationAction")} : null}
: null} {metadata.length ? (
diff --git a/apps/web/src/features/sessions/session-diagnostics.test.tsx b/apps/web/src/features/sessions/session-diagnostics.test.tsx index 1f179df34..dfcd7140e 100644 --- a/apps/web/src/features/sessions/session-diagnostics.test.tsx +++ b/apps/web/src/features/sessions/session-diagnostics.test.tsx @@ -5,14 +5,14 @@ import { afterEach, describe, expect, it } from "vitest"; import i18n from "../../i18n"; import { diagnosticFailure } from "../../lib/diagnostic-failure"; -import { DiagnosticScope, SessionFailure, SessionFailureDetails, TurnFailure, sessionDiagnosticsQuery, turnDiagnosticsQuery } from "./session-diagnostics"; +import { DiagnosticScope, InitializationSteps, SessionFailure, SessionFailureDetails, TurnFailure, sessionDiagnosticsQuery, turnDiagnosticsQuery } from "./session-diagnostics"; import { ItemReceiptTiming } from "./trace/ItemReceiptTiming"; const scope = { projectId: "project", sessionId: "session" }; const session = { id: "session", status: "failed", last_active_at: 20 } as AgentSession; const turn = { id: "turn", session_id: "session", status: "failed", completed_at: 20, error: { code: "internal_error", message: "PRIVATE_NATIVE_SENTINEL" } } as AgentTurn; const failure: DiagnosticFailure = { code: "authentication_error", params: {}, failed_at: null }; -const sessionData: SessionDiagnostics = { object: "core.session_diagnostics", session_id: "session", status: "failed", failure: { ...failure, source: "turn", turn_id: "turn" } }; +const sessionData: SessionDiagnostics = { object: "core.session_diagnostics", session_id: "session", status: "failed", failure: { ...failure, source: "turn", turn_id: "turn" }, initialization_steps: [{ step: "npm", index: null, duration_ms: 4100 }, { step: "setup", index: 1, duration_ms: 5200 }] }; const turnData: TurnDiagnostics = { object: "core.turn_diagnostics", session_id: "session", turn_id: "turn", status: "failed", failure, items: [], items_truncated: false }; afterEach(() => { void i18n.changeLanguage("en"); }); @@ -38,6 +38,17 @@ describe("Core diagnostics in the console", () => { expect(render("turn", turnData)).not.toContain("PRIVATE_NATIVE_SENTINEL"); }); + it("lists the initialization operations that ran with their durations and the failure category", () => { + const client = new QueryClient(); + client.setQueryData(sessionDiagnosticsQuery(scope.projectId, session).queryKey, sessionData); + const html = renderToStaticMarkup(); + client.clear(); + expect(html).toContain("npm dependencies: 4.1 s"); + expect(html).toContain("setup 2: 5.2 s"); + const t = i18n.getFixedT("en", "diagnostics"); + expect(diagnosticFailure({ code: "environment_provisioning_failed", params: { step: null, index: null, exit_code: null, category: "timeout" }, failed_at: null }, t)).toContain("The preparation timed out."); + }); + it("gives the Session page the reason, then its next step, in one block", () => { expect(render("session", sessionData)).toContain('

The model provider rejected authentication.

Check the API key'); }); @@ -58,7 +69,7 @@ describe("Core diagnostics in the console", () => { it("renders only typed provisioning metadata and does not guess a timeout", () => { const t = i18n.getFixedT("en", "diagnostics"); - const text = diagnosticFailure({ code: "environment_provisioning_failed", params: { step: "setup", index: 0, exit_code: 7 }, failed_at: null }, t); + const text = diagnosticFailure({ code: "environment_provisioning_failed", params: { step: "setup", index: 0, exit_code: 7, category: null }, failed_at: null }, t); expect(text).toContain("Setup command 1"); expect(text).toContain("Exit code 7"); expect(diagnosticFailure({ code: "harness_error", params: {}, failed_at: null }, t)).not.toContain("timed out"); diff --git a/apps/web/src/features/sessions/session-diagnostics.tsx b/apps/web/src/features/sessions/session-diagnostics.tsx index c2bc01e63..d543ef3cb 100644 --- a/apps/web/src/features/sessions/session-diagnostics.tsx +++ b/apps/web/src/features/sessions/session-diagnostics.tsx @@ -4,6 +4,7 @@ import { createContext, useContext } from "react"; import { useTranslation } from "react-i18next"; import { HelpTip } from "../../components/console-ui"; +import { formatDuration } from "../../lib/format"; import { diagnosticFailure, diagnosticNext, diagnosticReason } from "../../lib/diagnostic-failure"; import { admin } from "../../lib/projects"; import { sessionKey } from "./session-queries"; @@ -13,7 +14,7 @@ export const DiagnosticScope = createContext(null); export function sessionDiagnosticsQuery(projectId: string, session: AgentSession) { return queryOptions({ - queryKey: [...sessionKey(projectId, session.id), "diagnostics", "session", session.status, session.last_active_at], + queryKey: [...sessionKey(projectId, session.id), "diagnostics", "session", session.status], queryFn: ({ signal }) => admin.retrieveSessionDiagnostics(projectId, session.id, { signal }), enabled: session.status === "failed", retry: false, @@ -39,6 +40,17 @@ export function DiagnosticsUnavailable({ pending, retry }: { pending: boolean; r ; } +/** The facts row of the operations the Environment's initialization ran, in order. */ +export function InitializationSteps({ projectId, session }: { projectId: string; session: AgentSession }) { + const { t } = useTranslation("diagnostics"); + const query = useQuery({ ...sessionDiagnosticsQuery(projectId, session), enabled: true }); + const steps = query.isError ? [] : query.data?.initialization_steps ?? []; + if (!steps.length) return null; + return

{t("initializationTitle")}
+ {steps.map((step, index) => {t(`step.${step.step}`)}{step.index === null ? "" : ` ${step.index + 1}`}: {formatDuration(step.duration_ms / 1000)})} +
; +} + function useSessionFailure(projectId: string, session: AgentSession) { const query = useQuery(sessionDiagnosticsQuery(projectId, session)); return { query, failure: !query.isError && query.data?.status === session.status ? query.data.failure : null }; diff --git a/apps/web/src/i18n/locales/en/diagnostics.ts b/apps/web/src/i18n/locales/en/diagnostics.ts index 32cdfe5b5..257fc576e 100644 --- a/apps/web/src/i18n/locales/en/diagnostics.ts +++ b/apps/web/src/i18n/locales/en/diagnostics.ts @@ -1,3 +1,5 @@ +import type { ProvisioningCategory } from "@oac/agents-client"; + export const diagnostics = { providerUnknown: "Not recorded yet", providerStale: "Observation unconfirmed", @@ -61,7 +63,18 @@ export const diagnostics = { exitCode: "Exit code {{code}}.", httpStatus: "HTTP {{status}}.", unreachableHost: "Then check that the URL's host resolves and is reachable from the Session's sandbox, or from the host of a self-hosted Session.", - step: { setup: "setup", python: "Python dependencies", npm: "npm dependencies", file: "file preparation", skill: "Skill preparation", harness: "Harness preparation" }, + step: { setup: "setup", python: "Python dependencies", npm: "npm dependencies", file: "file preparation", skill: "Skill preparation", harness: "Harness preparation", plugin: "Plugin preparation", configure: "environment configuration", finalize: "finalization" }, + category: { + timeout: "The preparation timed out.", + runtime_disconnected: "The Runtime disconnected.", + unconfirmed: "The Runtime did not confirm the result.", + rejected: "The Runtime rejected the operation.", + operation_failed: "The Runtime reported a failed operation.", + core_error: "Core could not read, validate or record the initialization state.", + core_restart: "Core lost ownership of the initialization.", + compute_released: "The sandbox was released or never created.", + } satisfies Record, + initializationTitle: "Initialization", unavailable: "Failure details unavailable", unavailableHelp: "The diagnostics read failed or no longer matches this status. Refresh to check again.", checking: "Checking failure details", diff --git a/apps/web/src/i18n/locales/zh-CN/diagnostics.ts b/apps/web/src/i18n/locales/zh-CN/diagnostics.ts index 8df62ea55..8bf3309dc 100644 --- a/apps/web/src/i18n/locales/zh-CN/diagnostics.ts +++ b/apps/web/src/i18n/locales/zh-CN/diagnostics.ts @@ -1,3 +1,5 @@ +import type { ProvisioningCategory } from "@oac/agents-client"; + export const diagnostics = { providerUnknown: "还没有记录", providerStale: "记录尚未确认", @@ -61,7 +63,18 @@ export const diagnostics = { exitCode: "退出码 {{code}}。", httpStatus: "HTTP {{status}}。", unreachableHost: "再确认 Session 的沙箱(自托管 Session 则为其主机)能解析并访问该 URL 的主机。", - step: { setup: "设置", python: "Python 依赖", npm: "npm 依赖", file: "文件准备", skill: "Skill 准备", harness: "Harness 准备" }, + step: { setup: "设置", python: "Python 依赖", npm: "npm 依赖", file: "文件准备", skill: "Skill 准备", harness: "Harness 准备", plugin: "Plugin 准备", configure: "环境配置", finalize: "收尾" }, + category: { + timeout: "准备超时。", + runtime_disconnected: "Runtime 已断开连接。", + unconfirmed: "Runtime 未确认结果。", + rejected: "Runtime 拒绝了该操作。", + operation_failed: "Runtime 报告操作失败。", + core_error: "Core 无法读取、校验或记录初始化状态。", + core_restart: "Core 失去了初始化的所有权。", + compute_released: "沙箱已被释放或从未创建。", + } satisfies Record, + initializationTitle: "初始化", unavailable: "失败详情不可用", unavailableHelp: "诊断读取失败或与当前状态不一致,请刷新后重试。", checking: "正在读取失败详情", diff --git a/apps/web/src/lib/diagnostic-failure.ts b/apps/web/src/lib/diagnostic-failure.ts index 3df058ab7..336c164e6 100644 --- a/apps/web/src/lib/diagnostic-failure.ts +++ b/apps/web/src/lib/diagnostic-failure.ts @@ -15,6 +15,9 @@ export function diagnosticReason(failure: DiagnosticFailure, t: TFunction<"diagn if (failure.params.index !== null) message += gap + t("setupIndex", { number: failure.params.index + 1 }); if (failure.params.exit_code !== null) message += gap + t("exitCode", { code: failure.params.exit_code }); } + if (failure.code === "environment_provisioning_failed" && "category" in failure.params && failure.params.category) { + message += gap + t(`category.${failure.params.category}`); + } const status = connectionStatus(failure); if (status !== null) message += gap + t("httpStatus", { status }); return message; diff --git a/contracts/agents-api/core-errors.md b/contracts/agents-api/core-errors.md index 430cefc5a..297a2a711 100644 --- a/contracts/agents-api/core-errors.md +++ b/contracts/agents-api/core-errors.md @@ -134,7 +134,7 @@ The [Session diagnostics](./session-diagnostics.md) routes return these categori | `internal_error` | Unknown or malformed outcome; no raw value is returned | | `environment_connection_timeout` | Initial input connection deadline expired | | `environment_unavailable` | Environment unavailable for initial input | -| `environment_provisioning_failed` | Hosted provisioning failure; params contain nullable `step`, `index`, `exit_code` from a sanitized receipt | +| `environment_provisioning_failed` | Hosted provisioning failure; params contain nullable `step`, `index`, `exit_code` from a sanitized receipt, and `category` for a failure without a confirmed step | A database failure is an error, never an empty or healthy snapshot. Provisioning reasons and native messages are never parsed for categories or parameters. diff --git a/contracts/agents-api/core.openapi.yaml b/contracts/agents-api/core.openapi.yaml index a0448560b..7c1457196 100644 --- a/contracts/agents-api/core.openapi.yaml +++ b/contracts/agents-api/core.openapi.yaml @@ -490,6 +490,29 @@ definitions: - object - updated_at type: object + api.InitializationStepTiming: + properties: + duration_ms: + type: integer + index: + type: integer + x-nullable: true + step: + enum: + - file + - skill + - plugin + - configure + - npm + - python + - setup + - finalize + type: string + required: + - duration_ms + - index + - step + type: object api.Installation: properties: address_bindings: @@ -855,6 +878,11 @@ definitions: allOf: - $ref: '#/definitions/api.SessionDiagnosticFailure' x-nullable: true + initialization_steps: + description: InitializationSteps lists the operations the Environment's initialization ran, in order. + items: + $ref: '#/definitions/api.InitializationStepTiming' + type: array object: enum: - core.session_diagnostics @@ -870,6 +898,7 @@ definitions: type: string required: - failure + - initialization_steps - object - session_id - status diff --git a/contracts/agents-api/session-diagnostics.md b/contracts/agents-api/session-diagnostics.md index a8b06aa21..44853d9ec 100644 --- a/contracts/agents-api/session-diagnostics.md +++ b/contracts/agents-api/session-diagnostics.md @@ -13,7 +13,7 @@ Missing, malformed, foreign and deleted resources follow the Session and Turn no ## Session snapshot -The object is `core.session_diagnostics`, with `session_id`, the official Session `status`, and nullable `failure`. Each Session or Turn read uses one repeatable-read database snapshot and the public status projection, within a five-second budget that an earlier caller deadline shortens. The transaction is closed after the read, including on cancellation. `failure` is null unless the projection says `failed`. Its fields are: +The object is `core.session_diagnostics`, with `session_id`, the official Session `status`, nullable `failure` and `initialization_steps`. Each Session or Turn read uses one repeatable-read database snapshot and the public status projection, within a five-second budget that an earlier caller deadline shortens. The transaction is closed after the read, including on cancellation. `failure` is null unless the projection says `failed`. Its fields are: | Field | Value | | --- | --- | @@ -27,6 +27,21 @@ A hosted provisioning failure takes precedence over input activity, and input ac Provisioning parameters come from the confirmed structured receipt, persisted in the failure transaction that settles the Environment and its input and records the events. `step` is `setup`, `python`, `npm`, `file`, `skill`, `harness` or null. `index` is a nonnegative JSON-safe integer for setup only, otherwise null. `exit_code` is 1 to 255 for script steps, otherwise null. Details that were not recorded remain null. These private fields do not change the public failure reason or SSE. +`category` is set only when `step` is null, for a failure whose public reason is the generic `initialization did not complete`, and is otherwise null: + +| `category` | Cause | +| --- | --- | +| `timeout` | The initialization budget or a transfer budget expired | +| `runtime_disconnected` | The Runtime connection closed, changed or was not registered | +| `unconfirmed` | An operation's effect is unknown, or its receipt is missing or invalid | +| `rejected` | The Runtime refused an operation before applying it | +| `operation_failed` | The Runtime confirmed a failed operation that has no public step label, such as a Plugin or snapshot finalization | +| `core_error` | Core failed to read, validate or record initialization state | +| `core_restart` | Core lost ownership of the initialization, by restart or lease loss | +| `compute_released` | The sandbox was released or never created before initialization completed; never set for an Environment whose initialization completed | + +`initialization_steps` lists the operations the Environment's initialization ran, in order, from the same snapshot and for any Session status. Each entry has `step` (`file`, `skill`, `plugin`, `configure`, `npm`, `python`, `setup` or `finalize`), `index` (the setup command position for `setup`, otherwise null) and `duration_ms`, the Runtime-measured application time from the [Core–Runtime protocol](../../docs/runtime-protocol.md). Only operations whose result the Runtime reported with a `completed` or `failed` outcome appear, so a preparation-cache hit lists only `finalize`, and an unconfirmed operation is absent. Core also writes one `Environment initialization step` log line per entry with the Session, Environment, `step`, `index` and `duration_ms`. Core stores the list when the initialization ends, successfully or not, and logs each step as it finishes. The list is empty before any operation ran. + ## Turn snapshot and Item receipt timing The object is `core.turn_diagnostics`, with `session_id`, `turn_id`, the official root Turn `status`, nullable `failure`, `items` and `items_truncated`. A Turn failure has `code`, `params` and nullable `failed_at`, without a source or Turn ID. Only failed Turns have failure details; cancelled and completed Turns never inherit a classification from a private outcome. diff --git a/contracts/agents-api/zh/core-errors.md b/contracts/agents-api/zh/core-errors.md index a09140a3e..63260327f 100644 --- a/contracts/agents-api/zh/core-errors.md +++ b/contracts/agents-api/zh/core-errors.md @@ -1,7 +1,7 @@ --- title: "Core 管理错误" source: contracts/agents-api/core-errors.md -source_hash: b2a6cd40a67bbe58fc78efa068a8ad0cf23cf62ad02e3c1456323fa66e9bb6ef +source_hash: f2c2a927b8faad9c2834ae4d1195940195df5fc617c8395a027f0d21dfb5ea1e --- `/core/v1` 上的错误使用此封装结构。`message` 是安全的英文文本;`code` 和 `param` 可以为 null。客户端依据稳定的 `code` 和可选的 `param` 进行处理,对未知代码显示 `message`,绝不解析消息,也绝不自动重试被拒绝的写操作。 @@ -136,7 +136,7 @@ Web 的控制台服务器在 `/core` 路径上发生自身故障时使用此封 | `internal_error` | 结果未知或格式错误;不返回原始值 | | `environment_connection_timeout` | 初始输入连接截止时间已过 | | `environment_unavailable` | 初始输入所需 Environment 不可用 | -| `environment_provisioning_failed` | 托管预置失败;params 包含来自已清理回执的可空 `step`、`index`、`exit_code` | +| `environment_provisioning_failed` | 托管预置失败;params 包含来自已清理回执的可空 `step`、`index`、`exit_code`,以及用于没有已确认步骤的失败的 `category` | 数据库故障属于错误,绝不会产生空快照或健康快照。绝不会解析预置原因或原生消息以确定类别或参数。 diff --git a/contracts/agents-api/zh/session-diagnostics.md b/contracts/agents-api/zh/session-diagnostics.md index d81427fcc..10f3a336b 100644 --- a/contracts/agents-api/zh/session-diagnostics.md +++ b/contracts/agents-api/zh/session-diagnostics.md @@ -1,7 +1,7 @@ --- title: "Session 诊断" source: contracts/agents-api/session-diagnostics.md -source_hash: fe7192fda8191ceca39aa19bed83f37f79b381638a84ca931b51e3d671e4251b +source_hash: d2159eddd1995bac506cb753a243b9ac063aba0f87c1854e2f97e885f9bb624f --- 管理员通过两个需要 Core 密钥的路由读取 Session 或 Turn 失败的原因,它们报告失败类别和 Item 接收时间。 @@ -15,7 +15,7 @@ source_hash: fe7192fda8191ceca39aa19bed83f37f79b381638a84ca931b51e3d671e4251b ## Session 快照 {#session-snapshot} -对象为 `core.session_diagnostics`,包含 `session_id`、官方 Session `status` 和可空的 `failure`。每次 Session 或 Turn 读取使用一个可重复读数据库快照和公开状态投影,时间预算为五秒,调用方更早的截止时间会缩短该预算。读取后关闭事务,取消时也一样。除非投影为 `failed`,否则 `failure` 为 null。其字段为: +对象为 `core.session_diagnostics`,包含 `session_id`、官方 Session `status`、可空的 `failure` 和 `initialization_steps`。每次 Session 或 Turn 读取使用一个可重复读数据库快照和公开状态投影,时间预算为五秒,调用方更早的截止时间会缩短该预算。读取后关闭事务,取消时也一样。除非投影为 `failed`,否则 `failure` 为 null。其字段为: | 字段 | 值 | | --- | --- | @@ -29,6 +29,21 @@ source_hash: fe7192fda8191ceca39aa19bed83f37f79b381638a84ca931b51e3d671e4251b 配置参数来自已确认的结构化回执,在结算 Environment 及其输入并记录事件的失败事务中持久化。`step` 为 `setup`、`python`、`npm`、`file`、`skill`、`harness` 或 null。`index` 仅对 setup 为 JSON 安全的非负整数,其他情况为 null。`exit_code` 对脚本步骤为 1 至 255,其他情况为 null。未记录的详情保持 null。这些私有字段不会改变公开失败原因或 SSE。 +`category` 仅在 `step` 为 null 时设置,对应公开原因为通用的 `initialization did not complete` 的失败,其他情况为 null: + +| `category` | 原因 | +| --- | --- | +| `timeout` | 初始化预算或传输预算到期 | +| `runtime_disconnected` | Runtime 连接关闭、变更或未注册 | +| `unconfirmed` | 某个操作的效果未知,或其回执缺失或无效 | +| `rejected` | Runtime 在应用前拒绝了某个操作 | +| `operation_failed` | Runtime 确认某个没有公开步骤标签的操作失败,例如 Plugin 或快照终结 | +| `core_error` | Core 无法读取、校验或记录初始化状态 | +| `core_restart` | Core 失去了初始化的所有权,原因是重启或租约丢失 | +| `compute_released` | 沙箱在初始化完成前已被释放或从未创建;初始化已完成的 Environment 不会设置此值 | + +`initialization_steps` 按顺序列出该 Environment 的初始化运行过的操作,来自同一快照,适用于任何 Session 状态。每项包含 `step`(`file`、`skill`、`plugin`、`configure`、`npm`、`python`、`setup` 或 `finalize`)、`index`(`setup` 为设置命令位置,其他为 null)和 `duration_ms`,即 [Core–Runtime 协议](../../../docs/zh/runtime-protocol.md)中 Runtime 测得的应用时间。仅 Runtime 以 `completed` 或 `failed` 结果报告的操作会出现,因此命中准备缓存时只列出 `finalize`,未确认的操作不会出现。Core 还会为每项写一条 `Environment initialization step` 日志,包含 Session、Environment、`step`、`index` 和 `duration_ms`。Core 在初始化结束时(无论成败)存储该列表,并在每一步完成时记录日志。在任何操作运行之前列表为空。 + ## Turn 快照与 Item 回执时间 {#turn-snapshot-and-item-receipt-timing} 对象为 `core.turn_diagnostics`,包含 `session_id`、`turn_id`、官方根 Turn `status`、可空的 `failure`、`items` 和 `items_truncated`。Turn 失败包含 `code`、`params` 和可空的 `failed_at`,不包含来源或 Turn ID。只有失败的 Turn 才有失败详情;已取消或已完成的 Turn 不会继承私有结果中的分类。 diff --git a/docs/runtime-protocol.md b/docs/runtime-protocol.md index 387dcd763..435ee21a3 100644 --- a/docs/runtime-protocol.md +++ b/docs/runtime-protocol.md @@ -145,7 +145,7 @@ sequenceDiagram R-->>C: runtime_prepare_result completed ``` -Initialization and finalization have typed headers without file data. Every `begin` carries `budget_ms`, the remaining Core-owned initialization budget; chunks and commits omit it. The Runtime enforces that relative budget from receipt of `begin`, and Core waits no longer than its original operation deadline. The `begin`–`commit` staging phase has its own limit; applying a committed operation and waiting for `completed` use the remaining initialization budget, not the staging limit. Expiry before application rejects the transfer; expiry during application reports `unknown` after local mutations stop and never authorizes replay. Validate the expected outcome, offset, size and finite error code with the shared validator. One transfer is allowed per connection. A chunk receipt confirms staged bytes, not installation; a completed commit confirms that operation, not that a later Turn ran. +Initialization and finalization have typed headers without file data. Every `begin` carries `budget_ms`, the remaining Core-owned initialization budget; chunks and commits omit it. The Runtime enforces that relative budget from receipt of `begin`, and Core waits no longer than its original operation deadline. The `begin`–`commit` staging phase has its own limit; applying a committed operation and waiting for `completed` use the remaining initialization budget, not the staging limit. Expiry before application rejects the transfer; expiry during application reports `unknown` after local mutations stop and never authorizes replay. A terminal `completed`, `failed` or `unknown` result of an operation the Runtime applied carries `duration_ms`, the Runtime-measured time from the start of application to the outcome; no other result carries it, and it adds no command text, path or output. Validate the expected outcome, offset, size, duration and finite error code with the shared validator. One transfer is allowed per connection. A chunk receipt confirms staged bytes, not installation; a completed commit confirms that operation, not that a later Turn ran. An execution Turn runs as follows. Core subscribes to preparation status before it sends `execution_prepare` and to the Run before it sends `execution_start`, because output can race the status. diff --git a/docs/zh/runtime-protocol.md b/docs/zh/runtime-protocol.md index 5cbe4e530..2f32ea541 100644 --- a/docs/zh/runtime-protocol.md +++ b/docs/zh/runtime-protocol.md @@ -1,7 +1,7 @@ --- title: "Core–Runtime 协议" source: docs/runtime-protocol.md -source_hash: 986ab6e6ef3979a672f2e49f7c75346e7bfff327d9de1a6138e7f5c75b55d720 +source_hash: d0180316782a49812b3922ed544e2338d66cb735e496c5d08ccac47e1e2b4024 --- Core–Runtime 协议连接 Core 与 Runtime daemon,定义 daemon 连接上消息的含义和顺序。托管和自托管 Runtime 使用同一协议。 @@ -147,7 +147,7 @@ sequenceDiagram R-->>C: runtime_prepare_result completed ``` -初始化和终结阶段使用不含文件数据的类型化 header。每个 `begin` 携带 `budget_ms`,表示 Core 所拥有的初始化预算剩余毫秒数;chunk 和 commit 不携带该字段。Runtime 从收到 `begin` 起执行此相对预算,Core 的等待不超过原操作期限。`begin`–`commit` 暂存阶段另有独立限制;应用已提交操作及等待 `completed` 使用剩余初始化预算,不受暂存限制约束。应用前到期会拒绝传输;应用中到期则在本地变更停止后报告 `unknown`,绝不授权重放。使用共享 validator 验证预期结果、offset、size 和有限错误 code。每条连接允许一个 transfer。chunk 回执确认暂存字节,不确认安装;完成的 commit 确认该操作,不证明后续 Turn 已运行。 +初始化和终结阶段使用不含文件数据的类型化 header。每个 `begin` 携带 `budget_ms`,表示 Core 所拥有的初始化预算剩余毫秒数;chunk 和 commit 不携带该字段。Runtime 从收到 `begin` 起执行此相对预算,Core 的等待不超过原操作期限。`begin`–`commit` 暂存阶段另有独立限制;应用已提交操作及等待 `completed` 使用剩余初始化预算,不受暂存限制约束。应用前到期会拒绝传输;应用中到期则在本地变更停止后报告 `unknown`,绝不授权重放。Runtime 已应用的操作,其终态 `completed`、`failed` 或 `unknown` 结果携带 `duration_ms`,即 Runtime 测得的从开始应用到得出结果的时间;其他结果不携带,它也不增加命令文本、路径或输出。使用共享 validator 验证预期结果、offset、size、duration 和有限错误 code。每条连接允许一个 transfer。chunk 回执确认暂存字节,不确认安装;完成的 commit 确认该操作,不证明后续 Turn 已运行。 执行 Turn 流程如下。Core 在发送 `execution_prepare` 之前订阅 preparation status,在发送 `execution_start` 之前订阅 Run,因为输出可能与 status 竞争。 diff --git a/internal/agentdaemon/proto/runtime_prepare.go b/internal/agentdaemon/proto/runtime_prepare.go index ea388f47a..ad710190f 100644 --- a/internal/agentdaemon/proto/runtime_prepare.go +++ b/internal/agentdaemon/proto/runtime_prepare.go @@ -61,6 +61,9 @@ type RuntimePrepareResultPayload struct { Offset int `json:"offset,omitempty"` SizeBytes int `json:"size_bytes,omitempty"` ErrorCode string `json:"error_code,omitempty"` + // DurationMS is the Runtime-measured time spent applying the operation. It is + // reported only by a terminal result of an operation that was applied. + DurationMS int64 `json:"duration_ms,omitempty"` } func ValidRuntimePrepareRequest(p RuntimePreparePayload) bool { @@ -144,6 +147,9 @@ func ValidRuntimePrepareResult(r RuntimePrepareResultPayload, expected string, o if r.ExitCode < 0 || r.ExitCode > 255 || (r.Outcome != "failed" && r.ExitCode != 0) { return false } + if r.DurationMS < 0 || r.DurationMS > RuntimePrepareMaxBudgetMS || (r.DurationMS != 0 && r.Outcome != "completed" && r.Outcome != "failed" && r.Outcome != "unknown") { + return false + } switch r.Outcome { case "rejected": if r.Offset != 0 || r.SizeBytes != 0 { diff --git a/internal/agentdaemon/proto/runtime_prepare_test.go b/internal/agentdaemon/proto/runtime_prepare_test.go index aa0f37b84..1e43d6ebd 100644 --- a/internal/agentdaemon/proto/runtime_prepare_test.go +++ b/internal/agentdaemon/proto/runtime_prepare_test.go @@ -283,3 +283,19 @@ func TestRuntimePreparationBudgetOnlyOnBegin(t *testing.T) { } } } + +func TestRuntimePrepareResultDuration(t *testing.T) { + for _, tc := range []struct { + result RuntimePrepareResultPayload + valid bool + }{ + {RuntimePrepareResultPayload{Outcome: "completed", DurationMS: 1500}, true}, + {RuntimePrepareResultPayload{Outcome: "completed", DurationMS: -1}, false}, + {RuntimePrepareResultPayload{Outcome: "completed", DurationMS: RuntimePrepareMaxBudgetMS + 1}, false}, + {RuntimePrepareResultPayload{Outcome: "rejected", ErrorCode: "invalid_request", DurationMS: 1}, false}, + } { + if got := ValidRuntimePrepareResult(tc.result, "completed", 0, 0); got != tc.valid { + t.Fatalf("%+v: valid=%v", tc.result, got) + } + } +} diff --git a/internal/agentdaemon/proto/version.go b/internal/agentdaemon/proto/version.go index d24c19dd7..9ae7aecb6 100644 --- a/internal/agentdaemon/proto/version.go +++ b/internal/agentdaemon/proto/version.go @@ -2,7 +2,7 @@ package proto // Version identifies the complete Core–Runtime wire contract. Change it when // removing or changing a payload or its semantics; deploy both endpoints together. -const Version = "0.22.0" +const Version = "0.23.0" // VersionCompatible accepts only this contract. Patch drift, prerelease suffixes // and malformed versions do not select an implicit compatibility path. diff --git a/packages/agents-client/src/generated/core-api.ts b/packages/agents-client/src/generated/core-api.ts index be0433809..4dae6fc7c 100644 --- a/packages/agents-client/src/generated/core-api.ts +++ b/packages/agents-client/src/generated/core-api.ts @@ -339,6 +339,14 @@ export interface HostHistoryPoint { start: string; } export const hostHistoryPointFields = ["available_disk_bytes_min", "cpu_utilization_max", "memory_used_bytes_max", "start"] as const; +export interface InitializationStepTiming { + duration_ms: number; + index: number | null; + step: InitializationStepTimingStep; +} +export const initializationStepTimingFields = ["duration_ms", "index", "step"] as const; +export const initializationStepTimingStepValues = ["file", "skill", "plugin", "configure", "npm", "python", "setup", "finalize"] as const; +export type InitializationStepTimingStep = (typeof initializationStepTimingStepValues)[number]; export interface Installation { address_bindings: AddressBindings; api_base_url: string; @@ -885,11 +893,12 @@ export const sessionDiagnosticFailureCodeValues = ["harness_error", "model_provi export type SessionDiagnosticFailureCode = (typeof sessionDiagnosticFailureCodeValues)[number]; export interface SessionDiagnostics { failure: SessionDiagnosticFailure | null; + initialization_steps: InitializationStepTiming[]; object: "core.session_diagnostics"; session_id: string; status: SessionDiagnosticsStatus; } -export const sessionDiagnosticsFields = ["failure", "object", "session_id", "status"] as const; +export const sessionDiagnosticsFields = ["failure", "initialization_steps", "object", "session_id", "status"] as const; export const sessionDiagnosticsStatusValues = ["idle", "in_progress", "requires_action", "failed"] as const; export type SessionDiagnosticsStatus = (typeof sessionDiagnosticsStatusValues)[number]; export interface SessionExecutionConfiguration { diff --git a/packages/agents-client/src/index.ts b/packages/agents-client/src/index.ts index 2c450c799..6c81cc79c 100644 --- a/packages/agents-client/src/index.ts +++ b/packages/agents-client/src/index.ts @@ -12,7 +12,7 @@ export { AdminClient } from "./admin-client"; export { adminResourceTypes } from "./admin-types"; export type { AdminClientOptions, AdminProject, CreateAdminProjectInput, RenameAdminProjectInput, AdminAPIKey, AdminIssuedAPIKey, IssueAdminAPIKeyInput, AdminPage, AdminDeleted, AdminContent, AdminResourceType, AdminKeyProvenance, AdminResourceOwner, AdminWriteOperation, AdminWriteOperationOptions, AdminWriteOperationPage, AdminSummaryOptions, AdminSummaryEntry, AdminSummary, AdminRuntimeObservation, AdminAuditOptions, AdminAuditEntry, AdminAuditPage, ExecutorCredential, ExecutorConnection, ExecutorCredentialList, IssueExecutorCredentialInput, IssuedExecutorCredential, CoreInstallation, CoreInstallationConfiguration, CoreInstallationSetting, CoreAddressBindings } from "./admin-types"; -export type { DiagnosticFailureCode, ConnectionFailureParams, ProvisioningFailureParams, DiagnosticFailure, SessionDiagnosticFailure, SessionDiagnostics, ItemDiagnosticTiming, TurnDiagnostics } from "./session-diagnostics"; +export type { DiagnosticFailureCode, ConnectionFailureParams, ProvisioningFailureParams, ProvisioningCategory, InitializationStepTiming, DiagnosticFailure, SessionDiagnosticFailure, SessionDiagnostics, ItemDiagnosticTiming, TurnDiagnostics } from "./session-diagnostics"; export type { Selection as WorkspaceStorageSelection, WorkspaceStorageInput } from "./generated/core-api"; diff --git a/packages/agents-client/src/session-diagnostics.test.ts b/packages/agents-client/src/session-diagnostics.test.ts index 1f6d32f6f..e83a5ecdd 100644 --- a/packages/agents-client/src/session-diagnostics.test.ts +++ b/packages/agents-client/src/session-diagnostics.test.ts @@ -1,13 +1,14 @@ import { expect, it } from "vitest"; import { AdminClient } from "./admin-client"; -import { projectSessionDiagnostics, projectTurnDiagnostics } from "./session-diagnostics"; +import provisioningCategoryFixture from "../../../services/core/internal/sessions/testdata/provisioning-categories.json"; +import { projectSessionDiagnostics, projectTurnDiagnostics, provisioningCategoryValues } from "./session-diagnostics"; const id = "a113b7db-c689-4dfc-af9a-04bd0e466f11"; const turn = "729dab72-a9ea-4d0a-a38c-1b45e46233a9"; const item = "bf8d4f3a-d8bd-4d59-ad37-15f186f90832"; const time = "2026-09-28T03:00:00.123456Z"; const failure = { code: "runtime_disconnected", params: {}, failed_at: time }; -const session = { object: "core.session_diagnostics", session_id: id, status: "failed", failure: { ...failure, source: "turn", turn_id: turn } }; +const session = { object: "core.session_diagnostics", session_id: id, status: "failed", failure: { ...failure, source: "turn", turn_id: turn }, initialization_steps: [{ step: "npm", index: null, duration_ms: 4100 }, { step: "setup", index: 1, duration_ms: 5200 }] }; const snapshot = { object: "core.turn_diagnostics", session_id: id, turn_id: turn, status: "failed", failure, items: [{ item_id: item, started_at: time, completed_at: null, observed_duration_ms: null }], items_truncated: false }; it("retrieves Core diagnostics with credential, scope and cancellation", async () => { @@ -25,13 +26,13 @@ it("retrieves Core diagnostics with credential, scope and cancellation", async ( }); it("preserves historical nulls and finite safe provisioning parameters", () => { - const value = { ...session, failure: { source: "environment", code: "environment_provisioning_failed", params: { step: "setup", index: 2, exit_code: 7 }, failed_at: null } }; + const value = { ...session, failure: { source: "environment", code: "environment_provisioning_failed", params: { step: "setup", index: 2, exit_code: 7, category: null }, failed_at: null } }; expect(projectSessionDiagnostics(value, id)).toEqual(value); expect(projectTurnDiagnostics(snapshot, id.toUpperCase(), turn.toUpperCase())).toEqual(snapshot); }); it("accepts the Harness step Core records when the selected Harness is unavailable", () => { - const value = { ...session, failure: { source: "environment", code: "environment_provisioning_failed", params: { step: "harness", index: null, exit_code: null }, failed_at: null } }; + const value = { ...session, failure: { source: "environment", code: "environment_provisioning_failed", params: { step: "harness", index: null, exit_code: null, category: null }, failed_at: null } }; expect(projectSessionDiagnostics(value, id)).toEqual(value); }); @@ -53,12 +54,20 @@ it.each([ expect(() => projectTurnDiagnostics(value, id, turn)).not.toThrow(/secret-canary/u); }); +it("preserves a failure category and rejects malformed initialization steps", () => { + const categorized = { ...session, failure: { source: "environment", code: "environment_provisioning_failed", params: { step: null, index: null, exit_code: null, category: "timeout" }, failed_at: null } }; + expect(projectSessionDiagnostics(categorized, id)).toEqual(categorized); + expect(() => projectSessionDiagnostics({ ...categorized, failure: { ...categorized.failure, params: { ...categorized.failure.params, category: "secret-canary" } } }, id)).toThrow(); + expect(() => projectSessionDiagnostics({ ...session, initialization_steps: [{ step: "setup", index: null, duration_ms: 1 }] }, id)).toThrow(); + expect(() => projectSessionDiagnostics({ ...session, initialization_steps: [{ step: "npm", index: null, duration_ms: -1 }] }, id)).toThrow(); +}); + it.each([ - { step: "secret-canary", index: null, exit_code: null }, - { step: "python", index: 3, exit_code: 2 }, - { step: "setup", index: Number.MAX_SAFE_INTEGER + 1, exit_code: 1 }, - { step: "file", index: null, exit_code: 1 }, - { step: "setup", index: 0, exit_code: 256 }, + { step: "secret-canary", index: null, exit_code: null, category: null }, + { step: "python", index: 3, exit_code: 2, category: null }, + { step: "setup", index: Number.MAX_SAFE_INTEGER + 1, exit_code: 1, category: null }, + { step: "file", index: null, exit_code: 1, category: null }, + { step: "setup", index: 0, exit_code: 256, category: null }, ])("rejects unsafe provisioning parameters", (params) => { const value = { ...session, failure: { source: "environment", code: "environment_provisioning_failed", params, failed_at: time } }; expect(() => projectSessionDiagnostics(value, id)).toThrow(); @@ -82,7 +91,7 @@ it("rejects HTTP status parameters on nonconnection categories", () => { expect(() => projectTurnDiagnostics({ ...snapshot, failure: { ...failure, code: "authentication_error", params: { http_status: 401 } } }, id, turn)).toThrow(); }); -const provisioning = { source: "environment", code: "environment_provisioning_failed", params: { step: "setup", index: null, exit_code: null }, failed_at: null }; +const provisioning = { source: "environment", code: "environment_provisioning_failed", params: { step: "setup", index: null, exit_code: null, category: null }, failed_at: null }; it.each([ ["Session status", () => projectSessionDiagnostics({ ...session, status: ["failed"], failure: null }, id)], ["Turn status", () => projectTurnDiagnostics({ ...snapshot, status: ["failed"], failure: null }, id, turn)], @@ -91,3 +100,7 @@ it.each([ ] as const)("rejects arrays in %s", (_field, project) => { expect(project).toThrow(); }); + +it("keeps the provisioning categories equal to the Core set", () => { + expect([...provisioningCategoryValues]).toEqual(provisioningCategoryFixture); +}); diff --git a/packages/agents-client/src/session-diagnostics.ts b/packages/agents-client/src/session-diagnostics.ts index a3c470b7b..9e7aa39a5 100644 --- a/packages/agents-client/src/session-diagnostics.ts +++ b/packages/agents-client/src/session-diagnostics.ts @@ -2,17 +2,20 @@ import { canonicalUuid, exactFields, isOneOf, isRecord, sameResourceId } from ". import { invalidAdminResponse } from "./admin-projection"; import { turnStatusResourceValues } from "./generated/public-api"; import { - diagnosticFailureFields, itemDiagnosticTimingFields, sessionDiagnosticFailureFields, sessionDiagnosticFailureRequired, + diagnosticFailureFields, initializationStepTimingFields, initializationStepTimingStepValues, itemDiagnosticTimingFields, sessionDiagnosticFailureFields, sessionDiagnosticFailureRequired, diagnosticSourceValues, sessionDiagnosticsFields, sessionDiagnosticsStatusValues, turnDiagnosticsFields, - type DiagnosticFailure as DiagnosticFailureResource, type DiagnosticFailureCode, type ItemDiagnosticTiming, + type DiagnosticFailure as DiagnosticFailureResource, type DiagnosticFailureCode, type InitializationStepTiming, type ItemDiagnosticTiming, type SessionDiagnosticFailure as SessionDiagnosticFailureResource, type SessionDiagnostics as SessionDiagnosticsResource, type TurnDiagnostics as TurnDiagnosticsResource, } from "./generated/core-api"; +// provisioningCategoryValues is checked against the Go set by the shared fixture in session-diagnostics.test.ts. // ItemDiagnosticTiming holds Core receipt intervals, distinct from the public tool-reported duration_ms. -export type { DiagnosticFailureCode, ItemDiagnosticTiming }; +export type { DiagnosticFailureCode, InitializationStepTiming, ItemDiagnosticTiming }; // The schema types params as a free-form object; each code that carries params has one of these shapes. -export type ProvisioningFailureParams = { step: "setup" | "python" | "npm" | "file" | "skill" | "harness" | null; index: number | null; exit_code: number | null }; +export const provisioningCategoryValues = ["timeout", "runtime_disconnected", "unconfirmed", "rejected", "operation_failed", "core_error", "core_restart", "compute_released"] as const; +export type ProvisioningCategory = (typeof provisioningCategoryValues)[number]; +export type ProvisioningFailureParams = { step: "setup" | "python" | "npm" | "file" | "skill" | "harness" | null; index: number | null; exit_code: number | null; category: ProvisioningCategory | null }; export type ConnectionFailureParams = { http_status: number | null }; export type DiagnosticFailure = Omit & { params: Record | ProvisioningFailureParams | ConnectionFailureParams }; export type SessionDiagnosticFailure = DiagnosticFailure & Pick; @@ -33,10 +36,10 @@ function failure(value: unknown, codes: readonly DiagnosticFailureCode[], sessio let params: DiagnosticFailure["params"] = {}; if (value.code === "environment_provisioning_failed") { const p = value.params; - if (!exactFields(p, fields("step", "index", "exit_code")) || (p.step !== null && (typeof p.step !== "string" || !["setup", "python", "npm", "file", "skill", "harness"].includes(p.step))) || + if (!exactFields(p, fields("step", "index", "exit_code", "category")) || (p.category !== null && (!isOneOf(provisioningCategoryValues, p.category) || p.step !== null)) || (p.step !== null && (typeof p.step !== "string" || !["setup", "python", "npm", "file", "skill", "harness"].includes(p.step))) || (p.index !== null && (!Number.isSafeInteger(p.index) || (p.index as number) < 0 || p.step !== "setup")) || (p.exit_code !== null && (!Number.isSafeInteger(p.exit_code) || (p.exit_code as number) < 1 || (p.exit_code as number) > 255 || !["setup", "python", "npm"].includes(p.step ?? "")))) return invalidAdminResponse(); - params = { step: p.step as ProvisioningFailureParams["step"], index: p.index as number | null, exit_code: p.exit_code as number | null }; + params = { step: p.step as ProvisioningFailureParams["step"], index: p.index as number | null, exit_code: p.exit_code as number | null, category: p.category as ProvisioningFailureParams["category"] }; } else if (value.code === "connection_failed") { const p = value.params; if (!exactFields(p, fields("http_status")) || (p.http_status !== null && (!Number.isSafeInteger(p.http_status) || (p.http_status as number) < 100 || (p.http_status as number) > 599))) return invalidAdminResponse(); @@ -59,7 +62,14 @@ export function projectSessionDiagnostics(value: unknown, sessionId: string): Se projected.turn_id = f.turn_id as string; } } else if (value.failure !== null) return invalidAdminResponse(); - return { object: "core.session_diagnostics", session_id: value.session_id as string, status: value.status, failure: projected }; + if (!Array.isArray(value.initialization_steps)) return invalidAdminResponse(); + const initialization_steps: InitializationStepTiming[] = value.initialization_steps.map((step: unknown) => { + if (!isRecord(step) || !exactFields(step, initializationStepTimingFields) || !isOneOf(initializationStepTimingStepValues, step.step) || + !Number.isSafeInteger(step.duration_ms) || (step.duration_ms as number) < 0 || + (step.step === "setup" ? !Number.isSafeInteger(step.index) || (step.index as number) < 0 : step.index !== null)) return invalidAdminResponse(); + return { step: step.step, index: step.index as number | null, duration_ms: step.duration_ms as number }; + }); + return { object: "core.session_diagnostics", session_id: value.session_id as string, status: value.status, failure: projected, initialization_steps }; } export function projectTurnDiagnostics(value: unknown, sessionId: string, turnId: string): TurnDiagnostics { diff --git a/scripts/ci_plan.py b/scripts/ci_plan.py index 7d6836881..f76b2c8f8 100644 --- a/scripts/ci_plan.py +++ b/scripts/ci_plan.py @@ -100,6 +100,7 @@ ) EXACT_INPUTS = { "services/core/internal/sandbox/testdata/node-diagnostics.json": ("web", "web-acceptance", "example"), + "services/core/internal/sessions/testdata/provisioning-categories.json": ("web", "web-acceptance", "example"), "services/core/internal/sandbox/testdata/deployment-contract.json": ("distribution",), "services/core/internal/sandbox/e2b/testdata/configuration-selectors.json": ("distribution",), } diff --git a/services/core/internal/api/session_diagnostics.go b/services/core/internal/api/session_diagnostics.go index dd5ad70d3..ed0af2f85 100644 --- a/services/core/internal/api/session_diagnostics.go +++ b/services/core/internal/api/session_diagnostics.go @@ -30,11 +30,20 @@ type SessionDiagnosticFailure struct { TurnID string `json:"turn_id,omitempty"` } +// InitializationStepTiming is the Runtime-measured duration of one Environment initialization operation that ran. +type InitializationStepTiming struct { + Step string `json:"step" enums:"file,skill,plugin,configure,npm,python,setup,finalize" binding:"required"` + Index *int `json:"index" extensions:"x-nullable" binding:"required"` + DurationMS int64 `json:"duration_ms" binding:"required"` +} + type SessionDiagnostics struct { Object string `json:"object" enums:"core.session_diagnostics" binding:"required"` SessionID string `json:"session_id" binding:"required"` Status string `json:"status" enums:"idle,in_progress,requires_action,failed" binding:"required"` Failure *SessionDiagnosticFailure `json:"failure" extensions:"x-nullable" binding:"required"` + // InitializationSteps lists the operations the Environment's initialization ran, in order. + InitializationSteps []InitializationStepTiming `json:"initialization_steps" binding:"required"` } type ItemDiagnosticTiming struct { @@ -85,7 +94,10 @@ func (h *Handler) getSessionDiagnostics(w http.ResponseWriter, r *http.Request) writeSessionsError(w, r, err) return } - response := SessionDiagnostics{Object: "core.session_diagnostics", SessionID: public.ID, Status: public.Status} + response := SessionDiagnostics{Object: "core.session_diagnostics", SessionID: public.ID, Status: public.Status, InitializationSteps: []InitializationStepTiming{}} + for _, step := range session.EnvironmentInitializationSteps { + response.InitializationSteps = append(response.InitializationSteps, InitializationStepTiming{Step: string(step.Step), Index: step.Index, DurationMS: step.DurationMS}) + } if public.Status == "failed" { failure := SessionDiagnosticFailure{DiagnosticFailure: DiagnosticFailure{Code: "internal_error", Params: CoreErrorDetails{}}} switch { @@ -162,7 +174,7 @@ func diagnosticTime(value time.Time) *time.Time { } func provisioningFailureParams(detail *sessions.ProvisioningFailureDetail) CoreErrorDetails { - params := CoreErrorDetails{"step": CoreErrorNull(), "index": CoreErrorNull(), "exit_code": CoreErrorNull()} + params := CoreErrorDetails{"step": CoreErrorNull(), "index": CoreErrorNull(), "exit_code": CoreErrorNull(), "category": CoreErrorNull()} if detail == nil { return params } @@ -172,6 +184,9 @@ func provisioningFailureParams(detail *sessions.ProvisioningFailureDetail) CoreE if detail.Index != nil { params["index"] = CoreErrorNumber(float64(*detail.Index)) } + if detail.Category != nil { + params["category"] = CoreErrorString(string(*detail.Category)) + } if detail.ExitCode != nil { params["exit_code"] = CoreErrorNumber(float64(*detail.ExitCode)) } diff --git a/services/core/internal/api/session_diagnostics_test.go b/services/core/internal/api/session_diagnostics_test.go index becdf229e..67e5efc5a 100644 --- a/services/core/internal/api/session_diagnostics_test.go +++ b/services/core/internal/api/session_diagnostics_test.go @@ -107,19 +107,22 @@ func TestDiagnosticsHostedFailureOverridesInputWithoutParsingReason(t *testing.T session := hostedFailureSession() session.EnvironmentInputActivity = &sessions.EnvironmentInputActivity{Status: "failed", Failure: "environment_unavailable", LastActiveAt: time.Now()} session.LastTurn = &sessions.Turn{ID: uuid.NewString(), SessionID: session.ID, Status: sessions.TurnFailed, Outcome: json.RawMessage(`{"error_code":"engine_failed"}`)} - step, index, exit := "setup", 2, 7 - for _, detail := range []*sessions.ProvisioningFailureDetail{nil, {Step: &step, Index: &index, ExitCode: &exit}} { + step, index, exit, category := "setup", 2, 7, sessions.ProvisioningTimeout + session.EnvironmentInitializationSteps = []sessions.InitializationStep{{Step: "npm", DurationMS: 4100}, {Step: "setup", Index: &index, DurationMS: 5200}} + for _, detail := range []*sessions.ProvisioningFailureDetail{nil, {Step: &step, Index: &index, ExitCode: &exit}, {Category: &category}} { session.EnvironmentFailure = &sessions.EnvironmentFailure{Reason: "private-secret-canary setup_commands[99] exit 254", Detail: detail} h, _, _ := adminTestHandler(t, serveDiagnostics(diagnosticSnapshotStore{session: session})) w := diagnosticRequest(h, adminSessionsPath+session.ID+"/diagnostics", "Bearer admin") if w.Code != 200 || strings.Contains(w.Body.String(), "canary") || !strings.Contains(w.Body.String(), `"code":"environment_provisioning_failed"`) || !strings.Contains(w.Body.String(), `"source":"environment"`) { t.Fatal(w.Code, w.Body) } - want := `"params":{"exit_code":null,"index":null,"step":null}` - if detail != nil { - want = `"params":{"exit_code":7,"index":2,"step":"setup"}` + want := `"params":{"category":null,"exit_code":null,"index":null,"step":null}` + if detail != nil && detail.Step != nil { + want = `"params":{"category":null,"exit_code":7,"index":2,"step":"setup"}` + } else if detail != nil { + want = `"params":{"category":"timeout","exit_code":null,"index":null,"step":null}` } - if !strings.Contains(w.Body.String(), want) || !strings.Contains(w.Body.String(), `"failed_at":null`) { + if !strings.Contains(w.Body.String(), `"initialization_steps":[{"step":"npm","index":null,"duration_ms":4100},{"step":"setup","index":2,"duration_ms":5200}]`) || !strings.Contains(w.Body.String(), want) || !strings.Contains(w.Body.String(), `"failed_at":null`) { t.Fatal("historical reason parsed or time invented", w.Body) } } @@ -132,3 +135,14 @@ func TestDiagnosticStatusMatchesOfficialSession(t *testing.T) { t.Fatal("diagnostics must preserve the pinned official Session status set") } } + +func TestDiagnosticStepEnumMatchesDeclaredLabels(t *testing.T) { + field, _ := reflect.TypeFor[InitializationStepTiming]().FieldByName("Step") + var declared []string + for _, label := range sessions.InitializationLabels { + declared = append(declared, string(label)) + } + if field.Tag.Get("enums") != strings.Join(declared, ",") { + t.Fatal("OpenAPI step enum differs from the declared labels", field.Tag.Get("enums")) + } +} diff --git a/services/core/internal/db/queries/environment_initialization.sql b/services/core/internal/db/queries/environment_initialization.sql index d1452e781..f3d671337 100644 --- a/services/core/internal/db/queries/environment_initialization.sql +++ b/services/core/internal/db/queries/environment_initialization.sql @@ -14,5 +14,9 @@ WHERE id = $1 AND initialization = 'pending' AND status NOT IN ('failed', 'expir UPDATE environments SET initialization = 'complete' WHERE id = $1 AND initialization = 'running' AND status NOT IN ('failed', 'expired'); +-- name: RecordEnvironmentInitializationSteps :exec +UPDATE environments SET initialization_steps = sqlc.arg(steps) +WHERE id = sqlc.arg(id) AND initialization = 'running'; + -- name: FailEnvironmentInitialization :exec UPDATE environments SET initialization = 'failed' WHERE id = $1 AND initialization <> 'complete'; diff --git a/services/core/internal/db/sqlc/environment_initialization.sql.go b/services/core/internal/db/sqlc/environment_initialization.sql.go index 102d4837d..a3c8c5bbf 100644 --- a/services/core/internal/db/sqlc/environment_initialization.sql.go +++ b/services/core/internal/db/sqlc/environment_initialization.sql.go @@ -90,3 +90,18 @@ func (q *Queries) ListEnvironmentInitializations(ctx context.Context, id pgtype. } return items, nil } + +const recordEnvironmentInitializationSteps = `-- name: RecordEnvironmentInitializationSteps :exec +UPDATE environments SET initialization_steps = $1 +WHERE id = $2 AND initialization = 'running' +` + +type RecordEnvironmentInitializationStepsParams struct { + Steps []byte `json:"steps"` + ID pgtype.UUID `json:"id"` +} + +func (q *Queries) RecordEnvironmentInitializationSteps(ctx context.Context, arg RecordEnvironmentInitializationStepsParams) error { + _, err := q.db.Exec(ctx, recordEnvironmentInitializationSteps, arg.Steps, arg.ID) + return err +} diff --git a/services/core/internal/db/sqlc/environments.sql.go b/services/core/internal/db/sqlc/environments.sql.go index 6a8097c94..514d21724 100644 --- a/services/core/internal/db/sqlc/environments.sql.go +++ b/services/core/internal/db/sqlc/environments.sql.go @@ -28,7 +28,7 @@ func (q *Queries) CreateEnvironment(ctx context.Context, arg CreateEnvironmentPa } const getEnvironment = `-- name: GetEnvironment :one -SELECT e.id, e.session_id, e.status, e.created_at, e.failure_reason, e.failed_at, e.failure_detail, e.initialization, s.tenant_id, (s.configuration->'environment')::jsonb AS configuration, +SELECT e.id, e.session_id, e.status, e.created_at, e.failure_reason, e.failed_at, e.failure_detail, e.initialization, e.initialization_steps, s.tenant_id, (s.configuration->'environment')::jsonb AS configuration, EXISTS (SELECT 1 FROM environment_workspaces w WHERE w.environment_id = e.id)::boolean AS external_workspace FROM environments e JOIN sessions s ON s.id = e.session_id WHERE s.tenant_id = $1 AND e.id = $2 AND s.deleted_at IS NULL @@ -58,6 +58,7 @@ func (q *Queries) GetEnvironment(ctx context.Context, arg GetEnvironmentParams) &i.Environment.FailedAt, &i.Environment.FailureDetail, &i.Environment.Initialization, + &i.Environment.InitializationSteps, &i.TenantID, &i.Configuration, &i.ExternalWorkspace, @@ -66,7 +67,7 @@ func (q *Queries) GetEnvironment(ctx context.Context, arg GetEnvironmentParams) } const getSessionEnvironment = `-- name: GetSessionEnvironment :one -SELECT e.id, e.session_id, e.status, e.created_at, e.failure_reason, e.failed_at, e.failure_detail, e.initialization, s.tenant_id, (s.configuration->'environment')::jsonb AS configuration, +SELECT e.id, e.session_id, e.status, e.created_at, e.failure_reason, e.failed_at, e.failure_detail, e.initialization, e.initialization_steps, s.tenant_id, (s.configuration->'environment')::jsonb AS configuration, EXISTS (SELECT 1 FROM environment_workspaces w WHERE w.environment_id = e.id)::boolean AS external_workspace FROM environments e JOIN sessions s ON s.id = e.session_id WHERE s.tenant_id = $1 AND s.id = $2 AND s.deleted_at IS NULL @@ -96,6 +97,7 @@ func (q *Queries) GetSessionEnvironment(ctx context.Context, arg GetSessionEnvir &i.Environment.FailedAt, &i.Environment.FailureDetail, &i.Environment.Initialization, + &i.Environment.InitializationSteps, &i.TenantID, &i.Configuration, &i.ExternalWorkspace, diff --git a/services/core/internal/db/sqlc/models.go b/services/core/internal/db/sqlc/models.go index 035c6b639..4d11656ca 100644 --- a/services/core/internal/db/sqlc/models.go +++ b/services/core/internal/db/sqlc/models.go @@ -68,14 +68,15 @@ type Device struct { } type Environment struct { - ID pgtype.UUID `json:"id"` - SessionID pgtype.UUID `json:"session_id"` - Status string `json:"status"` - CreatedAt pgtype.Timestamptz `json:"created_at"` - FailureReason pgtype.Text `json:"failure_reason"` - FailedAt pgtype.Timestamptz `json:"failed_at"` - FailureDetail []byte `json:"failure_detail"` - Initialization string `json:"initialization"` + ID pgtype.UUID `json:"id"` + SessionID pgtype.UUID `json:"session_id"` + Status string `json:"status"` + CreatedAt pgtype.Timestamptz `json:"created_at"` + FailureReason pgtype.Text `json:"failure_reason"` + FailedAt pgtype.Timestamptz `json:"failed_at"` + FailureDetail []byte `json:"failure_detail"` + Initialization string `json:"initialization"` + InitializationSteps []byte `json:"initialization_steps"` } type EnvironmentConnection struct { diff --git a/services/core/internal/deployment/allocations.go b/services/core/internal/deployment/allocations.go index e0ebb2cd4..b1aa86d77 100644 --- a/services/core/internal/deployment/allocations.go +++ b/services/core/internal/deployment/allocations.go @@ -223,7 +223,7 @@ func (e *ExecutionOperations) cleanup(ctx context.Context, owner Allocation, evi return ErrAllocationConflict } if !retain { - err = sessions.TerminateEnvironment(ctx, tx, revoked.Expired, sessions.ProvisioningFailureReason, nil) + err = sessions.TerminateEnvironment(ctx, tx, revoked.Expired, sessions.ProvisioningFailureReason, sessions.ProvisioningFailure{Category: sessions.ProvisioningComputeReleased}.Detail()) } } if err != nil { diff --git a/services/core/internal/execution/runtime_capabilities_test.go b/services/core/internal/execution/runtime_capabilities_test.go index 52d30fbd6..0c2b411bd 100644 --- a/services/core/internal/execution/runtime_capabilities_test.go +++ b/services/core/internal/execution/runtime_capabilities_test.go @@ -39,7 +39,7 @@ func TestRuntimeCapabilitiesPreserveRawBundlesAndSetupOrdering(t *testing.T) { owner := agentcapabilities.Identity{EnvironmentID: uuid.NewString(), SessionID: uuid.NewString()} for _, op := range operations { peer := &capabilityFixture{outcome: "completed"} - if err := runRuntimeSetup(initializationTestContext(t), peer, owner, op); err != nil { + if _, err := runRuntimeSetup(initializationTestContext(t), peer, owner, op); err != nil { t.Fatal(err) } if _, err := uuid.Parse(peer.requestID); err != nil { @@ -63,14 +63,14 @@ func TestRuntimeCapabilitiesPreserveRawBundlesAndSetupOrdering(t *testing.T) { func TestRuntimeCapabilitiesConfirmedAndUnknownFailures(t *testing.T) { for _, outcome := range []string{"failed", "rejected", "unknown", "unexpected"} { peer := &capabilityFixture{outcome: outcome} - err := runRuntimeSetup(initializationTestContext(t), peer, agentcapabilities.Identity{}, runtimeSetupOperation{Request: proto.RuntimePreparePayload{Action: "finalize"}}) + _, err := runRuntimeSetup(initializationTestContext(t), peer, agentcapabilities.Identity{}, runtimeSetupOperation{Request: proto.RuntimePreparePayload{Action: "finalize"}}) var confirmed *runtimeStepFailure if err == nil || errors.As(err, &confirmed) != (outcome == "failed" || outcome == "rejected") { t.Fatal(outcome, err) } } peer := &capabilityFixture{outcome: "completed", err: errors.New(setupCanary)} - err := runRuntimeSetup(initializationTestContext(t), peer, agentcapabilities.Identity{}, runtimeSetupOperation{Request: proto.RuntimePreparePayload{}}) + _, err := runRuntimeSetup(initializationTestContext(t), peer, agentcapabilities.Identity{}, runtimeSetupOperation{Request: proto.RuntimePreparePayload{}}) if err == nil || bytes.Contains([]byte(err.Error()), []byte(setupCanary)) { t.Fatal("transport error leaked or succeeded", err) } diff --git a/services/core/internal/execution/runtime_initialization.go b/services/core/internal/execution/runtime_initialization.go index 3b01cde3e..91177c91b 100644 --- a/services/core/internal/execution/runtime_initialization.go +++ b/services/core/internal/execution/runtime_initialization.go @@ -50,7 +50,7 @@ func (w *Worker) runEnvironmentInitializations(ctx context.Context) error { } if owner.State == "running" { // Lost process-local progress cannot prove which side effects ran. - if err := w.dispatcher.sessionExecution.FailEnvironmentInitialization(ctx, owner, sessions.ProvisioningFailure{}); err != nil && !errors.Is(err, sessions.ErrNotFound) { + if err := w.dispatcher.sessionExecution.FailEnvironmentInitialization(ctx, owner, sessions.ProvisioningFailure{Category: sessions.ProvisioningCoreRestart}); err != nil && !errors.Is(err, sessions.ErrNotFound) { return err } continue @@ -96,7 +96,15 @@ func (w *Worker) initializeEnvironment(ctx context.Context, owner sessions.Envir operation, cancel := context.WithTimeout(ctx, time.Duration(proto.RuntimePrepareMaxBudgetMS)*time.Millisecond) defer cancel() failure := sessions.ProvisioningFailure{} - err := w.prepareEnvironment(operation, owner, &failure) + steps := []sessions.InitializationStep{} + err := w.prepareEnvironment(operation, owner, &failure, &steps) + // Steps stay recorded for a failed initialization too, but a write failure never fails + // one that succeeded. Each step was already logged when it finished. + recordSteps, stopSteps := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + if recordErr := w.dispatcher.sessionExecution.RecordEnvironmentInitializationSteps(recordSteps, owner, steps); recordErr != nil { + log.Warn(ctx, "Environment initialization steps not recorded", "environment_id", owner.EnvironmentID, "session_id", owner.SessionID) + } + stopSteps() if err == nil { err = w.dispatcher.sessionExecution.CompleteEnvironmentInitialization(operation, owner) if err == nil { @@ -104,7 +112,10 @@ func (w *Worker) initializeEnvironment(ctx context.Context, owner sessions.Envir } } if err != nil { - log.Warn(ctx, "Environment preparation failed", "environment_id", owner.EnvironmentID, "session_id", owner.SessionID) + if failure.Step == "" && failure.Category == "" { + failure.Category = provisioningCategory(err) + } + log.Warn(ctx, "Environment preparation failed", "environment_id", owner.EnvironmentID, "session_id", owner.SessionID, "step", failure.Step, "category", string(failure.Category)) // A later scan settles an unrecorded failure; it never retries the setup. record, stop := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer stop() @@ -112,7 +123,7 @@ func (w *Worker) initializeEnvironment(ctx context.Context, owner sessions.Envir } } -func (w *Worker) prepareEnvironment(ctx context.Context, owner sessions.EnvironmentInitialization, failure *sessions.ProvisioningFailure) error { +func (w *Worker) prepareEnvironment(ctx context.Context, owner sessions.EnvironmentInitialization, failure *sessions.ProvisioningFailure, steps *[]sessions.InitializationStep) error { environment, err := w.dispatcher.SessionsReader.GetEnvironment(ctx, owner.TenantID, owner.EnvironmentID) if err != nil { return err @@ -146,25 +157,40 @@ func (w *Worker) prepareEnvironment(ctx context.Context, owner sessions.Environm operations := setupOperations(setup) step := func(index int) error { err := w.lease.CheckOwnership(ctx) + if err != nil { + err = errors.Join(errOwnershipLost, err) + } if err == nil { var currentPeer = peer currentPeer, err = w.dispatcher.authorizedPeer(ctx, owner.DeviceID) if err == nil && currentPeer != peer { - err = errors.New("Runtime connection changed during initialization") + err = errRuntimeConnectionChanged } } candidate := sessions.ProvisioningFailure{Step: sessions.ProvisioningInitialFile} + var result proto.RuntimePrepareResultPayload + var recorded sessions.InitializationStep if err == nil && index < len(cfg.Files) { var metadata environmentconfig.InitialFileMetadata var body []byte metadata, body, err = w.dispatcher.SessionsReader.ReadInitialEnvironmentFile(ctx, owner.TenantID, owner.SessionID, index) if err == nil { - err = installInitialFile(ctx, peer, identity, metadata, body) + result, err = installInitialFile(ctx, peer, identity, metadata, body) + recorded, _ = runtimeSetupOperation{Request: proto.RuntimePreparePayload{Action: "file"}}.step(result) } } else if err == nil { command := operations[index-len(cfg.Files)] candidate = command.provisioningFailure(0) - err = runRuntimeSetup(ctx, peer, identity, command) + result, err = runRuntimeSetup(ctx, peer, identity, command) + recorded, _ = command.step(result) + } + if recorded.Step != "" { + *steps = append(*steps, recorded) + attrs := []any{"environment_id", owner.EnvironmentID, "session_id", owner.SessionID, "step", recorded.Step, "duration_ms", recorded.DurationMS} + if recorded.Index != nil { + attrs = append(attrs, "index", *recorded.Index) + } + log.With(attrs...).InfoContext(ctx, "Environment initialization step") } var confirmed *runtimeStepFailure if errors.As(err, &confirmed) { diff --git a/services/core/internal/execution/runtime_setup.go b/services/core/internal/execution/runtime_setup.go index bff49c3f7..7abd302b1 100644 --- a/services/core/internal/execution/runtime_setup.go +++ b/services/core/internal/execution/runtime_setup.go @@ -8,6 +8,7 @@ import ( "github.com/MiniMax-AI/OpenAgentCore/internal/agentcapabilities" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/environmentconfig" + "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/runtimegateway" "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/sessions" "github.com/google/uuid" ) @@ -20,10 +21,65 @@ type runtimeSetupOperation struct { Index int } -type runtimeStepFailure struct{ exitCode int } +type runtimeStepFailure struct { + exitCode int + rejected bool +} func (*runtimeStepFailure) Error() string { return "environment initialization operation failed" } +// unconfirmedError reports an operation whose effect or receipt is unknown. It +// keeps the cause for classification and never renders it. +type unconfirmedError struct{ cause error } + +func (*unconfirmedError) Error() string { return "environment initialization operation unconfirmed" } +func (e *unconfirmedError) Unwrap() error { return e.cause } + +var errOwnershipLost = errors.New("Core lost ownership of the initialization") + +var errRuntimeConnectionChanged = errors.New("Runtime connection changed during initialization") + +// stepLabel is the fixed label of the operation in step timing. +func (operation runtimeSetupOperation) stepLabel() sessions.InitializationLabel { + if operation.Request.Initialization != nil { + return sessions.InitializationLabel(operation.Request.Initialization.Action) + } + return sessions.InitializationLabel(operation.Request.Action) +} + +// step reports the Runtime-measured timing of an operation that ran. +func (operation runtimeSetupOperation) step(result proto.RuntimePrepareResultPayload) (sessions.InitializationStep, bool) { + if result.Outcome != "completed" && result.Outcome != "failed" { + return sessions.InitializationStep{}, false + } + step := sessions.InitializationStep{Step: operation.stepLabel(), DurationMS: result.DurationMS} + if step.Step == sessions.InitializationSetup { + step.Index = &operation.Index + } + return step, true +} + +// provisioningCategory classifies a failure without a confirmed failed step. +func provisioningCategory(err error) sessions.ProvisioningCategory { + var confirmed *runtimeStepFailure + var unconfirmed *unconfirmedError + switch { + case errors.Is(err, errOwnershipLost): + return sessions.ProvisioningCoreRestart + case errors.Is(err, context.DeadlineExceeded): + return sessions.ProvisioningTimeout + case errors.Is(err, runtimegateway.ErrSessionClosed), errors.Is(err, runtimegateway.ErrDeviceNotRegistered), errors.Is(err, errRuntimeConnectionChanged): + return sessions.ProvisioningRuntimeDisconnected + case errors.As(err, &confirmed) && confirmed.rejected: + return sessions.ProvisioningRejected + case errors.As(err, &confirmed): + return sessions.ProvisioningOperationFailed + case errors.As(err, &unconfirmed): + return sessions.ProvisioningUnconfirmed + } + return sessions.ProvisioningCoreError +} + func (operation runtimeSetupOperation) provisioningFailure(exitCode int) sessions.ProvisioningFailure { action := operation.Request.Action if operation.Request.Initialization != nil { @@ -82,31 +138,31 @@ type runtimePreparer interface { PrepareRuntime(context.Context, string, proto.RuntimePreparePayload, []byte) (proto.RuntimePrepareResultPayload, error) } -func runRuntimeSetup(ctx context.Context, peer runtimePreparer, identity agentcapabilities.Identity, operation runtimeSetupOperation) error { +func runRuntimeSetup(ctx context.Context, peer runtimePreparer, identity agentcapabilities.Identity, operation runtimeSetupOperation) (proto.RuntimePrepareResultPayload, error) { if peer == nil { - return errors.New("environment initialization request unavailable") + return proto.RuntimePrepareResultPayload{}, errors.New("environment initialization request unavailable") } deadline, bounded := ctx.Deadline() budget := time.Until(deadline).Milliseconds() if !bounded || budget <= 0 || budget > proto.RuntimePrepareMaxBudgetMS || ctx.Err() != nil { - return errors.New("environment initialization budget unavailable") + return proto.RuntimePrepareResultPayload{}, errors.New("environment initialization budget unavailable") } request := operation.Request request.BudgetMS = budget request.EnvironmentID, request.SessionID = identity.EnvironmentID, identity.SessionID result, err := peer.PrepareRuntime(ctx, uuid.NewString(), request, operation.Data) if err == nil && result.Outcome == "completed" { - return nil + return result, nil } if err == nil && (result.Outcome == "rejected" || result.Outcome == "failed") { - return &runtimeStepFailure{exitCode: result.ExitCode} + return result, &runtimeStepFailure{exitCode: result.ExitCode, rejected: result.Outcome == "rejected"} } - return errors.New("environment initialization operation unconfirmed") + return result, &unconfirmedError{cause: err} } -func installInitialFile(ctx context.Context, peer runtimePreparer, identity agentcapabilities.Identity, file environmentconfig.InitialFileMetadata, body []byte) error { +func installInitialFile(ctx context.Context, peer runtimePreparer, identity agentcapabilities.Identity, file environmentconfig.InitialFileMetadata, body []byte) (proto.RuntimePrepareResultPayload, error) { if file.SizeBytes == nil || *file.SizeBytes != int64(len(body)) || len(body) > environmentconfig.MaxInitialFileBytes { - return errors.New("environment initialization request unavailable") + return proto.RuntimePrepareResultPayload{}, errors.New("environment initialization request unavailable") } return runRuntimeSetup(ctx, peer, identity, runtimeSetupOperation{Request: proto.RuntimePreparePayload{Action: "file", File: &proto.RuntimeInitialFile{Path: file.Path}}, Data: body}) } diff --git a/services/core/internal/execution/runtime_setup_test.go b/services/core/internal/execution/runtime_setup_test.go index 2bd9be1bb..5e6c5ac6c 100644 --- a/services/core/internal/execution/runtime_setup_test.go +++ b/services/core/internal/execution/runtime_setup_test.go @@ -10,6 +10,7 @@ import ( "github.com/MiniMax-AI/OpenAgentCore/internal/agentcapabilities" "github.com/MiniMax-AI/OpenAgentCore/internal/agentdaemon/proto" "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/environmentconfig" + "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/runtimegateway" "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/sessions" ) @@ -37,7 +38,7 @@ func TestRuntimeSetupReceiptOutcomes(t *testing.T) { } { t.Run(test.name, func(t *testing.T) { peer := &receiptRuntime{result: proto.RuntimePrepareResultPayload{Outcome: test.outcome, ExitCode: test.code}, err: test.err} - err := runRuntimeSetup(initializationTestContext(t), peer, agentcapabilities.Identity{}, runtimeSetupOperation{Request: proto.RuntimePreparePayload{Action: "initialize", Initialization: &proto.RuntimeInitialization{Action: "setup", Command: setupCanary}}}) + _, err := runRuntimeSetup(initializationTestContext(t), peer, agentcapabilities.Identity{}, runtimeSetupOperation{Request: proto.RuntimePreparePayload{Action: "initialize", Initialization: &proto.RuntimeInitialization{Action: "setup", Command: setupCanary}}}) if test.outcome == "completed" && test.err == nil { if err != nil { t.Fatal(err) @@ -74,14 +75,14 @@ func TestInitialFileUsesTypedRuntimeBytes(t *testing.T) { size := int64(len(body)) owner := agentcapabilities.Identity{EnvironmentID: "environment", SessionID: "session"} peer := &receiptRuntime{result: proto.RuntimePrepareResultPayload{Outcome: "completed"}} - if err := installInitialFile(initializationTestContext(t), peer, owner, environmentconfig.InitialFileMetadata{Path: "/workspace/a", SizeBytes: &size}, body); err != nil { + if _, err := installInitialFile(initializationTestContext(t), peer, owner, environmentconfig.InitialFileMetadata{Path: "/workspace/a", SizeBytes: &size}, body); err != nil { t.Fatal(err) } if peer.request.Action != "file" || peer.request.File.Path != "/workspace/a" || peer.request.EnvironmentID != owner.EnvironmentID || peer.request.SessionID != owner.SessionID || string(peer.data) != setupCanary { t.Fatal("file transport changed") } size++ - if err := installInitialFile(initializationTestContext(t), peer, owner, environmentconfig.InitialFileMetadata{SizeBytes: &size}, body); err == nil { + if _, err := installInitialFile(initializationTestContext(t), peer, owner, environmentconfig.InitialFileMetadata{SizeBytes: &size}, body); err == nil { t.Fatal("mismatched source size accepted") } } @@ -97,7 +98,7 @@ func TestRuntimeSetupUsesRemainingInitializationBudget(t *testing.T) { ctx := initializationTestContext(t) deadline, _ := ctx.Deadline() peer := &receiptRuntime{result: proto.RuntimePrepareResultPayload{Outcome: "completed"}} - err := runRuntimeSetup(ctx, peer, agentcapabilities.Identity{}, runtimeSetupOperation{}) + _, err := runRuntimeSetup(ctx, peer, agentcapabilities.Identity{}, runtimeSetupOperation{}) if err != nil { t.Fatal(err) } @@ -112,9 +113,58 @@ func TestRuntimeSetupUsesRemainingInitializationBudget(t *testing.T) { }()} { t.Run(name, func(t *testing.T) { peer := &receiptRuntime{} - if runRuntimeSetup(c, peer, agentcapabilities.Identity{}, runtimeSetupOperation{}) == nil || peer.request.BudgetMS != 0 { + if _, err := runRuntimeSetup(c, peer, agentcapabilities.Identity{}, runtimeSetupOperation{}); err == nil || peer.request.BudgetMS != 0 { t.Fatal("invalid budget sent") } }) } } + +func TestRuntimeSetupReportsStepTimingAndCategories(t *testing.T) { + setup := runtimeSetupOperation{Request: proto.RuntimePreparePayload{Action: "initialize", Initialization: &proto.RuntimeInitialization{Action: "setup"}}, Index: 3} + step, ok := setup.step(proto.RuntimePrepareResultPayload{Outcome: "completed", DurationMS: 5200}) + if !ok || step.Step != "setup" || step.Index == nil || *step.Index != 3 || step.DurationMS != 5200 { + t.Fatal("setup timing", step) + } + if step, ok = (runtimeSetupOperation{Request: proto.RuntimePreparePayload{Action: "finalize"}}).step(proto.RuntimePrepareResultPayload{Outcome: "failed", DurationMS: 7}); !ok || step.Step != "finalize" || step.Index != nil { + t.Fatal("finalize timing", step) + } + if _, ok = setup.step(proto.RuntimePrepareResultPayload{Outcome: "unknown"}); ok { + t.Fatal("unconfirmed operation reported as run") + } + for want, err := range map[sessions.ProvisioningCategory]error{ + sessions.ProvisioningTimeout: &unconfirmedError{cause: context.DeadlineExceeded}, + sessions.ProvisioningRuntimeDisconnected: &unconfirmedError{cause: runtimegateway.ErrSessionClosed}, + sessions.ProvisioningUnconfirmed: &unconfirmedError{}, + sessions.ProvisioningRejected: &runtimeStepFailure{rejected: true}, + sessions.ProvisioningOperationFailed: &runtimeStepFailure{}, + sessions.ProvisioningCoreError: sessions.ErrInvalidInput, + sessions.ProvisioningCoreRestart: errors.Join(errOwnershipLost, context.DeadlineExceeded), + } { + if got := provisioningCategory(err); got != want { + t.Fatalf("category %s, want %s", got, want) + } + } +} + +func TestRuntimeSetupLabelsAreDeclared(t *testing.T) { + setup := environmentconfig.Setup{ + Skills: []environmentconfig.Skill{{Metadata: environmentconfig.SkillMetadata{Type: "skill_reference", SkillID: "s", Version: "1", Name: "n", Description: "d"}}}, + Plugins: []environmentconfig.Plugin{{Metadata: proto.PluginMetadata{Type: "inline", Name: "p", Description: "d"}}}, + Commands: []environmentconfig.SetupCommand{{Command: "c"}}, + CapabilityDirectories: []string{"/workspace/generated"}, + } + setup.Packages.NPM, setup.Packages.Python = []string{"a"}, []string{"b"} + labels := map[sessions.InitializationLabel]bool{sessions.InitializationFile: true} + for _, operation := range setupOperations(setup) { + labels[operation.stepLabel()] = true + } + if len(labels) != len(sessions.InitializationLabels) { + t.Fatal("operations and declared labels differ", labels) + } + for _, label := range sessions.InitializationLabels { + if !labels[label] { + t.Fatal("undeclared or unproduced label", label) + } + } +} diff --git a/services/core/internal/persistence/postgres/sessionpg/execution_environment.go b/services/core/internal/persistence/postgres/sessionpg/execution_environment.go index de4bf3cd5..c99a98ab7 100644 --- a/services/core/internal/persistence/postgres/sessionpg/execution_environment.go +++ b/services/core/internal/persistence/postgres/sessionpg/execution_environment.go @@ -2,6 +2,7 @@ package sessionpg import ( "context" + "encoding/json" "errors" "github.com/google/uuid" @@ -104,6 +105,21 @@ func (t *environmentTx) CompleteInitialization(ctx context.Context, environment return count == 1, err } +func (t *environmentTx) RecordInitializationSteps(ctx context.Context, environment string, steps []sessions.InitializationStep) error { + id, err := parseID(environment) + if err != nil { + return err + } + if steps == nil { + steps = []sessions.InitializationStep{} + } + raw, err := json.Marshal(steps) + if err != nil { + return err + } + return t.q.RecordEnvironmentInitializationSteps(ctx, sqlc.RecordEnvironmentInitializationStepsParams{ID: id, Steps: raw}) +} + func (t *environmentTx) FailInitialization(ctx context.Context, environment string) error { id, err := parseID(environment) if err != nil { diff --git a/services/core/internal/persistence/postgres/sessionpg/session_reads.go b/services/core/internal/persistence/postgres/sessionpg/session_reads.go index dc0109247..a3982164d 100644 --- a/services/core/internal/persistence/postgres/sessionpg/session_reads.go +++ b/services/core/internal/persistence/postgres/sessionpg/session_reads.go @@ -292,6 +292,9 @@ func loadSessionActivity(ctx context.Context, q *sqlc.Queries, session sessions. } session.Environment = &value session.EnvironmentFailure = environmentFailure(environment.Environment) + if err := json.Unmarshal(environment.Environment.InitializationSteps, &session.EnvironmentInitializationSteps); err != nil { + return session, err + } state, err := LoadEnvironmentInput(ctx, q, id) if err != nil { return session, err diff --git a/services/core/internal/sessions/environment_termination.go b/services/core/internal/sessions/environment_termination.go index 2707b7457..b7225a44e 100644 --- a/services/core/internal/sessions/environment_termination.go +++ b/services/core/internal/sessions/environment_termination.go @@ -149,6 +149,10 @@ func TerminateEnvironment(ctx context.Context, tx EnvironmentTerminationTx, comp } termination := decideEnvironmentTermination(environment.Status, computeExpired) if termination == terminationFails { + if environment.Initialization == "complete" { + // The category describes a failed initialization, which this was not. + detail = nil + } return FailEnvironment(ctx, tx, environment, reason, detail) } return TrackInputActivity(ctx, tx, func(ctx context.Context) error { diff --git a/services/core/internal/sessions/execution_environment.go b/services/core/internal/sessions/execution_environment.go index 942c08b60..bee1eac57 100644 --- a/services/core/internal/sessions/execution_environment.go +++ b/services/core/internal/sessions/execution_environment.go @@ -64,6 +64,9 @@ type InitializationTx interface { // CompleteInitialization completes the running preparation of the live // Environment and reports whether it did. CompleteInitialization(ctx context.Context, environment string) (bool, error) + // RecordInitializationSteps stores the operation durations of the + // Environment's running preparation. + RecordInitializationSteps(ctx context.Context, environment string, steps []InitializationStep) error // FailInitialization marks the Environment's preparation failed unless it // completed. FailInitialization(ctx context.Context, environment string) error @@ -202,6 +205,14 @@ func journalInitialization(ctx context.Context, tx InitializationTx, environment return true, tx.AppendChanges(ctx, EnvironmentStateChange(environment.ID, kind, status)) } +// RecordEnvironmentInitializationSteps stores the operation durations of the +// claimed preparation, before it completes or fails. +func (o *ExecutionOperations) RecordEnvironmentInitializationSteps(ctx context.Context, owner EnvironmentInitialization, steps []InitializationStep) error { + return o.withInitialization(ctx, owner, func(ctx context.Context, tx InitializationTx, environment Environment) error { + return tx.RecordInitializationSteps(ctx, environment.ID, steps) + }) +} + // FailEnvironmentInitialization records the failure of a preparation that did // not complete and fails the Environment, as FailEnvironment reports it. It // records state and settles work; it never destroys compute or a workspace. diff --git a/services/core/internal/sessions/execution_environment_test.go b/services/core/internal/sessions/execution_environment_test.go index 286673b55..f8af313ca 100644 --- a/services/core/internal/sessions/execution_environment_test.go +++ b/services/core/internal/sessions/execution_environment_test.go @@ -24,6 +24,10 @@ func (f *fakeTx) CompleteInitialization(_ context.Context, environment string) ( return f.completeInitialization() } +func (f *fakeTx) RecordInitializationSteps(context.Context, string, []InitializationStep) error { + return nil +} + func (f *fakeTx) FailInitialization(_ context.Context, environment string) error { f.record("FailInitialization", f.failInitialization != nil, environment) return f.failInitialization() diff --git a/services/core/internal/sessions/provisioning.go b/services/core/internal/sessions/provisioning.go index da5882344..5230f8d89 100644 --- a/services/core/internal/sessions/provisioning.go +++ b/services/core/internal/sessions/provisioning.go @@ -2,6 +2,7 @@ package sessions import ( "fmt" + "slices" "time" ) @@ -16,9 +17,10 @@ type EnvironmentFailure struct { // ProvisioningFailureDetail is private, fixed-category evidence from a confirmed // initialization receipt. It never contains command text, paths or Runtime output. type ProvisioningFailureDetail struct { - Step *string `json:"step"` - Index *int `json:"index"` - ExitCode *int `json:"exit_code"` + Step *string `json:"step"` + Index *int `json:"index"` + ExitCode *int `json:"exit_code"` + Category *ProvisioningCategory `json:"category,omitempty"` } // ProvisioningFailureReason is the safe reason for an Environment that @@ -26,6 +28,64 @@ type ProvisioningFailureDetail struct { // old receipts, bootstrap rejection and Core restart during initialization. const ProvisioningFailureReason = "Failed to provision environment: initialization did not complete" +// ProvisioningCategory classifies an Environment that failed without a confirmed +// failed step. It is recorded privately beside the generic public reason. +type ProvisioningCategory string + +const ( + // ProvisioningTimeout: the initialization budget or a transfer budget expired. + ProvisioningTimeout ProvisioningCategory = "timeout" + // ProvisioningRuntimeDisconnected: the Runtime connection closed or changed. + ProvisioningRuntimeDisconnected ProvisioningCategory = "runtime_disconnected" + // ProvisioningUnconfirmed: the effect of an operation is unknown or its receipt is missing or invalid. + ProvisioningUnconfirmed ProvisioningCategory = "unconfirmed" + // ProvisioningRejected: the Runtime refused an operation before applying it. + ProvisioningRejected ProvisioningCategory = "rejected" + // ProvisioningOperationFailed: the Runtime confirmed failure of an operation with no public step label. + ProvisioningOperationFailed ProvisioningCategory = "operation_failed" + // ProvisioningCoreError: Core failed to read, validate or record initialization state. + ProvisioningCoreError ProvisioningCategory = "core_error" + // ProvisioningCoreRestart: Core lost ownership of the initialization, by restart or lease loss. + ProvisioningCoreRestart ProvisioningCategory = "core_restart" + // ProvisioningComputeReleased: the sandbox was released or never created before initialization completed. + ProvisioningComputeReleased ProvisioningCategory = "compute_released" +) + +// ProvisioningCategories is the one authored category set. The shared fixture +// testdata/provisioning-categories.json checks the client and Web projections. +var ProvisioningCategories = []ProvisioningCategory{ + ProvisioningTimeout, ProvisioningRuntimeDisconnected, ProvisioningUnconfirmed, ProvisioningRejected, + ProvisioningOperationFailed, ProvisioningCoreError, ProvisioningCoreRestart, ProvisioningComputeReleased, +} + +// InitializationLabel is the fixed label of one initialization operation in step timing. +type InitializationLabel string + +const ( + InitializationFile InitializationLabel = "file" + InitializationSkill InitializationLabel = "skill" + InitializationPlugin InitializationLabel = "plugin" + InitializationConfigure InitializationLabel = "configure" + InitializationNPM InitializationLabel = "npm" + InitializationPython InitializationLabel = "python" + InitializationSetup InitializationLabel = "setup" + InitializationFinalize InitializationLabel = "finalize" +) + +// InitializationLabels is the one authored label set; the diagnostics OpenAPI enum is checked against it. +var InitializationLabels = []InitializationLabel{ + InitializationFile, InitializationSkill, InitializationPlugin, InitializationConfigure, + InitializationNPM, InitializationPython, InitializationSetup, InitializationFinalize, +} + +// InitializationStep is the Runtime-reported duration of one initialization +// operation that ran. Step is a fixed label and Index is set for setup commands. +type InitializationStep struct { + Step InitializationLabel `json:"step"` + Index *int `json:"index"` + DurationMS int64 `json:"duration_ms"` +} + // Provisioning step kinds for ProvisioningFailure.Step. const ( ProvisioningSetupCommand = "setup" @@ -39,10 +99,12 @@ const ( // ProvisioningFailure identifies a confirmed failed initialization step. // It cannot carry Runtime output: Step selects a fixed label, Index is the setup // command position and ExitCode is the Runtime-reported status (0 when absent). +// Category classifies a failure without a confirmed step. type ProvisioningFailure struct { Step string Index int ExitCode int + Category ProvisioningCategory } // Reason renders the public Session error. The setup_commands and Python package @@ -72,14 +134,25 @@ func (f ProvisioningFailure) Reason() string { // Detail is the private evidence recorded with the failure. func (f ProvisioningFailure) Detail() *ProvisioningFailureDetail { - return SanitizedProvisioningDetail(ProvisioningFailureDetail{Step: &f.Step, Index: &f.Index, ExitCode: &f.ExitCode}) + detail := ProvisioningFailureDetail{Step: &f.Step, Index: &f.Index, ExitCode: &f.ExitCode} + if f.Step == "" { + detail.Step = nil + if f.Category != "" { + detail.Category = &f.Category + } + } + return SanitizedProvisioningDetail(detail) } // SanitizedProvisioningDetail keeps only the fields the step's category allows -// and returns nil for a missing or unknown step. +// and returns nil for a missing or unknown step without a known category. func SanitizedProvisioningDetail(f ProvisioningFailureDetail) *ProvisioningFailureDetail { if f.Step == nil { - return nil + if f.Category == nil || !slices.Contains(ProvisioningCategories, *f.Category) { + return nil + } + value := *f.Category + return &ProvisioningFailureDetail{Category: &value} } result := &ProvisioningFailureDetail{} switch *f.Step { diff --git a/services/core/internal/sessions/provisioning_test.go b/services/core/internal/sessions/provisioning_test.go index 90ecbc499..e0af72d00 100644 --- a/services/core/internal/sessions/provisioning_test.go +++ b/services/core/internal/sessions/provisioning_test.go @@ -1,6 +1,11 @@ package sessions -import "testing" +import ( + "encoding/json" + "os" + "slices" + "testing" +) // Reasons contain only a fixed label and an exit status. Setup and Python labels // match official samples; npm, system, file and Skill labels are unverified. @@ -25,3 +30,21 @@ func TestProvisioningFailureReasons(t *testing.T) { } } } + +func TestProvisioningCategoriesMatchSharedFixture(t *testing.T) { + raw, err := os.ReadFile("testdata/provisioning-categories.json") + if err != nil { + t.Fatal(err) + } + var fixture []string + if err := json.Unmarshal(raw, &fixture); err != nil { + t.Fatal(err) + } + var declared []string + for _, category := range ProvisioningCategories { + declared = append(declared, string(category)) + } + if !slices.Equal(fixture, declared) { + t.Fatal("fixture differs from the declared categories", fixture, declared) + } +} diff --git a/services/core/internal/sessions/session.go b/services/core/internal/sessions/session.go index dddf2e0c0..e2cad8b4c 100644 --- a/services/core/internal/sessions/session.go +++ b/services/core/internal/sessions/session.go @@ -35,6 +35,9 @@ type Session struct { // EnvironmentFailure is the recorded provisioning failure of a failed hosted // Environment. It makes the Session failed and is terminal. EnvironmentFailure *EnvironmentFailure + // EnvironmentInitializationSteps are the durations the Runtime reported for + // the operations of the Environment's initialization. + EnvironmentInitializationSteps []InitializationStep // PendingInput reports that the latest input reservation, read once no Turn // is active or newer, can still start a Turn. It only supports settlement // checks and is never rendered. diff --git a/services/core/internal/sessions/testdata/provisioning-categories.json b/services/core/internal/sessions/testdata/provisioning-categories.json new file mode 100644 index 000000000..803556ed8 --- /dev/null +++ b/services/core/internal/sessions/testdata/provisioning-categories.json @@ -0,0 +1,10 @@ +[ + "timeout", + "runtime_disconnected", + "unconfirmed", + "rejected", + "operation_failed", + "core_error", + "core_restart", + "compute_released" +] diff --git a/services/core/migrations/000009_environment_initialization_steps.sql b/services/core/migrations/000009_environment_initialization_steps.sql new file mode 100644 index 000000000..7ceecb17f --- /dev/null +++ b/services/core/migrations/000009_environment_initialization_steps.sql @@ -0,0 +1,4 @@ +-- +goose Up +ALTER TABLE environments + ADD COLUMN initialization_steps jsonb NOT NULL DEFAULT '[]'::jsonb, + ADD CONSTRAINT environments_initialization_steps_check CHECK (jsonb_typeof(initialization_steps) = 'array'); diff --git a/services/core/tests/integration/session_diagnostics_test.go b/services/core/tests/integration/session_diagnostics_test.go index 7f097b231..8b185ffd2 100644 --- a/services/core/tests/integration/session_diagnostics_test.go +++ b/services/core/tests/integration/session_diagnostics_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "reflect" "strings" "testing" "time" @@ -254,6 +255,38 @@ func TestDiagnosticProvisioningDetailAtomicAndPrivate(t *testing.T) { } } +func TestDiagnosticInitializationStepsAndFailureCategory(t *testing.T) { + s, installation := configuredStore(t) + tenant := uuid.NewString() + session, err := s.CreateSession(t.Context(), tenant, environmentInput("step-timing", "openai_hosted", "/workspace")) + if err != nil { + t.Fatal(err) + } + writer := executionWriter(t, s) + owner, err := deploymentExecution(t, writer).ReserveAllocation(t.Context(), deployment.AllocationKey{TenantID: tenant, EnvironmentID: session.Environment.ID}, installation, runtimedevice.HashCredential(uuid.NewString())) + if err != nil { + t.Fatal(err) + } + runtimeSuspensionSQL(t, s.pool, "UPDATE environments SET initialization='running' WHERE id=$1", owner.EnvironmentID) + preparation := sessions.EnvironmentInitialization{EnvironmentID: owner.EnvironmentID, SessionID: owner.SessionID, TenantID: owner.TenantID, DeviceID: owner.DeviceID} + index := 1 + steps := []sessions.InitializationStep{{Step: "npm", DurationMS: 4100}, {Step: "setup", Index: &index, DurationMS: 5200}} + execution := sessionExecution(t, writer.lease) + if err = execution.RecordEnvironmentInitializationSteps(t.Context(), preparation, steps); err != nil { + t.Fatal(err) + } + if err = execution.FailEnvironmentInitialization(t.Context(), preparation, sessions.ProvisioningFailure{Category: sessions.ProvisioningTimeout}); err != nil { + t.Fatal(err) + } + snap, err := sessionAdapter(s).GetSession(t.Context(), tenant, session.ID) + if err != nil || !reflect.DeepEqual(snap.EnvironmentInitializationSteps, steps) { + t.Fatal("steps not persisted", snap.EnvironmentInitializationSteps, err) + } + if failure := snap.EnvironmentFailure; failure == nil || failure.Reason != sessions.ProvisioningFailureReason || failure.Detail == nil || failure.Detail.Step != nil || *failure.Detail.Category != sessions.ProvisioningTimeout { + t.Fatal("category not persisted beside the generic reason", snap.EnvironmentFailure) + } +} + func TestDiagnosticPutItemRollsBack(t *testing.T) { s, pool := testStore(t) tenant, session := newTurnSession(t, s) From a8ee0cc70055f3bfce69e44eccb8ad746a7ea4ef Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 14:47:40 +0800 Subject: [PATCH 12/84] Accept HTTP model providers on loopback and private addresses (#868) * Accept HTTP model providers on loopback and private addresses A model provider base_url may now use HTTP when its host is a loopback or private IP address, so a local or LAN gateway works without a TLS terminator. A host name still needs HTTPS, because it can resolve to any address. Core admission and the Runtime's frozen-bundle check share the one rule in internal/modelprovider. Closes #416. * Keep the client's base_url check no stricter than Core * Leave the HTTP host rule to Core in the provider dialog test * Describe the HTTP host rule in the provider hint --- apps/web/e2e/system.spec.ts | 2 +- .../src/features/system/ModelProviderDialog.tsx | 6 +++--- apps/web/src/i18n/locales/en/core-errors.ts | 2 +- apps/web/src/i18n/locales/en/system.ts | 2 +- apps/web/src/i18n/locales/zh-CN/core-errors.ts | 2 +- apps/web/src/i18n/locales/zh-CN/system.ts | 2 +- contracts/agents-api/core-errors.md | 2 +- contracts/agents-api/model-execution.md | 2 +- contracts/agents-api/v1/model_execution.go | 2 +- contracts/agents-api/v1/model_execution_test.go | 5 +++-- .../agents-api/v1/model_provider_admission.go | 6 +++--- .../agents-api/v1/model_provider_error_test.go | 2 +- contracts/agents-api/zh/core-errors.md | 4 ++-- contracts/agents-api/zh/model-execution.md | 4 ++-- internal/modelprovider/config.go | 15 ++++++++++++--- packages/agents-client/src/admin-client.test.ts | 6 +++--- .../src/execution-configuration-projection.ts | 7 ++++--- .../api/model_provider_public_validation_test.go | 2 +- 18 files changed, 42 insertions(+), 31 deletions(-) diff --git a/apps/web/e2e/system.spec.ts b/apps/web/e2e/system.spec.ts index cf4277fac..bf8b30f15 100644 --- a/apps/web/e2e/system.spec.ts +++ b/apps/web/e2e/system.spec.ts @@ -30,7 +30,7 @@ test("sets, replaces and clears a harness's default model configuration, and kee await set.getByLabel("Default model ID").fill("fixture-model"); await expect(set).toContainText("Used for new Sessions when the application does not specify a model."); // Every rejected URL stays local; Enter cannot bypass validation or write a secret. - for (const url of ["http://model.example/v1", "ftp://model.example", "https://user:password@model.example/v1", "https://@model.example/v1", "https:model.example/v1", "https://model.example/v1?token=x", "https://model.example/v1#fragment", "https://model.example/v1?", "https://model.example/v1#", "not a URL"]) { + for (const url of ["ftp://model.example", "https://user:password@model.example/v1", "https://@model.example/v1", "https:model.example/v1", "https://model.example/v1?token=x", "https://model.example/v1#fragment", "https://model.example/v1?", "https://model.example/v1#", "not a URL"]) { await set.getByLabel("Base URL").fill(url); await expect(set.getByLabel("Base URL")).toHaveAttribute("aria-invalid", "true"); await expect(set.getByRole("button", { name: "Save", exact: true })).toBeDisabled(); diff --git a/apps/web/src/features/system/ModelProviderDialog.tsx b/apps/web/src/features/system/ModelProviderDialog.tsx index b62a876ff..ca4ac082c 100644 --- a/apps/web/src/features/system/ModelProviderDialog.tsx +++ b/apps/web/src/features/system/ModelProviderDialog.tsx @@ -27,8 +27,8 @@ function tokenLimit(text: string): { value: number | undefined; problem: "whole" function isProviderUrl(value: string): boolean { try { const url = new URL(value); - const authority = /^https:\/\/([^/]+)/iu.exec(value)?.[1]; - return authority !== undefined && url.protocol === "https:" && url.hostname !== "" && !authority.includes("@") + const authority = /^https?:\/\/([^/]+)/iu.exec(value)?.[1]; + return authority !== undefined && (url.protocol === "https:" || url.protocol === "http:") && url.hostname !== "" && !authority.includes("@") && !/[\\\s?#]/u.test(value); } catch { return false; @@ -38,7 +38,7 @@ function isProviderUrl(value: string): boolean { /** * Sets or replaces one harness's model configuration. Non-secret fields start from the * current provider; the API key never does. The protocol describes the upstream - * model provider. The form checks the HTTPS provider URL and whole-number + * model provider. The form checks the provider URL's shape and whole-number * limits within Core's range, with max output no larger than the context window. * Core's typed rejection is shown beside its field, or beside the form * when no editable field applies. Enter saves; a save in flight blocks another. diff --git a/apps/web/src/i18n/locales/en/core-errors.ts b/apps/web/src/i18n/locales/en/core-errors.ts index 2dd7c8fe1..48d6b906a 100644 --- a/apps/web/src/i18n/locales/en/core-errors.ts +++ b/apps/web/src/i18n/locales/en/core-errors.ts @@ -16,7 +16,7 @@ export const coreErrors = { "model_configuration_model_invalid": "Enter a model ID of at most 1024 UTF-8 bytes without control characters.", "harness_config_invalid": "Check the supported native fields and their values. The JSON object must be at most 16 KiB and cannot redefine Core-managed settings.", "invalid_model_provider": "Enter the complete model provider configuration.", - "model_provider_base_url_invalid": "Use an HTTPS URL without credentials, query parameters or a fragment.", + "model_provider_base_url_invalid": "Use an HTTPS URL, or HTTP to a loopback or private IP address, without credentials, query parameters or a fragment.", "model_provider_protocol_unsupported": "This protocol is not supported by the Harness.", "model_provider_api_key_invalid": "Enter a valid API key without control characters.", "model_provider_token_limits_invalid": "Use valid token limits; output cannot exceed context.", diff --git a/apps/web/src/i18n/locales/en/system.ts b/apps/web/src/i18n/locales/en/system.ts index c5230056a..48845e78d 100644 --- a/apps/web/src/i18n/locales/en/system.ts +++ b/apps/web/src/i18n/locales/en/system.ts @@ -78,7 +78,7 @@ export const system = { setTitle: "Set default model configuration for {{harness}}", replaceTitle: "Replace default model configuration for {{harness}}", modelName: "Used for new Sessions when the application does not specify a model. Enter an exact model ID accepted by this provider.", - baseUrlInvalid: "Enter an HTTPS URL with a hostname and no credentials, query or fragment, such as https://api.example.com/v1.", + baseUrlInvalid: "Enter an HTTPS URL, or an HTTP URL to a loopback or private IP address, with no credentials, query or fragment, such as https://api.example.com/v1.", apiKeyHelp: "Required every time. Core encrypts it and never shows it again.", contextHelp: "The model's context window, in tokens. Optional.", outputHelp: "The most tokens the model writes in one response. Optional; it needs a context window at least as large.", diff --git a/apps/web/src/i18n/locales/zh-CN/core-errors.ts b/apps/web/src/i18n/locales/zh-CN/core-errors.ts index 957ee9144..cd4120883 100644 --- a/apps/web/src/i18n/locales/zh-CN/core-errors.ts +++ b/apps/web/src/i18n/locales/zh-CN/core-errors.ts @@ -15,7 +15,7 @@ export const coreErrors = { "model_configuration_model_invalid": "请输入模型 ID,最多 1024 个 UTF-8 字节,且不能包含控制字符。", "harness_config_invalid": "请检查支持的原生字段及其取值。JSON 对象不能超过 16 KiB,也不能重复定义 Core 管理的设置。", "invalid_model_provider": "请填写完整的模型提供商配置。", - "model_provider_base_url_invalid": "请使用 HTTPS 地址,不要包含凭据、查询参数或片段。", + "model_provider_base_url_invalid": "请使用 HTTPS 地址(回环或私有 IP 地址也可以用 HTTP),不要包含凭据、查询参数或片段。", "model_provider_protocol_unsupported": "此 Harness 不支持该协议。", "model_provider_api_key_invalid": "请输入有效的 API 密钥,不要包含控制字符。", "model_provider_token_limits_invalid": "请填写有效的 token 限制;输出不能超过上下文。", diff --git a/apps/web/src/i18n/locales/zh-CN/system.ts b/apps/web/src/i18n/locales/zh-CN/system.ts index 7e63fcb06..b2ee52295 100644 --- a/apps/web/src/i18n/locales/zh-CN/system.ts +++ b/apps/web/src/i18n/locales/zh-CN/system.ts @@ -80,7 +80,7 @@ export const system: TranslationShape = { setTitle: "设置 {{harness}} 的默认模型配置", replaceTitle: "替换 {{harness}} 的默认模型配置", modelName: "应用未指定模型时,新 Session 使用此模型。请填写该服务接受的准确模型 ID。", - baseUrlInvalid: "请输入包含主机名、不含账号密码、查询参数或片段的 HTTPS URL,例如 https://api.example.com/v1。", + baseUrlInvalid: "请输入 HTTPS URL,或指向回环、私有 IP 地址的 HTTP URL,不含账号密码、查询参数或片段,例如 https://api.example.com/v1。", apiKeyHelp: "每次都必须填写。Core 会加密保存,之后不再显示。", contextHelp: "模型的上下文窗口,单位为 token。可选。", outputHelp: "模型单次回复最多输出的 token 数。可选;填写时,上下文窗口必须不小于它。", diff --git a/contracts/agents-api/core-errors.md b/contracts/agents-api/core-errors.md index 297a2a711..624b6d3fd 100644 --- a/contracts/agents-api/core-errors.md +++ b/contracts/agents-api/core-errors.md @@ -58,7 +58,7 @@ Each code returns HTTP 400 with `type: "invalid_request_error"`. A missing, malf | `invalid_name` | `name` | `max_length`: 128 for Projects and nodes, 80 for Project keys | The name failed the resource's validator | | `invalid_node_capacity` | `max_active` or `max_retained` | `min`: 1, `max`: 1000000 | Capacity is invalid; retained capacity must also be at least active capacity | | `invalid_model_provider` | null | omitted | A complete model-provider bundle is required | -| `model_provider_base_url_invalid` | `base_url` | omitted | Requires HTTPS without credentials, query or fragment | +| `model_provider_base_url_invalid` | `base_url` | omitted | Requires HTTPS, or HTTP to a loopback or private IP address, without credentials, query or fragment | | `model_provider_protocol_unsupported` | `protocol` | `harness` and `allowed_protocols`, from the build's adapter catalog | The protocol is unknown or unsupported by the selected Harness | | `model_provider_api_key_invalid` | `api_key` | `max_length`: 16384 | The key is empty, too long or contains a prohibited character | | `model_provider_token_limits_invalid` | `context_window` or `max_output_tokens` | omitted | A limit is negative, `max_output_tokens` exceeds a set `context_window`, or the Harness has no native setting for a set limit | diff --git a/contracts/agents-api/model-execution.md b/contracts/agents-api/model-execution.md index 4b90470d7..2d8200b37 100644 --- a/contracts/agents-api/model-execution.md +++ b/contracts/agents-api/model-execution.md @@ -11,7 +11,7 @@ A Harness receives one frozen model provider bundle, defined by [`modelprovider. | Field | Meaning | | --- | --- | | `protocol` | The upstream API: `anthropic`, `responses` or `chat_completions`, not an engine. The selected Harness must support it natively | -| `base_url` | An HTTPS URL with a valid host, without credentials, query or fragment | +| `base_url` | An HTTPS URL with a valid host, or an HTTP URL whose host is a loopback or private IP address, without credentials, query or fragment. Loopback is the machine the Harness runs on: in a Core-managed sandbox, the sandbox itself | | `api_key` | Nonempty, at most 16 KiB, without NUL, CR or LF | | `context_window`, `max_output_tokens` | Optional nonnegative integers, with output no larger than context. Use the real model's limits | diff --git a/contracts/agents-api/v1/model_execution.go b/contracts/agents-api/v1/model_execution.go index e193af040..a94782269 100644 --- a/contracts/agents-api/v1/model_execution.go +++ b/contracts/agents-api/v1/model_execution.go @@ -43,7 +43,7 @@ func (p *ModelProviderInput) validate(registry harnessconfig.Registry) error { return &ModelProviderError{Code: "invalid_model_provider", Param: "", message: "model_provider is required"} } if !validModelProviderBaseURL(p.BaseURL) { - return &ModelProviderError{Code: "model_provider_base_url_invalid", Param: "base_url", message: "model provider requires an HTTPS base_url without credentials, query or fragment"} + return &ModelProviderError{Code: "model_provider_base_url_invalid", Param: "base_url", message: "model provider requires an HTTPS base_url, or HTTP to a loopback or private IP address, without credentials, query or fragment"} } if !registry.SupportsProtocol(string(p.Protocol)) { return &ModelProviderError{Code: "model_provider_protocol_unsupported", Param: "protocol", message: "unsupported model provider protocol"} diff --git a/contracts/agents-api/v1/model_execution_test.go b/contracts/agents-api/v1/model_execution_test.go index b6ddb0526..b801c99c0 100644 --- a/contracts/agents-api/v1/model_execution_test.go +++ b/contracts/agents-api/v1/model_execution_test.go @@ -32,13 +32,14 @@ func TestModelExecutionValidation(t *testing.T) { t.Fatalf("unsupported protocol or harness accepted: %s/%s", tc.protocol, tc.harness) } } - for _, url := range []string{"http://example.com", "https://user:pass@example.com", "https://example.com?key=secret", "https://example.com#secret", "https://", + for _, url := range []string{"http://example.com", "http://8.8.8.8/v1", "http://169.254.169.254/v1", "http://localhost:7351/v1", "https://user:pass@example.com", "https://example.com?key=secret", "https://example.com#secret", "https://", "https://example.com:99999/v1", "https://example.com:0/v1", "https://xn--.test", "https://xn--a.test", "https://a..b", "https://999.1.1.1"} { if (&ModelProviderInput{Protocol: "responses", BaseURL: url, APIKey: "secret"}).Validate() == nil { t.Fatal("unsafe or unusable provider URL accepted", url) } } - for _, url := range []string{"https://example.com:8443/v1", "https://127.0.0.1/v1", "https://[::1]:8443/v1", "https://model_gateway.internal/v1", "https://bücher.example/v1"} { + for _, url := range []string{"https://example.com:8443/v1", "https://127.0.0.1/v1", "https://[::1]:8443/v1", "https://model_gateway.internal/v1", "https://bücher.example/v1", + "http://127.0.0.1:7351/v1", "http://10.0.0.5:8080/v1", "http://[fd00::1]:8080/v1"} { if err := (&ModelProviderInput{Protocol: "responses", BaseURL: url, APIKey: "secret"}).Validate(); err != nil { t.Fatal("valid provider URL rejected", url, err) } diff --git a/contracts/agents-api/v1/model_provider_admission.go b/contracts/agents-api/v1/model_provider_admission.go index d1b0d3f1e..190551d18 100644 --- a/contracts/agents-api/v1/model_provider_admission.go +++ b/contracts/agents-api/v1/model_provider_admission.go @@ -7,9 +7,9 @@ import ( "strings" "golang.org/x/net/idna" -) -const providerScheme = "https" + "github.com/MiniMax-AI/OpenAgentCore/internal/modelprovider" +) // providerHost converts a domain as URL host parsing does (UTS #46 without // hyphen or STD3 restrictions), rejecting invalid labels such as bad punycode. @@ -45,7 +45,7 @@ func ModelProviderRequired(environment string) bool { func validModelProviderBaseURL(base string) bool { u, err := url.Parse(base) - return err == nil && u.Scheme == providerScheme && validModelProviderHost(u) && u.User == nil && u.RawQuery == "" && u.Fragment == "" && !strings.ContainsAny(base, "\x00\r\n") + return err == nil && modelprovider.SchemeAllowed(u) && validModelProviderHost(u) && u.User == nil && u.RawQuery == "" && u.Fragment == "" && !strings.ContainsAny(base, "\x00\r\n") } // validModelProviderHost requires a usable host: an IP address, or a domain diff --git a/contracts/agents-api/v1/model_provider_error_test.go b/contracts/agents-api/v1/model_provider_error_test.go index 3952c6f30..1b00b3d5c 100644 --- a/contracts/agents-api/v1/model_provider_error_test.go +++ b/contracts/agents-api/v1/model_provider_error_test.go @@ -11,7 +11,7 @@ func TestModelProviderErrorMessagesAndPrecedence(t *testing.T) { name, harness, code, param, message string change func(*ModelProviderInput) }{ - {"url first", "codex", "model_provider_base_url_invalid", "base_url", "model provider requires an HTTPS base_url without credentials, query or fragment", func(p *ModelProviderInput) { + {"url first", "codex", "model_provider_base_url_invalid", "base_url", "model provider requires an HTTPS base_url, or HTTP to a loopback or private IP address, without credentials, query or fragment", func(p *ModelProviderInput) { p.BaseURL = "http://private.example" p.Protocol = "private" p.APIKey = "" diff --git a/contracts/agents-api/zh/core-errors.md b/contracts/agents-api/zh/core-errors.md index 63260327f..56cedb10e 100644 --- a/contracts/agents-api/zh/core-errors.md +++ b/contracts/agents-api/zh/core-errors.md @@ -1,7 +1,7 @@ --- title: "Core 管理错误" source: contracts/agents-api/core-errors.md -source_hash: f2c2a927b8faad9c2834ae4d1195940195df5fc617c8395a027f0d21dfb5ea1e +source_hash: 1424dc3288c244cb3be78bb2070530bdc0b5aec8474c1ab943611bee335fdca7 --- `/core/v1` 上的错误使用此封装结构。`message` 是安全的英文文本;`code` 和 `param` 可以为 null。客户端依据稳定的 `code` 和可选的 `param` 进行处理,对未知代码显示 `message`,绝不解析消息,也绝不自动重试被拒绝的写操作。 @@ -60,7 +60,7 @@ Web 的控制台服务器在 `/core` 路径上发生自身故障时使用此封 | `invalid_name` | `name` | `max_length`:项目和节点为 128,项目 API 密钥为 80 | 名称未通过相应资源的验证器 | | `invalid_node_capacity` | `max_active` 或 `max_retained` | `min`:1,`max`:1000000 | 容量无效;保留容量还必须至少等于活动容量 | | `invalid_model_provider` | null | 省略 | 必须提供完整的模型提供商配置包 | -| `model_provider_base_url_invalid` | `base_url` | 省略 | 必须使用 HTTPS,且不得包含凭据、查询或片段 | +| `model_provider_base_url_invalid` | `base_url` | 省略 | 必须使用 HTTPS(回环或私有 IP 地址也可以用 HTTP),且不得包含凭据、查询或片段 | | `model_provider_protocol_unsupported` | `protocol` | `harness` 和 `allowed_protocols`,来自该构建的适配器目录 | 协议未知,或所选 Harness 不支持该协议 | | `model_provider_api_key_invalid` | `api_key` | `max_length`:16384 | 密钥为空、过长或包含禁止字符 | | `model_provider_token_limits_invalid` | `context_window` 或 `max_output_tokens` | 省略 | 限制为负数、`max_output_tokens` 超过已设置的 `context_window`,或 Harness 没有已设置限制的原生设置 | diff --git a/contracts/agents-api/zh/model-execution.md b/contracts/agents-api/zh/model-execution.md index 3725b5aba..2643dd36c 100644 --- a/contracts/agents-api/zh/model-execution.md +++ b/contracts/agents-api/zh/model-execution.md @@ -1,7 +1,7 @@ --- title: "模型执行" source: contracts/agents-api/model-execution.md -source_hash: 2ac821cd3d4635e6780e3cf517298225036a6d24317d1375bfdc44789959f55a +source_hash: d33f9a9919e52136f8ece0a8480c1db059f2f35aa1cefa852ba1d001cc259fa2 --- 每个 Session 都运行一个 Harness,并使用一个模型提供商。Core 通过三个固定版本上游协议未定义的 Core 扩展来选择它们:`x_agents_core.harness` 选择 Harness,`x_agents_core.model_provider` 提供端点和密钥,`x_agents_core.harness_config` 携带原生模型参数。Core 没有提供商目录、模型别名解析或产品权限模型;除 Session 和已保存 Agent 配置包外,唯一存储的配置包是每个 Harness 的一个 [deployment default](#deployment-defaults)。本文档定义 Harness—模型提供商协议:[`internal/modelprovider/config.go`](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/internal/modelprovider/config.go) 负责验证冻结的提供商连接,每个 Harness 则通过 [`internal/harnessconfig/harness.go`](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/internal/harnessconfig/harness.go) 声明其协议和原生参数。 @@ -13,7 +13,7 @@ Harness 接收一个冻结的模型提供商配置包,其定义见 [`modelprov | 字段 | 含义 | | --- | --- | | `protocol` | 上游 API:`anthropic`、`responses` 或 `chat_completions`,而不是引擎。所选 Harness 必须原生支持它 | -| `base_url` | 带有效主机名的 HTTPS URL,不得包含凭据、查询参数或片段 | +| `base_url` | 带有效主机名的 HTTPS URL,或主机为回环或私有 IP 地址的 HTTP URL,不得包含凭据、查询参数或片段。回环地址指 Harness 所在的机器:在 Core 管理的沙箱中就是沙箱本身 | | `api_key` | 不得为空,最长 16 KiB,不得包含 NUL、CR 或 LF | | `context_window`、`max_output_tokens` | 可选的非负整数,输出限制不得大于上下文限制。请使用真实模型的限制 | diff --git a/internal/modelprovider/config.go b/internal/modelprovider/config.go index 95d10fcfd..0e695e373 100644 --- a/internal/modelprovider/config.go +++ b/internal/modelprovider/config.go @@ -62,9 +62,7 @@ func (p Provider) Validate() error { if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || strings.ContainsAny(p.BaseURL, "\x00\r\n") { return ErrConfiguration } - // Remote providers require HTTPS. Runtime-local providers may use loopback - // HTTP; Core retains stricter public provider admission. - if u.Scheme != "https" && !(u.Scheme == "http" && net.ParseIP(u.Hostname()).IsLoopback()) { + if !SchemeAllowed(u) { return ErrConfiguration } if strings.TrimSpace(p.APIKey) == "" || len(p.APIKey) > 16384 || strings.ContainsAny(p.APIKey, "\x00\r\n") { @@ -76,6 +74,17 @@ func (p Provider) Validate() error { return nil } +// SchemeAllowed is the one base URL scheme rule: HTTPS, or HTTP to a loopback +// or private IP address, so the key never crosses a public network in plain +// text. A host name never qualifies for HTTP, because it can resolve anywhere. +func SchemeAllowed(u *url.URL) bool { + if u.Scheme == "https" { + return true + } + ip := net.ParseIP(u.Hostname()) + return u.Scheme == "http" && ip != nil && (ip.IsLoopback() || ip.IsPrivate()) +} + // TokenLimitsValid holds the token-limit rule: unset is zero, and an output // limit never exceeds a set context window. func TokenLimitsValid(contextWindow, maxOutputTokens int32) bool { diff --git a/packages/agents-client/src/admin-client.test.ts b/packages/agents-client/src/admin-client.test.ts index 541650322..e40ad125a 100644 --- a/packages/agents-client/src/admin-client.test.ts +++ b/packages/agents-client/src/admin-client.test.ts @@ -165,7 +165,7 @@ describe("AdminClient transport boundary", () => { const input = { model: "test-model", harness_config: {}, model_provider: { protocol: "responses", base_url: "https://model.example/v1", api_key: "write-only", context_window: 200000, max_output_tokens: 8000 } } as const; expect(await client.setHarnessModelConfiguration("codex", input)).toEqual(provider); expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual(input); - for (const unsafe of [{ ...provider, api_key: "leak" }, { ...provider, harness: "mcode" }, { ...provider, model_provider: { ...provider.model_provider, api_key_configured: false } }, { ...provider, model_provider: { ...provider.model_provider, base_url: "http://model.example/v1" } }, { ...provider, model_provider: { ...provider.model_provider, api_key: "leak" } }, { ...provider, model: "" }, { ...provider, harness_config: [] }, { ...provider, extra: 1 }]) { + for (const unsafe of [{ ...provider, api_key: "leak" }, { ...provider, harness: "mcode" }, { ...provider, model_provider: { ...provider.model_provider, api_key_configured: false } }, { ...provider, model_provider: { ...provider.model_provider, base_url: "ftp://model.example/v1" } }, { ...provider, model_provider: { ...provider.model_provider, api_key: "leak" } }, { ...provider, model: "" }, { ...provider, harness_config: [] }, { ...provider, extra: 1 }]) { await expect(clientWith(unsafe).client.retrieveHarnessModelConfiguration("codex")).rejects.toMatchObject({ code: "invalid_admin_response" }); } for (const unsafe of [{ ...harnesses, data: [{ ...harnesses.data[1], model_configuration: { ...provider, api_key: "leak" } }] }, { ...harnesses, data: [harnesses.data[1], harnesses.data[1]] }, { data: harnesses.data }]) { @@ -240,9 +240,9 @@ describe("AdminClient response contracts", () => { const saved = { id: resourceId, object: "agent", model: "model", name: null, instructions: null, metadata: {}, multi_agent: { enabled: false, max_concurrent_subagents: null }, reasoning: { effort: null, summary: null }, service_tier: "auto", text: { format: { type: "text" }, verbosity: "medium" }, tools: [], created_at: 1, updated_at: 1 }; const withURL = (base_url: string, id = resourceId) => ({ ...saved, id, x_agents_core: { model_provider: { protocol: "responses", base_url, api_key_configured: true } } }); // The client is never stricter than Core's write rule: a host or port that URL parsing rejects must not fail the list. - const stored = ["https://p.test:99999/v1", "https://xn--.test", "https://[::1]:8443/v1", "HTTPS://p.test/v1?"].map((url, index) => withURL(url, `agent-${index}`)); + const stored = ["https://p.test:99999/v1", "https://xn--.test", "https://[::1]:8443/v1", "HTTPS://p.test/v1?", "http://10.0.0.5:8080/v1"].map((url, index) => withURL(url, `agent-${index}`)); expect((await clientWith(page(stored)).client.listAgents(projectId)).data).toEqual(stored); - for (const url of ["http://p.test", "https://user:pw@p.test", "https://p.test/?key=secret", "https://p.test/#secret", "https://:443/v1"]) { + for (const url of ["ftp://p.test", "https://user:pw@p.test", "https://p.test/?key=secret", "https://p.test/#secret", "https://:443/v1"]) { await expect(clientWith(page([withURL(url)])).client.listAgents(projectId)).rejects.toBeInstanceOf(AgentCoreError); } }); diff --git a/packages/agents-client/src/execution-configuration-projection.ts b/packages/agents-client/src/execution-configuration-projection.ts index b78e69a3b..dbd1ce5f3 100644 --- a/packages/agents-client/src/execution-configuration-projection.ts +++ b/packages/agents-client/src/execution-configuration-projection.ts @@ -18,12 +18,13 @@ function selection(value: unknown, invalid: Invalid): SessionExecutionConfigurat } // Splits an absolute URL as RFC 3986 appendix B does, without parsing its host. -const baseURLPattern = /^https:\/\/([^/?#]*)[^?#]*(?:\?([^#]*))?(?:#([\s\S]*))?$/iu; +const baseURLPattern = /^https?:\/\/([^/?#]*)[^?#]*(?:\?([^#]*))?(?:#([\s\S]*))?$/iu; /** * Checks a stored base URL as Core's write rule does, never more strictly: - * HTTPS with a host and no credentials, query or fragment. Host syntax is - * Core's to enforce, so one stored value never fails a whole list. + * HTTP or HTTPS with a host and no credentials, query or fragment. Host syntax, + * including which hosts HTTP may use, is Core's to enforce, so one stored value + * never fails a whole list. */ function safeBaseURL(value: string): boolean { const match = baseURLPattern.exec(value); diff --git a/services/core/internal/api/model_provider_public_validation_test.go b/services/core/internal/api/model_provider_public_validation_test.go index e334d368b..c6e1a6665 100644 --- a/services/core/internal/api/model_provider_public_validation_test.go +++ b/services/core/internal/api/model_provider_public_validation_test.go @@ -17,7 +17,7 @@ func TestModelProviderPublicValidation(t *testing.T) { body := `{"agent":{"model":"fixture"},"environment":{"type":"openai_hosted"},"input":"hello","x_agents_core":{"model_provider":` + tc.provider + `}}` out := credentialRequest(h, http.MethodPost, "/v1/agents/sessions", body) messages := map[string]string{ - "url": "model provider requires an HTTPS base_url without credentials, query or fragment", + "url": "model provider requires an HTTPS base_url, or HTTP to a loopback or private IP address, without credentials, query or fragment", "protocol": "unsupported model provider protocol", "key": "invalid model provider API key", "limits": "invalid model token limits", } From c5d4205dea2aa5fe22e1c8ebf86df4bc373287ed Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 15:00:42 +0800 Subject: [PATCH 13/84] Initialize every hosted Environment (#873) --- contracts/agents-api/environments.md | 2 +- contracts/agents-api/index.md | 1 + contracts/agents-api/zh/environments.md | 4 +- contracts/agents-api/zh/index.md | 3 +- .../core/internal/db/queries/environments.sql | 3 +- .../core/internal/db/sqlc/environments.sql.go | 3 +- .../archive_cancellation_cleanup_test.go | 3 ++ .../runtime_workspace_settlement_test.go | 4 ++ .../integration/archive_cancellation_test.go | 3 ++ .../local_environment_devices_test.go | 4 ++ .../tests/integration/root_fixture_test.go | 5 +++ .../runtime_initialization_test.go | 39 +++++++++++++++++++ 12 files changed, 68 insertions(+), 6 deletions(-) diff --git a/contracts/agents-api/environments.md b/contracts/agents-api/environments.md index e99afc829..0a40df7db 100644 --- a/contracts/agents-api/environments.md +++ b/contracts/agents-api/environments.md @@ -255,7 +255,7 @@ stateDiagram-v2 - Each file, Skill or Plugin transfer has a two-minute staging budget. Configure, package installation, setup commands and snapshot finalization share the whole initialization’s 30-minute budget, whose remaining duration Core carries on each operation and the Runtime enforces. Initial input keeps its five-minute admission deadline, so large installations should start from an idle Session. - A running initialization whose owner is lost, including across a Core restart, fails as unconfirmed; nothing is replayed. A completed Environment never reinstalls on reconnect or native recovery, so later user changes survive. - Failure is terminal for the Session but destroys neither compute nor files. -- An `openai_hosted` Environment journals `agent.session.environment.pending` in the transaction that starts its initialization and `agent.session.environment.ready` in the one that completes it, each exactly once. A `self_hosted` Environment emits neither. +- Every `openai_hosted` Environment starts `pending`, including one with no files or setup, and journals `agent.session.environment.pending` in the transaction that starts its initialization and `agent.session.environment.ready` in the one that completes it, each exactly once. Core journals `agent.session.environment.connected` when the Runtime connects, which is usually before initialization starts. A `self_hosted` Environment emits neither `pending` nor `ready`, and starts `complete` unless it has files or setup. A failed initialization records the events and Session state that [Environment initialization failure](./sessions-events.md#environment-initialization-failure) defines. The reason names only the step and its exit status: diff --git a/contracts/agents-api/index.md b/contracts/agents-api/index.md index 4cb29a291..e7d4da9d3 100644 --- a/contracts/agents-api/index.md +++ b/contracts/agents-api/index.md @@ -111,6 +111,7 @@ Each item is Core's deliberate or native behavior where the official service beh - `env` cannot set `OPENAI_API_KEY`, which Core reserves ([env](./environments.md#env-and-setup-commands)); the official service accepts it. - A `self_hosted` Session without pending input requests no connection ([activity](./environments.md#activity-and-required-actions)); one unused official Session switched to `requires_action` with `environment_connection` about five minutes after creation, and its deletion then returned 409. - A hosted Environment emits `ready` once, when its initialization completes, and not again before each later Turn as one official Session did. It also emits `connected` and `disconnected`, which that Session did not. +- The usual hosted order is `connected`, `pending`, `ready`, because Core journals `connected` when the Runtime connects, before it starts initialization; the last Environment event then reads `ready` while the Environment is `connected`. **Files, Skills, Environment files and Artifacts** ([Files and Skills](./source-files.md), [Environment files and Artifacts](./environment-files.md)) diff --git a/contracts/agents-api/zh/environments.md b/contracts/agents-api/zh/environments.md index 933cffb75..75f1f11dc 100644 --- a/contracts/agents-api/zh/environments.md +++ b/contracts/agents-api/zh/environments.md @@ -1,7 +1,7 @@ --- title: "Environment 与模板" source: contracts/agents-api/environments.md -source_hash: fa17eba20ecb905da36dfb1c0ffb8d9a86f49560f0688ddc6b9a3b59009fc4b4 +source_hash: 5cd6355e98456fc2b65dd8097080a8bce391d577bd9a746370d281c379d5e48b --- Environment 是 Session 的执行资源,包括 Harness 运行所在的机器、工作区以及已完成准备的能力。Session 通过其 `environment` 配置创建 Environment;不存在独立的 create 调用。Environment 模板是 Session 创建时解析的可复用准备配置。本契约涵盖这两类资源、两种放置方式、输入接纳、能力准备、Skills、Plugins 和 MCP 连接来源。 @@ -257,7 +257,7 @@ stateDiagram-v2 - 每个文件、Skill 或 Plugin 传输的暂存预算为两分钟。configure、软件包安装、设置命令和快照最终确定共享整个初始化过程的 30 分钟预算,Core 在每项操作中携带剩余时长,由 Runtime 执行。初始输入仍保留其五分钟接纳期限,因此大型安装应从空闲 Session 开始。 - 正在运行且所有权丧失的初始化,包括跨 Core 重启丧失所有权,会作为未确认而失败;不会重播任何内容。已完成的 Environment 在重连或原生恢复时绝不会重新安装,因此用户后续更改会保留下来。 - 失败对 Session 而言是终止状态,但不会销毁计算资源或文件。 -- `openai_hosted` Environment 在开始初始化的事务中记录 `agent.session.environment.pending`,在完成初始化的事务中记录 `agent.session.environment.ready`,各恰好一次。`self_hosted` Environment 两者都不发出。 +- 每个 `openai_hosted` Environment 都从 `pending` 开始,包括没有文件和初始化设置的 Environment,并在开始初始化的事务中记录 `agent.session.environment.pending`,在完成初始化的事务中记录 `agent.session.environment.ready`,各恰好一次。Core 在 Runtime 连接时记录 `agent.session.environment.connected`,通常早于初始化开始。`self_hosted` Environment 不发出 `pending` 和 `ready`,且除非有文件或初始化设置,否则从 `complete` 开始。 初始化失败时记录的事件和 Session 状态由 [Environment 初始化失败](sessions-events.md#environment-initialization-failure)定义。原因只指明步骤及其退出状态: diff --git a/contracts/agents-api/zh/index.md b/contracts/agents-api/zh/index.md index 43691403b..e7f48629f 100644 --- a/contracts/agents-api/zh/index.md +++ b/contracts/agents-api/zh/index.md @@ -1,7 +1,7 @@ --- title: "OpenAI 兼容性" source: contracts/agents-api/index.md -source_hash: b6322e1f2733cd1e5b1486488c4341190ce72b3cd29bb4547ef3fc244893ff7c +source_hash: 27f86ff815bee7a3bfe69a5fb4706cea7f5c5103e5718b5a5b227822e3e259ac --- Core 实现下方固定版本的 OpenAI Agents API。本台账列出各项资源的覆盖情况、相对于官方服务的所有差异以及已知缺口。 @@ -114,6 +114,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - `env` 不能设置 Core 保留的 `OPENAI_API_KEY`([env](environments.md#env-and-setup-commands));官方服务接受该变量。 - 没有待处理输入的 `self_hosted` Session 不会请求连接([活动状态](environments.md#activity-and-required-actions));一个未使用的官方 Session 在创建约五分钟后转为 `requires_action`,原因为 `environment_connection`,之后删除它返回 409。 - hosted Environment 只在初始化完成时发出一次 `ready`,不会像一个官方 Session 那样在之后每个 Turn 之前再次发出;它还会发出 `connected` 和 `disconnected`,而该官方 Session 没有。 +- hosted Environment 通常的顺序是 `connected`、`pending`、`ready`,因为 Core 在 Runtime 连接时、开始初始化之前就记录 `connected`;此时最后一个 Environment 事件显示 `ready`,而 Environment 处于 `connected`。 **Files、Skills、Environment files 和 Artifacts**([Files and Skills](source-files.md)、[Environment files and Artifacts](environment-files.md)) diff --git a/services/core/internal/db/queries/environments.sql b/services/core/internal/db/queries/environments.sql index 2e122d372..1e843a5a2 100644 --- a/services/core/internal/db/queries/environments.sql +++ b/services/core/internal/db/queries/environments.sql @@ -1,6 +1,7 @@ -- name: CreateEnvironment :exec INSERT INTO environments (id, session_id, initialization) -VALUES ($1, $2, CASE WHEN EXISTS (SELECT 1 FROM initial_environment_files WHERE session_id = $2) +VALUES ($1, $2, CASE WHEN (SELECT configuration->'environment'->>'type' FROM sessions WHERE id = $2) = 'openai_hosted' + OR EXISTS (SELECT 1 FROM initial_environment_files WHERE session_id = $2) OR EXISTS (SELECT 1 FROM environment_setups WHERE session_id = $2) THEN 'pending' ELSE 'complete' END); -- name: GetEnvironment :one diff --git a/services/core/internal/db/sqlc/environments.sql.go b/services/core/internal/db/sqlc/environments.sql.go index 514d21724..acfb01961 100644 --- a/services/core/internal/db/sqlc/environments.sql.go +++ b/services/core/internal/db/sqlc/environments.sql.go @@ -13,7 +13,8 @@ import ( const createEnvironment = `-- name: CreateEnvironment :exec INSERT INTO environments (id, session_id, initialization) -VALUES ($1, $2, CASE WHEN EXISTS (SELECT 1 FROM initial_environment_files WHERE session_id = $2) +VALUES ($1, $2, CASE WHEN (SELECT configuration->'environment'->>'type' FROM sessions WHERE id = $2) = 'openai_hosted' + OR EXISTS (SELECT 1 FROM initial_environment_files WHERE session_id = $2) OR EXISTS (SELECT 1 FROM environment_setups WHERE session_id = $2) THEN 'pending' ELSE 'complete' END) ` diff --git a/services/core/internal/execution/archive_cancellation_cleanup_test.go b/services/core/internal/execution/archive_cancellation_cleanup_test.go index 6dddee6bc..8a4307025 100644 --- a/services/core/internal/execution/archive_cancellation_cleanup_test.go +++ b/services/core/internal/execution/archive_cancellation_cleanup_test.go @@ -83,6 +83,9 @@ func TestArchiveWaitingCleanupReceiptBarrier(t *testing.T) { t.Fatal(err) } session := created.Session + if _, err := pool.Exec(t.Context(), `UPDATE environments SET initialization='complete' WHERE id=$1`, session.Environment.ID); err != nil { + t.Fatal(err) + } secret := uuid.NewString() key := deployment.AllocationKey{TenantID: project.TenantID, EnvironmentID: session.Environment.ID} owner, err := leased.Deployment.ReserveAllocation(t.Context(), key, installation, runtimedevice.HashCredential(secret)) diff --git a/services/core/internal/execution/runtime_workspace_settlement_test.go b/services/core/internal/execution/runtime_workspace_settlement_test.go index 13ad9efd2..824fc5afa 100644 --- a/services/core/internal/execution/runtime_workspace_settlement_test.go +++ b/services/core/internal/execution/runtime_workspace_settlement_test.go @@ -110,6 +110,10 @@ func workspaceSettlementFixtureWithSetup(t *testing.T, provider sandbox.SandboxP t.Fatal(err) } session := created.Session + // The fixture's Environment is already prepared. + if _, err := pool.Exec(t.Context(), `UPDATE environments SET initialization='complete' WHERE id=$1`, session.Environment.ID); err != nil { + t.Fatal(err) + } if nodeID != "" { if _, err := operations.EnsurePlacement(t.Context(), deployment.AllocationKey{TenantID: session.TenantID, EnvironmentID: session.Environment.ID}, installation); err != nil { t.Fatal(err) diff --git a/services/core/tests/integration/archive_cancellation_test.go b/services/core/tests/integration/archive_cancellation_test.go index 6f3bb7a73..d1b05c5ec 100644 --- a/services/core/tests/integration/archive_cancellation_test.go +++ b/services/core/tests/integration/archive_cancellation_test.go @@ -62,6 +62,9 @@ func TestArchiveWaitingCancellationReceipts(t *testing.T) { if err != nil { t.Fatal(err) } + if _, err := s.pool.Exec(t.Context(), `UPDATE environments SET initialization='complete' WHERE id=$1`, session.Environment.ID); err != nil { + t.Fatal(err) + } secret := uuid.NewString() owner, err := leased.Deployment.ReserveAllocation(t.Context(), deployment.AllocationKey{TenantID: project.TenantID, EnvironmentID: session.Environment.ID}, installation, runtimedevice.HashCredential(secret)) if err != nil { diff --git a/services/core/tests/integration/local_environment_devices_test.go b/services/core/tests/integration/local_environment_devices_test.go index 9a146faad..feda04d56 100644 --- a/services/core/tests/integration/local_environment_devices_test.go +++ b/services/core/tests/integration/local_environment_devices_test.go @@ -24,6 +24,10 @@ func localEnvironment(t *testing.T, s *Store, tenant string) (sessions.Session, if err != nil { t.Fatal(err) } + // The fixture's Environment is already prepared. + if _, err := s.pool.Exec(t.Context(), `UPDATE environments SET initialization='complete' WHERE id=$1`, environment.ID); err != nil { + t.Fatal(err) + } return session, environment } diff --git a/services/core/tests/integration/root_fixture_test.go b/services/core/tests/integration/root_fixture_test.go index 4d4367215..6f00f0e9f 100644 --- a/services/core/tests/integration/root_fixture_test.go +++ b/services/core/tests/integration/root_fixture_test.go @@ -57,6 +57,11 @@ func (s *Store) SetPlacement(rules *placement.Rules) { s.placement = rules } // CreateSession creates a Session through the Session service on s. func (s *Store) CreateSession(ctx context.Context, tenant string, input sessions.CreateSession) (sessions.Session, error) { creation, err := createSession(ctx, s, tenant, input) + // A hosted fixture with nothing to set up stands for a prepared Environment; + // the initialization tests give theirs files or a setup. + if err == nil && creation.Session.Environment != nil && len(input.InitialFiles) == 0 && input.Initialization.Empty() { + _, err = s.pool.Exec(ctx, `UPDATE environments SET initialization='complete' WHERE id=$1`, creation.Session.Environment.ID) + } return creation.Session, err } diff --git a/services/core/tests/integration/runtime_initialization_test.go b/services/core/tests/integration/runtime_initialization_test.go index 3fed7317b..65aabfaca 100644 --- a/services/core/tests/integration/runtime_initialization_test.go +++ b/services/core/tests/integration/runtime_initialization_test.go @@ -216,3 +216,42 @@ func TestManagedRuntimePreparationAllOperationsUsePeer(t *testing.T) { t.Fatal("initialization events", lifecycle) } } + +func TestHostedEnvironmentWithoutSetupIsInitialized(t *testing.T) { + s, key := configuredStore(t) + tenant := uuid.NewString() + creation, err := createSession(t.Context(), s, tenant, WithFixtureModelProvider(sessions.CreateSession{ + Creator: FixtureCreator(), Engine: "codex", IdempotencyKey: uuid.NewString(), + Configuration: json.RawMessage(`{"agent":{"model":"test-model"},"environment":{"type":"openai_hosted","network":{"access":"disabled"}}}`), + })) + if err != nil { + t.Fatal(err) + } + session := creation.Session + if initializationState(t, s, tenant, session.Environment.ID) != "pending" { + t.Fatal("hosted Environment without setup did not start pending") + } + provider := &initializingProvider{lifecycleProvider: lifecycleProvider{resources: map[string]sandbox.Info{}}} + provider.apply = func(request proto.RuntimePreparePayload, _ []byte) proto.RuntimePrepareResultPayload { + t.Error("empty initialization sent a Runtime operation", request.Action) + return completedInitialization(request, nil) + } + worker, _ := managedWorkerMode(t, s, key, provider, true) + if _, err := worker.ProvisionEnvironment(t.Context(), tenant, session.Environment.ID, key); err != nil { + t.Fatal(err) + } + awaitInitialization(t, s, tenant, session.Environment.ID, "complete") + changes, err := sessionAdapter(s).ListSessionEvents(t.Context(), tenant, session.ID, 0) + if err != nil { + t.Fatal(err) + } + var lifecycle []string + for _, change := range changes { + if change.Event.Type == "agent.session.environment.pending" || change.Event.Type == "agent.session.environment.ready" { + lifecycle = append(lifecycle, change.Event.Type) + } + } + if !reflect.DeepEqual(lifecycle, []string{"agent.session.environment.pending", "agent.session.environment.ready"}) { + t.Fatal("initialization events", lifecycle) + } +} From 7a9dc1594768ac09c8959c5061023dbdafa41114 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 15:20:30 +0800 Subject: [PATCH 14/84] State that connected and pending arrive in either order (#874) Core journals connected when it observes the Runtime's connection and pending when the initialization Worker claims the Environment on that Runtime, so either can come first. On the mx test installation, 16 of 23 hosted Sessions recorded pending first and 7 connected first; the documents said connected usually came first. --- contracts/agents-api/environments.md | 2 +- contracts/agents-api/index.md | 2 +- contracts/agents-api/zh/environments.md | 4 ++-- contracts/agents-api/zh/index.md | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contracts/agents-api/environments.md b/contracts/agents-api/environments.md index 0a40df7db..ef1a5ee16 100644 --- a/contracts/agents-api/environments.md +++ b/contracts/agents-api/environments.md @@ -255,7 +255,7 @@ stateDiagram-v2 - Each file, Skill or Plugin transfer has a two-minute staging budget. Configure, package installation, setup commands and snapshot finalization share the whole initialization’s 30-minute budget, whose remaining duration Core carries on each operation and the Runtime enforces. Initial input keeps its five-minute admission deadline, so large installations should start from an idle Session. - A running initialization whose owner is lost, including across a Core restart, fails as unconfirmed; nothing is replayed. A completed Environment never reinstalls on reconnect or native recovery, so later user changes survive. - Failure is terminal for the Session but destroys neither compute nor files. -- Every `openai_hosted` Environment starts `pending`, including one with no files or setup, and journals `agent.session.environment.pending` in the transaction that starts its initialization and `agent.session.environment.ready` in the one that completes it, each exactly once. Core journals `agent.session.environment.connected` when the Runtime connects, which is usually before initialization starts. A `self_hosted` Environment emits neither `pending` nor `ready`, and starts `complete` unless it has files or setup. +- Every `openai_hosted` Environment starts `pending`, including one with no files or setup, and journals `agent.session.environment.pending` in the transaction that starts its initialization and `agent.session.environment.ready` in the one that completes it, each exactly once. Core journals `agent.session.environment.connected` when it observes the Runtime's connection, before or after `pending`. A `self_hosted` Environment emits neither `pending` nor `ready`, and starts `complete` unless it has files or setup. A failed initialization records the events and Session state that [Environment initialization failure](./sessions-events.md#environment-initialization-failure) defines. The reason names only the step and its exit status: diff --git a/contracts/agents-api/index.md b/contracts/agents-api/index.md index e7d4da9d3..9eb9f89f3 100644 --- a/contracts/agents-api/index.md +++ b/contracts/agents-api/index.md @@ -111,7 +111,7 @@ Each item is Core's deliberate or native behavior where the official service beh - `env` cannot set `OPENAI_API_KEY`, which Core reserves ([env](./environments.md#env-and-setup-commands)); the official service accepts it. - A `self_hosted` Session without pending input requests no connection ([activity](./environments.md#activity-and-required-actions)); one unused official Session switched to `requires_action` with `environment_connection` about five minutes after creation, and its deletion then returned 409. - A hosted Environment emits `ready` once, when its initialization completes, and not again before each later Turn as one official Session did. It also emits `connected` and `disconnected`, which that Session did not. -- The usual hosted order is `connected`, `pending`, `ready`, because Core journals `connected` when the Runtime connects, before it starts initialization; the last Environment event then reads `ready` while the Environment is `connected`. +- A hosted Environment's `connected` and `pending` arrive in either order: Core journals `connected` when it observes the Runtime's connection and `pending` when initialization starts on that Runtime. `ready` follows both, so the last Environment event can read `ready` while the Environment is `connected`. **Files, Skills, Environment files and Artifacts** ([Files and Skills](./source-files.md), [Environment files and Artifacts](./environment-files.md)) diff --git a/contracts/agents-api/zh/environments.md b/contracts/agents-api/zh/environments.md index 75f1f11dc..110138577 100644 --- a/contracts/agents-api/zh/environments.md +++ b/contracts/agents-api/zh/environments.md @@ -1,7 +1,7 @@ --- title: "Environment 与模板" source: contracts/agents-api/environments.md -source_hash: 5cd6355e98456fc2b65dd8097080a8bce391d577bd9a746370d281c379d5e48b +source_hash: e62ff2b6bc6cee007f1bdbfac5cf6204e2d13552686e7d7c0a424362495e7a52 --- Environment 是 Session 的执行资源,包括 Harness 运行所在的机器、工作区以及已完成准备的能力。Session 通过其 `environment` 配置创建 Environment;不存在独立的 create 调用。Environment 模板是 Session 创建时解析的可复用准备配置。本契约涵盖这两类资源、两种放置方式、输入接纳、能力准备、Skills、Plugins 和 MCP 连接来源。 @@ -257,7 +257,7 @@ stateDiagram-v2 - 每个文件、Skill 或 Plugin 传输的暂存预算为两分钟。configure、软件包安装、设置命令和快照最终确定共享整个初始化过程的 30 分钟预算,Core 在每项操作中携带剩余时长,由 Runtime 执行。初始输入仍保留其五分钟接纳期限,因此大型安装应从空闲 Session 开始。 - 正在运行且所有权丧失的初始化,包括跨 Core 重启丧失所有权,会作为未确认而失败;不会重播任何内容。已完成的 Environment 在重连或原生恢复时绝不会重新安装,因此用户后续更改会保留下来。 - 失败对 Session 而言是终止状态,但不会销毁计算资源或文件。 -- 每个 `openai_hosted` Environment 都从 `pending` 开始,包括没有文件和初始化设置的 Environment,并在开始初始化的事务中记录 `agent.session.environment.pending`,在完成初始化的事务中记录 `agent.session.environment.ready`,各恰好一次。Core 在 Runtime 连接时记录 `agent.session.environment.connected`,通常早于初始化开始。`self_hosted` Environment 不发出 `pending` 和 `ready`,且除非有文件或初始化设置,否则从 `complete` 开始。 +- 每个 `openai_hosted` Environment 都从 `pending` 开始,包括没有文件和初始化设置的 Environment,并在开始初始化的事务中记录 `agent.session.environment.pending`,在完成初始化的事务中记录 `agent.session.environment.ready`,各恰好一次。Core 在观察到 Runtime 连接时记录 `agent.session.environment.connected`,可能在 `pending` 之前或之后。`self_hosted` Environment 不发出 `pending` 和 `ready`,且除非有文件或初始化设置,否则从 `complete` 开始。 初始化失败时记录的事件和 Session 状态由 [Environment 初始化失败](sessions-events.md#environment-initialization-failure)定义。原因只指明步骤及其退出状态: diff --git a/contracts/agents-api/zh/index.md b/contracts/agents-api/zh/index.md index e7f48629f..3ad298a27 100644 --- a/contracts/agents-api/zh/index.md +++ b/contracts/agents-api/zh/index.md @@ -1,7 +1,7 @@ --- title: "OpenAI 兼容性" source: contracts/agents-api/index.md -source_hash: 27f86ff815bee7a3bfe69a5fb4706cea7f5c5103e5718b5a5b227822e3e259ac +source_hash: 1ba11a295c62e532fae58388b09d54a065648642ee17aed10081a36c65ef64f5 --- Core 实现下方固定版本的 OpenAI Agents API。本台账列出各项资源的覆盖情况、相对于官方服务的所有差异以及已知缺口。 @@ -114,7 +114,7 @@ Core 自身字段位于 `x_agents_core` 中([Core extensions](../../../docs/zh - `env` 不能设置 Core 保留的 `OPENAI_API_KEY`([env](environments.md#env-and-setup-commands));官方服务接受该变量。 - 没有待处理输入的 `self_hosted` Session 不会请求连接([活动状态](environments.md#activity-and-required-actions));一个未使用的官方 Session 在创建约五分钟后转为 `requires_action`,原因为 `environment_connection`,之后删除它返回 409。 - hosted Environment 只在初始化完成时发出一次 `ready`,不会像一个官方 Session 那样在之后每个 Turn 之前再次发出;它还会发出 `connected` 和 `disconnected`,而该官方 Session 没有。 -- hosted Environment 通常的顺序是 `connected`、`pending`、`ready`,因为 Core 在 Runtime 连接时、开始初始化之前就记录 `connected`;此时最后一个 Environment 事件显示 `ready`,而 Environment 处于 `connected`。 +- hosted Environment 的 `connected` 和 `pending` 先后顺序不固定:Core 在观察到 Runtime 连接时记录 `connected`,在该 Runtime 上开始初始化时记录 `pending`。`ready` 在两者之后,因此最后一个 Environment 事件可能显示 `ready`,而 Environment 处于 `connected`。 **Files、Skills、Environment files 和 Artifacts**([Files and Skills](source-files.md)、[Environment files and Artifacts](environment-files.md)) From abebcd1bab661f4320d1072f3166ed273dd87a11 Mon Sep 17 00:00:00 2001 From: SaladDay <1203511142@qq.com> Date: Sun, 25 Oct 2026 17:04:32 +0800 Subject: [PATCH 15/84] Publish reproducible performance results (#875) * Publish reproducible performance results scripts/benchmark.py drives hosted Sessions through the official SDK, times E2B with its SDK, and builds the table from the Session records and the Core log lines it keeps. docs/performance.md describes each measurement, the setup and how to reproduce it; the records it was built from are in docs/performance. The README shows the table beside E2B and the limits that apply. The backend comparison listed E2B as not suspending idle sandboxes; E2B pauses them in place. * Rerun the performance results with a 4 GiB E2B comparison and a cold resume Measure every row with the final script, add the full-node and npm install rows and a run that resumes from disk, describe how the E2B comparison differs, and put the Docker and workspace limits in their owning docs. * Record E2B resources and check the performance tables against their records The E2B run now records each sandbox's CPUs and memory, and build-template.py takes --memory-mb so the 4 GiB comparison template can be built from the repository. report fails when a measurement has no samples or the Core log yields no lines, and a hygiene check compares the published tables with report's output. The docs state the run conditions, the full list of E2B differences and the suspension triggers by link. --- Makefile | 1 + README.md | 23 ++ README.zh-CN.md | 23 ++ docs.json | 3 +- docs/getting-started/sandbox-backends.md | 6 +- docs/performance.md | 109 ++++++++ docs/performance/cold/core.jsonl | 256 +++++++++++++++++++ docs/performance/cold/sessions.jsonl | 50 ++++ docs/performance/cold/window.json | 1 + docs/performance/core.jsonl | 252 +++++++++++++++++++ docs/performance/e2b.jsonl | 20 ++ docs/performance/sessions.jsonl | 50 ++++ docs/performance/window.json | 1 + docs/workspace-provider.md | 2 +- docs/zh/getting-started/sandbox-backends.md | 8 +- docs/zh/performance.md | 111 ++++++++ docs/zh/workspace-provider.md | 4 +- scripts/benchmark.py | 265 ++++++++++++++++++++ scripts/benchmark.test.py | 31 +++ scripts/ci_plan.py | 1 + services/core/deploy/e2b/README.md | 2 +- services/core/deploy/e2b/build-template.py | 3 +- 22 files changed, 1209 insertions(+), 13 deletions(-) create mode 100644 docs/performance.md create mode 100644 docs/performance/cold/core.jsonl create mode 100644 docs/performance/cold/sessions.jsonl create mode 100644 docs/performance/cold/window.json create mode 100644 docs/performance/core.jsonl create mode 100644 docs/performance/e2b.jsonl create mode 100644 docs/performance/sessions.jsonl create mode 100644 docs/performance/window.json create mode 100644 docs/zh/performance.md create mode 100644 scripts/benchmark.py create mode 100644 scripts/benchmark.test.py diff --git a/Makefile b/Makefile index 3efed26be..2900c06e0 100644 --- a/Makefile +++ b/Makefile @@ -202,6 +202,7 @@ check-sandbox-provider-contract: .PHONY: check-docs check-ci check-docs: PYTHONDONTWRITEBYTECODE=1 python3 scripts/core-distribution-manifest.test.py BundledDocsTests + PYTHONDONTWRITEBYTECODE=1 python3 scripts/benchmark.test.py check-ci: PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts -p 'ci_*test.py' diff --git a/README.md b/README.md index 8601923f3..98384e609 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,29 @@ The OpenAI Agents API, open source and self-hosted. Run Codex, Claude Code or Mi - **Compute that sleeps, workspaces that stay.** On microsandbox, which keeps every workspace on independent storage, idle sandboxes release compute and resume on a compatible node with their files intact. E2B pauses idle sandboxes in place. Docker and your own Linux, macOS or Windows machine also run Sessions. See [Sandbox Provider protocol](https://openagentcore.dev/docs/sandbox-provider). - **Replaceable parts.** Sandbox Providers, workspace filesystems, Harnesses and model providers plug in through [defined protocols](AGENTS.md#protocols-at-every-boundary). +## Performance + +The sandbox lifecycle on one microsandbox node, with E2B's create, pause and resume for comparison. Medians of 7 to 30 samples on 2026-10-25; each row links to its method and raw records, and [`scripts/benchmark.py`](scripts/benchmark.py) reproduces them. + +| Operation | OpenAgentCore on microsandbox | E2B | Records | +| --- | --- | --- | --- | +| [Create a sandbox](https://openagentcore.dev/docs/performance#sandbox-start) | 1.22 s | 0.63 s | [core](docs/performance/core.jsonl), [e2b](docs/performance/e2b.jsonl) | +| [Sandbox created → initialization starts](https://openagentcore.dev/docs/performance#sandbox-start) | 0.98 s | — | [core](docs/performance/core.jsonl) | +| [Environment ready, preparation cache hit / miss](https://openagentcore.dev/docs/performance#environment-ready) | 2.50 s / 7.35 s | — | [sessions](docs/performance/sessions.jsonl) | +| [Environment ready on a full node](https://openagentcore.dev/docs/performance#environment-ready) | 5.90 s | — | [sessions](docs/performance/sessions.jsonl), [core](docs/performance/core.jsonl) | +| [Suspend an idle sandbox](https://openagentcore.dev/docs/performance#suspend-and-resume) | 3.33 s | 1.04 s | [core](docs/performance/core.jsonl), [e2b](docs/performance/e2b.jsonl) | +| [Resume it; after dropping the node's page cache](https://openagentcore.dev/docs/performance#suspend-and-resume) | 1.75 s / 1.99 s | 0.64 s | [core](docs/performance/core.jsonl), [cold](docs/performance/cold/core.jsonl), [e2b](docs/performance/e2b.jsonl) | +| [First text of a Turn, suspended / running Session](https://openagentcore.dev/docs/performance#suspend-and-resume) | 3.51 s / 1.26 s | — | [sessions](docs/performance/sessions.jsonl) | + +E2B times are SDK calls on the client, each with at least one 0.20 s API round trip; a resume makes two calls. OpenAgentCore's sandbox times are Core's own, over a 0.2 ms local network; Environment ready and first text are timed by an application on the Core host from its event stream, which Core sends in 100 ms steps. [Setup](https://openagentcore.dev/docs/performance#setup) lists the hosts and versions, and [E2B](https://openagentcore.dev/docs/performance#e2b) how the two sides differ. + +## Limits + +- **Docker is a compatibility backend**, for trusted workloads and hosts without KVM. Containers share the node's kernel, idle sandboxes never suspend, and files stay on the node's disk. See [Choose a sandbox backend](https://openagentcore.dev/docs/getting-started/sandbox-backends). +- **One writer per workspace.** A workspace is attached to one sandbox at a time, and storage keeps only its current files: no file history or forks. See [Workspace filesystem protocol](https://openagentcore.dev/docs/workspace-provider). +- **Workspace storage needs Linux.** The NFS adapter uses a kernel NFS mount on the Core host and on every node. See [Set up workspace storage](https://openagentcore.dev/docs/getting-started/workspace-storage). +- **Suspend is slower than E2B's pause**: 3.33 s against 1.04 s. A Session that starts on a node already running its maximum number of sandboxes waits for an idle one to suspend, as *Environment ready on a full node* above shows. See [Suspension](https://openagentcore.dev/docs/sandbox-provider#suspension). + ![Deployment overview](docs/assets/console-overview-en.webp) ## Quickstart diff --git a/README.zh-CN.md b/README.zh-CN.md index a92ff4679..1e4c832c8 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -20,6 +20,29 @@ - **计算会休眠,工作区会保留。** 在 microsandbox 上(每个工作区都保存在独立存储中),空闲沙箱释放计算资源,并在兼容节点上带着文件恢复。E2B 会就地暂停空闲沙箱。Docker 以及你自己的 Linux、macOS 或 Windows 机器同样可以运行 Session。详见[沙箱提供商协议](https://openagentcore.dev/zh/docs/sandbox-provider)。 - **部件可替换。** 沙箱提供商、工作区文件系统、Harness 和模型提供商都通过[既定协议](AGENTS.md#protocols-at-every-boundary)接入。 +## 性能 + +单个 microsandbox 节点上的沙箱生命周期,并以 E2B 的创建、暂停和恢复作为对照。2026-10-25 测得,每项为 7 到 30 个样本的中位数;每一行都链接到测量方法和原始记录,[`scripts/benchmark.py`](scripts/benchmark.py) 可以复现这些数据。 + +| 操作 | OpenAgentCore(microsandbox) | E2B | 原始记录 | +| --- | --- | --- | --- | +| [创建沙箱](https://openagentcore.dev/zh/docs/performance#sandbox-start) | 1.22 s | 0.63 s | [core](docs/performance/core.jsonl), [e2b](docs/performance/e2b.jsonl) | +| [沙箱创建完成 → 开始初始化](https://openagentcore.dev/zh/docs/performance#sandbox-start) | 0.98 s | — | [core](docs/performance/core.jsonl) | +| [Environment 就绪,准备缓存命中 / 未命中](https://openagentcore.dev/zh/docs/performance#environment-ready) | 2.50 s / 7.35 s | — | [sessions](docs/performance/sessions.jsonl) | +| [满载节点上 Environment 就绪](https://openagentcore.dev/zh/docs/performance#environment-ready) | 5.90 s | — | [sessions](docs/performance/sessions.jsonl), [core](docs/performance/core.jsonl) | +| [挂起空闲沙箱](https://openagentcore.dev/zh/docs/performance#suspend-and-resume) | 3.33 s | 1.04 s | [core](docs/performance/core.jsonl), [e2b](docs/performance/e2b.jsonl) | +| [恢复沙箱;清空节点页缓存后恢复](https://openagentcore.dev/zh/docs/performance#suspend-and-resume) | 1.75 s / 1.99 s | 0.64 s | [core](docs/performance/core.jsonl), [cold](docs/performance/cold/core.jsonl), [e2b](docs/performance/e2b.jsonl) | +| [Turn 的首个文本,已挂起 / 运行中的 Session](https://openagentcore.dev/zh/docs/performance#suspend-and-resume) | 3.51 s / 1.26 s | — | [sessions](docs/performance/sessions.jsonl) | + +E2B 时间为客户端上 SDK 调用的耗时,每次调用至少含一次 0.20 s 的 API 往返;恢复包含两次调用。OpenAgentCore 的沙箱时间由 Core 自己测量,经过 0.2 ms 的本地网络;Environment 就绪和首个文本由 Core 主机上的应用根据事件流计时,Core 以 100 ms 为间隔推送事件流。主机和版本见[测试环境](https://openagentcore.dev/zh/docs/performance#setup),两边的差异见 [E2B](https://openagentcore.dev/zh/docs/performance#e2b)。 + +## 适用边界 + +- **Docker 是兼容选项**,用于可信负载和没有 KVM 的主机。容器共享节点内核,空闲沙箱不会挂起,文件保存在节点磁盘上。详见[选择沙箱提供商](https://openagentcore.dev/zh/docs/getting-started/sandbox-backends)。 +- **每个工作区只有一个写入者。** 工作区同一时间只挂载到一个沙箱,存储只保留当前文件,没有文件历史或分叉。详见[工作区文件系统协议](https://openagentcore.dev/zh/docs/workspace-provider)。 +- **工作区存储需要 Linux。** NFS 适配器使用 Core 主机和每个节点上的内核 NFS 挂载。详见[设置工作区存储](https://openagentcore.dev/zh/docs/getting-started/workspace-storage)。 +- **挂起比 E2B 的暂停慢**:3.33 s 对 1.04 s。节点运行的沙箱已达上限时,新 Session 要等一个空闲沙箱挂起,见上表的“满载节点上 Environment 就绪”。详见[暂停](https://openagentcore.dev/zh/docs/sandbox-provider#suspension)。 + ![部署概览](docs/assets/console-overview-zh.webp) ## 快速开始 diff --git a/docs.json b/docs.json index 04e0453b1..d6809997c 100644 --- a/docs.json +++ b/docs.json @@ -31,7 +31,8 @@ "group": "Concepts", "pages": [ "docs/concepts", - "docs/architecture" + "docs/architecture", + "docs/performance" ] } ] diff --git a/docs/getting-started/sandbox-backends.md b/docs/getting-started/sandbox-backends.md index be34b9ace..36b81bc2a 100644 --- a/docs/getting-started/sandbox-backends.md +++ b/docs/getting-started/sandbox-backends.md @@ -8,19 +8,19 @@ The installer selects no backend. One installation uses one backend. To change i ## Compare the backends -| | microsandbox (recommended) | Docker | E2B | +| | microsandbox (recommended) | Docker (compatibility) | E2B | | --- | --- | --- | --- | | Where sandboxes run | A microVM on your Linux nodes | A container on your Linux nodes | E2B's cloud | | Nodes to add | Yes | Yes | None | | You provide | Linux amd64 hosts with systemd and `/dev/kvm` | Linux amd64 hosts with systemd and rootful Docker Engine | An E2B API key and a template; a public HTTPS URL for Core | | Isolation | Each sandbox has its own kernel | Containers share the node's kernel | E2B's | -| Idle sandboxes suspend and resume | Yes, with checkpoints | No | No | +| Idle sandboxes suspend and resume | Yes, with checkpoints | No | Yes, paused in place by E2B | | Workspace storage | Required, on NFS | Own disk | Own disk | | Disk limits | Root disk and workspace quota | None | Set by the template | The field-level differences are in the [deployment contract](../../contracts/agents-api/sandbox-deployment.md#what-each-field-means-per-sandbox-provider). Host requirements for nodes are in [Add and manage nodes](./nodes.md#host-requirements). -Docker nodes are [root-equivalent](./nodes.md#what-the-installer-sets-up) on their host: add them only on hosts dedicated to sandboxes. +Docker is a compatibility backend, for trusted workloads and for hosts without `/dev/kvm`. Its nodes are [root-equivalent](./nodes.md#what-the-installer-sets-up) on their host: add them only on hosts dedicated to sandboxes. Sandbox nodes run on Linux amd64. When Core runs on macOS or Windows, connect a Linux node or use E2B. Applications can also run [self-hosted Sessions](./self-hosted.md) on their own machines, with no backend. diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 000000000..8c57b2e96 --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,109 @@ +--- +title: "Performance" +--- + +These measurements cover the sandbox lifecycle on microsandbox: starting a sandbox, preparing its environment, suspending it when idle and resuming it. E2B's create, pause and resume are measured with its SDK for comparison, and [E2B](#e2b) lists how the two sides differ. [`scripts/benchmark.py`](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/scripts/benchmark.py) produced every number on this page from the [records](https://github.com/MiniMax-AI/OpenAgentCore/tree/main/docs/performance) published beside it. + +## Results + +| Measurement | Median | Range | n | +| --- | --- | --- | --- | +| Sandbox create | 1.22 s | 1.18–1.37 s | 30 | +| Sandbox created → initialization start | 0.98 s | 0.75–1.48 s | 20 | +| Session created → environment ready, preparation cache miss | 7.35 s | 5.90–16.20 s | 10 | +| npm install, preparation cache miss | 4.67 s | 3.09–13.54 s | 10 | +| Session created → environment ready, preparation cache hit | 2.50 s | 2.30–2.70 s | 10 | +| Session created → environment ready, free slot | 2.50 s | 2.10–2.60 s | 3 | +| Session created → environment ready, full node | 5.90 s | 5.50–15.40 s | 7 | +| Suspend | 3.33 s | 2.88–4.53 s | 10 | +| Resume → sandbox running | 1.75 s | 1.16–4.70 s | 10 | +| Turn first text, resumed Session | 3.51 s | 2.11–6.91 s | 10 | +| Turn first text, running Session | 1.26 s | 1.11–2.31 s | 10 | +| E2B create | 0.63 s | 0.51–1.79 s | 10 | +| E2B pause | 1.04 s | 0.66–2.48 s | 10 | +| E2B resume → first command | 0.64 s | 0.57–4.57 s | 10 | +| E2B API round trip | 0.20 s | 0.20–0.29 s | 10 | + +A second run dropped the node's page cache after every Session had suspended, so each resume read its checkpoint from disk. Its resume and first-text rows: + +| Measurement | Median | Range | n | +| --- | --- | --- | --- | +| Resume → sandbox running | 1.99 s | 1.69–5.26 s | 10 | +| Turn first text, resumed Session | 3.11 s | 2.71–8.41 s | 10 | +| Turn first text, running Session | 1.26 s | 0.71–2.81 s | 10 | + +## What each measurement covers + +### Sandbox start + +- **Sandbox create**: Core's `create` step, from the Provider call to a booted sandbox. +- **Sandbox created → initialization start**: from the end of `create` until Core starts preparing the environment. It covers the Runtime starting, connecting to Core and Core claiming the initialization. Core logs that start only for an Environment with files or setup work, so this row covers the cold-start Sessions below. + +### Environment ready + +**Session created → environment ready** runs from `agent.session.created` to `agent.session.environment.ready` as an application on the Core host receives them on its stream, so it includes queueing, sandbox start and preparation. Core sends stream events in 100 ms steps. + +Each cold-start sample uses a new Template with one npm package (`prettier@3.3.3`), one file and one setup command. Its first Session misses the [preparation cache](../contracts/agents-api/environments.md#preparation-reuse) and installs everything; **npm install** is that installation's `npm` step as the Runtime timed it, and it depends on the package registry. Its second Session restores the prepared result. + +**Free slot** and **full node** cover Sessions without a Template, started one after another. The first ones found a free slot. Once the node ran its maximum number of sandboxes, each waited for Core to [suspend](./sandbox-provider.md#suspension) an idle sandbox. + +### Suspend and resume + +- **Suspend**: Core's `suspend` step. The node captures the sandbox's memory and disk to a checkpoint and stops it. A Session suspends after the idle timeout, or earlier under capacity pressure as [Suspension](./sandbox-provider.md#suspension) describes. +- **Resume → sandbox running**: from the start of Core's `resume` step until the sandbox is running again. It covers restoring the checkpoint, waking the Runtime, confirming that the Environment resumed and deleting the checkpoint. The first run leaves the node's page cache as it is. +- **Turn first text**: from sending input to the first output text delta, measured by the application like Environment ready, once for the Turn that resumes a suspended Session and once for the next Turn on the same running Session. The difference is the wait a resume adds; the rest is the model. + +### E2B + +The E2B rows are durations of SDK calls on the client: `Sandbox.create`, `pause`, and `connect` plus one command for a resume. Each call includes at least one API round trip from the client, listed as **E2B API round trip** on a kept-alive connection. Sandboxes on both sides have 2 CPUs and 4 GiB of memory, which `e2b.jsonl` records for E2B, and resume after the same idle wait. They differ in: + +- **Clock**: the E2B rows are timed on the client. The sandbox rows for OpenAgentCore come from Core's log, and Core reaches its node over a 0.2 ms network. +- **Start of a create**: E2B's starts at the client's API call. Core's `create` step starts at the Provider call and leaves out Core's scheduling before it. +- **Workload**: before it pauses, each E2B sandbox holds 650 MiB in a process and has written 100 MiB to disk. Each OpenAgentCore sandbox has run one Codex Turn. +- **End of a resume**: E2B's ends when the first command returns, after one call to the API and one to the sandbox. OpenAgentCore's ends when Core records the sandbox running: the Runtime has reconnected, the Environment has resumed and the checkpoint is deleted. + +## Setup + +- **Revision**: Core at `c5d4205d`; the sandbox node and Runtime at `170a4983`, whose later changes do not touch these steps. Measured on 2026-10-25. +- **Hosts**: Core and one microsandbox node on two Intel Xeon 6982P-C cloud VMs with Ubuntu 22.04 and Linux 5.15, with a 0.2 ms ping between them. Core has 8 vCPUs and 62 GiB; the node has 4 vCPUs and 15 GiB and runs at most 3 sandboxes and retains at most 14. +- **Sandboxes**: 2 CPUs, 4 GiB of memory and an 8 GiB root disk each, with the workspace on NFSv4.2. Idle sandboxes suspend after 300 s. +- **Sessions**: Codex with MiniMax-M2.7 at `https://api.minimaxi.com/v1`, driven from the Core host with `openai` 3.13.0, 10 samples of each phase. +- **E2B**: a template with 2 vCPUs and 4 GiB, made from one that `build-template.py` built from the Runtime image of 2026-10-12, driven with `e2b` 2.51.0 from a client 0.20 s from the API, 10 sandboxes. + +## Reproduce + +Run on an installation with no other activity: the report reads every lifecycle step Core logs during the run. + +1. Install OpenAgentCore, add a microsandbox node with workspace storage, set a default model and issue a Project API key, as in [Install Core and Web](./getting-started/install.md). The Sessions need the default 300 s idle timeout and a node that runs fewer than 10 sandboxes at once, so that the later ones find it full; `report` stops with an error when a measurement has no samples. +2. On the Core host, with Python 3.10 or later and `pip install openai==3.13.0`, set `OPENAI_BASE_URL` and `OPENAI_API_KEY` and run the Sessions. It takes about 15 minutes, 7 of them waiting for the idle timeout: + + ```sh + python3 scripts/benchmark.py sessions results --model MiniMax-M2.7 --harness codex + ``` + +3. Save the Core log and build the table. The report keeps the log lines it uses in `results/core.jsonl`: + + ```sh + docker compose -f ~/.oac/core/compose.yaml logs --no-log-prefix core > core.log + python3 scripts/benchmark.py report results core.log + ``` + +4. To resume from disk, repeat step 2 into `results/cold`. About 6 minutes after it prints `waiting 420 s for the idle timeout`, when every Session has suspended, drop the page cache on the node with `sync; echo 3 | sudo tee /proc/sys/vm/drop_caches`. Then repeat step 3 for `results/cold`. +5. For E2B, `pip install e2b==2.51.0`, set `E2B_API_KEY` and build a template from the Runtime image with [Build a template](https://github.com/MiniMax-AI/OpenAgentCore/blob/main/services/core/deploy/e2b/README.md#build-a-template) and `--memory-mb 4096`, then run `report` again: + + ```sh + python3 scripts/benchmark.py e2b results --template