Skip to content

Commit 914d2a8

Browse files
authored
Qualify public Session creation and usage semantics (#581)
1 parent 92a4ecd commit 914d2a8

5 files changed

Lines changed: 254 additions & 31 deletions

File tree

‎contracts/agents-api/harness-onboarding.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ python services/core/tests/qualify_public_native.py \
224224

225225
| Suite | Operations | Placement |
226226
| --- | --- | --- |
227-
| `none` | Creation retry, foreign history rejection, two native text Turns, history recall, SSE ordering and SDK/raw Item and Turn parity | `none` |
227+
| `none` | Initial-input creation/retry/conflict with one Turn, foreign history rejection, two native text Turns, history recall, SSE ordering, SDK/raw schema parity and nullable usage accounting | `none` |
228228
| `pending-actions` | Query/reconnect pending calls, success/error results, cancellation, exact target rejection, retries and durable Items | Any declared placement with function tools |
229229
| `functions` | SDK handlers, success/error, native file and Artifact bytes, continuation, pending cancellation and tenant isolation | Workspace |
230230
| `images` | Initial and active images, image results, retry/atomic rejection, native files/Artifacts, isolation and continuation | Workspace with declared image and function support |
@@ -239,6 +239,8 @@ For `self_hosted`, choose a custom absolute `workspace_directory`. When the runn
239239

240240
Warm continuation is the default and records cold recovery as `unverified`. To qualify cold continuation, additionally pass `--compose-directory` with the owned installation's absolute directory and `--compose-project` with its exact project name. The runner restarts only that project's `agent-host`, confirms its container start time changed, and then runs the unchanged history assertions. This does not qualify a Core restart or a sandbox checkpoint restore. The `pending-actions` suite reconnects the public client, not the agent-host process, and rejects those restart options. Select cold recovery only where the [declaration and coverage ledger](./index.md#known-gaps) support it; unsupported recovery remains a gap, never a successful skipped check. An API rejection fails the selected suite.
241241

242+
The `none` suite validates required and nullable Session, Turn, Item and event fields against the pinned schema. When native Turns supply measured usage, it checks the terminal event against the stored Turn and sums the measurements into Session totals. Unknown usage remains `null` and each affected Turn is listed in the evidence’s `proof.unverified`; a passing suite does not claim native measurement support for those Turns.
243+
242244
Run `python -m unittest discover -s services/core/tests -p qualify_public_native_test.py` with the pinned SDK to check credential handling and the owned restart boundary without a model. Existing deterministic Core integration tests remain the authority for schema validation, atomic admission, durable receipts and rejection semantics. Real-model results qualify only the selected suite, protocol, Harness and placement. Provider lifecycle, native identity, credential isolation, deferred discovery and unselected suites need separate evidence; view-only results do not qualify the public path.
243245

244246
## Native version pins

‎contracts/agents-api/zh/harness-onboarding.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: "添加 Harness"
33
source: contracts/agents-api/harness-onboarding.md
4-
source_hash: 32b85617efe41a23bd25768a42fd7a57019c75ae723d07d8cc5106124709f402
4+
source_hash: 84ebd7cebed1995c89a59f8c4c71542ca41ef6ccc890b4eba96340a970ae161c
55
---
66

77
**Harness** 是一种运行模型和工具循环的原生代理引擎(Codex、Claude Code、MiniMax Code)。**Harness 适配器**将 Runtime 的 Executor 和 Turn 契约转换到该引擎的 SDK 或协议。本文档定义 Runtime–Harness 协议:适配器接口及其生命周期义务、注册、支持声明和验收。
@@ -226,7 +226,7 @@ python services/core/tests/qualify_public_native.py \
226226

227227
| 套件 | 操作 | 放置方式 |
228228
| --- | --- | --- |
229-
| `none` | 创建重试、外部历史拒绝、两个原生文本 Turn、历史回忆、SSE 顺序,以及 SDK/原始 Item 和 Turn 一致性 | `none` |
229+
| `none` | 带初始输入的创建、重试和冲突保持单个 Turn,跨项目历史拒绝,两个原生文本 Turn,历史回忆,SSE 顺序,SDK/原始响应 schema 一致性与可空 usage 核算 | `none` |
230230
| `pending-actions` | 查询和重连待处理调用、成功/错误结果、取消、精确目标拒绝、重试和持久化 Item | 声明支持函数工具的任意放置方式 |
231231
| `functions` | SDK handler、成功/错误、原生文件和 Artifact 字节、继续执行、待处理调用取消和租户隔离 | 工作区 |
232232
| `images` | 初始和活动图像、图像结果、重试/原子拒绝、原生文件/Artifact、隔离和继续执行 | 声明支持图像和函数的工作区 |
@@ -241,6 +241,8 @@ python services/core/tests/qualify_public_native.py \
241241

242242
默认验证热继续执行,并将冷恢复记录为 `unverified`。验证冷继续执行时,额外传入指向所拥有安装的绝对目录的 `--compose-directory`,以及指定其精确项目名称的 `--compose-project`。运行器仅重启该项目的 `agent-host`,确认容器启动时间已改变,然后执行相同的历史断言。这不能证明 Core 重启或 sandbox 检查点恢复。`pending-actions` 套件重连的是公共客户端,而非 agent-host 进程,因此拒绝这些重启选项。仅在[声明和覆盖台账](./index.md#known-gaps) 支持时选择冷恢复;不支持的恢复仍是缺口,不能把跳过的检查记为成功。API 拒绝会使所选套件失败。
243243

244+
`none` 套件依据固定版本 schema 校验 Session、Turn、Item 和事件的必需字段及可空字段。原生 Turn 提供用量测量时,它会对比终止事件与已存储 Turn,并将测量值求和核对 Session 总量。未知用量保留为 `null`,每个受影响 Turn 都列入证据的 `proof.unverified`;套件通过不代表这些 Turn 已验证原生用量测量支持。
245+
244246
使用锁定的 SDK 运行 `python -m unittest discover -s services/core/tests -p qualify_public_native_test.py`,可在不调用模型的情况下检查凭据处理和所拥有的重启边界。现有确定性 Core 集成测试仍负责 schema 验证、原子准入、持久化回执和拒绝语义。真实模型结果仅证明所选套件、协议、Harness 和放置方式。Provider 生命周期、原生身份、凭据隔离、延迟发现和未选择的套件需要独立证据;仅通过 view 测试不能证明公共调用路径。
245247

246248
## 原生版本固定 {#native-version-pins}

‎services/core/tests/official_session_initial_input.py‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,18 @@
1010
from official_session_creation_stream import verify_creation_streams
1111

1212

13+
def verify_initial_input_retry(sessions, raw, endpoint, headers, request, session_id):
14+
"""Retry and conflict preserve the one Turn admitted by Session creation."""
15+
turns = [turn.id for turn in sessions.turns.list(session_id)]
16+
assert len(turns) == 1
17+
reply = raw.post(endpoint, headers=headers, json=request)
18+
assert reply.status_code == 201 and reply.json()["id"] == session_id
19+
changed = raw.post(endpoint, headers=headers, json={**request, "input": "Changed " + uuid.uuid4().hex})
20+
assert changed.status_code == 409
21+
assert [turn.id for turn in sessions.turns.list(session_id)] == turns
22+
return reply, changed
23+
24+
1325
def main():
1426
base, token, foreign, unsupported = sys.argv[1:]
1527
headers = {"Authorization": "Bearer " + token, "OpenAI-Beta": "agents=v1"}
@@ -56,16 +68,11 @@ def main():
5668
assert len(turns) == 1
5769
items = list(sessions.items.list(session.id, order="asc"))
5870
assert [item.content[0].text for item in items] == (["First"] if i == 0 else ["First", "Second"])
59-
reply = raw.post(base + "/v1/agents/sessions", headers={**headers, **key},
60-
json={**configuration, "input": initial})
61-
assert reply.status_code == 201 and reply.json()["id"] == session.id
62-
assert [turn.id for turn in sessions.turns.list(session.id)] == [turns[0].id]
71+
verify_initial_input_retry(sessions, raw, base + "/v1/agents/sessions", {**headers, **key},
72+
{**configuration, "input": initial}, session.id)
6373
denied = raw.get(base + "/v1/agents/sessions/" + session.id,
6474
headers={**headers, "Authorization": "Bearer " + foreign})
6575
assert denied.status_code == 404
66-
changed = raw.post(base + "/v1/agents/sessions", headers={**headers, **key},
67-
json={**configuration, "input": "Changed"})
68-
assert changed.status_code == 409
6976
sessions.events.create(session.id, events=[{"type": "agent.session.input.cancel"}])
7077
assert sessions.create(**configuration, input=initial, extra_headers=key).status == "idle"
7178
assert len(list(sessions.turns.list(session.id))) == 1

‎services/core/tests/qualify_public_native.py‎

Lines changed: 93 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,14 @@
1414

1515
import httpx2
1616
from openai import OpenAI
17+
from jsonschema import Draft202012Validator
1718

1819
from official_hosted_functions_native import verify_hosted_functions
1920
from official_hosted_structured_native import verify_hosted_structured
2021
from official_pending_actions_native import verify_pending_actions
2122
from official_workspace_images_native import verify_workspace_images
23+
from official_schema import ResponseValidator
24+
from official_session_initial_input import verify_initial_input_retry
2225
from official_environment_composition import verify_composition
2326
from session_cleanup import delete_session
2427

@@ -33,46 +36,116 @@ def verify_none(client, foreign, http, agent_options, session_options, ready, re
3336
sessions = client.beta.agents.sessions
3437
marker = "memory-" + uuid.uuid4().hex
3538
key = "create-" + uuid.uuid4().hex
36-
session = sessions.create(agent=agent_options, **session_options, idempotency_key=key)
37-
proof = {"checks": [], "session": session.id, "runs": []}
38-
root = str(client.base_url).rstrip("/") + "/agents/sessions/" + session.id
39+
initial = "Remember " + marker + ". Reply with exactly that string. Do not use tools."
40+
request = {"agent": agent_options, **session_options, "input": initial}
41+
request.update(request.pop("extra_body", {}))
42+
endpoint = str(client.base_url).rstrip("/") + "/agents/sessions"
3943
headers = {"Authorization": "Bearer " + client.api_key, "OpenAI-Beta": "agents=v1"}
44+
validate = ResponseValidator(Path(__file__).resolve().parents[3] / "contracts/agents-api/openapi.yaml")
45+
events_schema = Draft202012Validator({"components": validate.contract["components"],
46+
"$ref": "#/components/schemas/SessionEvent"})
47+
session = None
48+
proof = {"checks": [], "runs": [], "snapshots": [], "unverified": []}
4049
try:
41-
assert sessions.create(agent=agent_options, **session_options, idempotency_key=key).id == session.id
42-
ready(session)
43-
for suffix in ("", "/items", "/turns"):
44-
assert http.get(root + suffix, headers={**headers, "Authorization": "Bearer " + foreign.api_key}).status_code == 404
45-
proof["checks"].append("create_retry_and_foreign_history_rejection")
46-
for index, prompt in enumerate(("Remember " + marker + ". Reply with exactly that string. Do not use tools.",
47-
"Recall the string from our previous turn. Reply with exactly that string. Do not use tools.")):
48-
if index and restart is not None:
49-
restart()
50-
with sessions.stream(session.id, input=prompt, idempotency_key=key + str(index), timeout=240) as stream:
51-
events = [event.to_dict() for event in stream]
50+
for index in range(2):
51+
if index == 0:
52+
stream = sessions.create(agent=agent_options, **session_options, input=initial,
53+
stream=True, extra_headers={"Idempotency-Key": key}, timeout=240)
54+
else:
55+
if restart is not None:
56+
restart()
57+
stream = sessions.stream(session.id,
58+
input="Recall the string from our previous turn. Reply with exactly that string. Do not use tools.",
59+
idempotency_key=key + "-continue", timeout=240)
60+
events = []
5261
proof["runs"].append(events)
62+
with stream:
63+
for event in stream:
64+
value = event.to_dict()
65+
events.append(value)
66+
if index == 0 and len(events) == 1:
67+
assert event.type == "agent.session.created"
68+
session = event.session
69+
proof["session"] = session.id
70+
events_schema.validate(value)
71+
ready(session)
72+
root = endpoint + "/" + session.id
73+
# Admission has committed before the first creation event.
74+
for response in verify_initial_input_retry(sessions, http, endpoint,
75+
{**headers, "Idempotency-Key": key}, request, session.id):
76+
validate(response)
77+
assert sessions.create(agent=agent_options, **session_options, input=initial,
78+
extra_headers={"Idempotency-Key": key}).id == session.id
79+
for suffix in ("", "/items", "/turns"):
80+
response = http.get(root + suffix, headers={**headers, "Authorization": "Bearer " + foreign.api_key})
81+
assert response.status_code == 404
82+
validate(response)
83+
else:
84+
events_schema.validate(value)
5385
record(proof)
5486
types = [event["type"] for event in events]
5587
terminals = [event for event in events if event["type"] in {
5688
"agent.session.turn.completed", "agent.session.turn.failed", "agent.session.turn.cancelled"}]
5789
assert len(terminals) == 1 and terminals[0]["type"] == "agent.session.turn.completed"
90+
terminal = terminals[0]
5891
assert types[-1] == "agent.session.idle"
92+
assert types.count("agent.session.turn.created") == 1
5993
assert types.index("agent.session.turn.created") < types.index("agent.session.turn.completed") < len(types) - 1
6094
assert len({event["event_id"] for event in events}) == len(events)
95+
assert all("usage" not in event for event in events if event is not terminal)
96+
snapshots = {}
6197
for name in ("items", "turns"):
6298
response = http.get(root + "/" + name, headers=headers, params={"limit": 100, "order": "asc"})
6399
assert response.status_code == 200 and not response.json()["has_more"]
100+
validate(response)
64101
expected = getattr(sessions, name).list(session.id, limit=100, order="asc").to_dict()
65102
assert response.json() == expected
66-
items = list(sessions.items.list(session.id, limit=100, order="asc"))
67-
answers = [item.to_dict() for item in items if item.type == "message" and item.role == "assistant"]
103+
snapshots[name] = response.json()["data"]
104+
response = http.get(root, headers=headers)
105+
assert response.status_code == 200
106+
validate(response)
107+
current = response.json()
108+
assert current == sessions.retrieve(session.id).to_dict()
109+
assert current["status"] == "idle" and current["required_actions"] == [] and current["error"] is None
110+
turns = snapshots["turns"]
111+
assert len(turns) == index + 1
112+
assert all(turn["status"] == "completed" and turn["error"] is None and turn["subagent_id"] is None for turn in turns)
113+
assert terminal["turn_id"] == turns[-1]["id"]
114+
assert terminal["turn"] == turns[-1] and terminal["usage"] == turns[-1]["usage"]
115+
answers = [item for item in snapshots["items"] if item["type"] == "message" and item["role"] == "assistant"]
68116
assert marker in "".join(part.get("text", "") for part in answers[-1]["content"])
69-
assert len(sessions.turns.list(session.id).data) == index + 1
70-
assert sessions.retrieve(session.id).required_actions == []
71-
proof["checks"].append(("cold_agent_host" if restart is not None else "warm") + "_text_history_sse_and_sdk_raw_parity")
117+
measured = [turn["usage"] for turn in turns if turn["usage"] is not None]
118+
for usage in measured:
119+
assert usage["input_tokens"] > 0 and usage["output_tokens"] > 0
120+
assert usage["total_tokens"] == usage["input_tokens"] + usage["output_tokens"]
121+
assert 0 <= usage["input_tokens_details"]["cached_tokens"] <= usage["input_tokens"]
122+
assert 0 <= usage["output_tokens_details"]["reasoning_tokens"] <= usage["output_tokens"]
123+
if len(measured) == len(turns):
124+
totals = {field: sum(usage[field] for usage in measured)
125+
for field in ("input_tokens", "output_tokens", "total_tokens")}
126+
for field, detail in (("input_tokens_details", "cached_tokens"), ("output_tokens_details", "reasoning_tokens")):
127+
totals[field] = {detail: sum(usage[field][detail] for usage in measured)}
128+
assert current["usage"] == totals
129+
else:
130+
assert current["usage"] is None
131+
for turn in turns:
132+
if turn["usage"] is None:
133+
gap = "Native measured usage unavailable for Turn " + turn["id"]
134+
if gap not in proof["unverified"]:
135+
proof["unverified"].append(gap)
136+
proof["snapshots"].append({**snapshots, "session": current})
137+
if index == 0:
138+
for response in verify_initial_input_retry(sessions, http, endpoint,
139+
{**headers, "Idempotency-Key": key}, request, session.id):
140+
validate(response)
141+
proof["checks"].append("initial_input_create_retry_conflict_one_native_turn_and_foreign_history_rejection")
142+
proof["checks"].append("native_usage_measurements_or_explicit_unknown_and_session_totals")
143+
proof["checks"].append(("cold_agent_host" if restart is not None else "warm") + "_text_history_sse_and_sdk_raw_schema_parity")
72144
return proof["checks"]
73145
finally:
74146
record(proof)
75-
delete_session(sessions, session.id)
147+
if session is not None:
148+
delete_session(sessions, session.id)
76149

77150

78151
def main():

0 commit comments

Comments
 (0)