bailinghub 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/docker-compose.images.yml +2 -2
  5. package/docs/CHANGELOG.en.md +12 -1
  6. package/docs/CHANGELOG.md +12 -1
  7. package/docs/IMPLEMENTATION_STATUS.en.md +12 -3
  8. package/docs/IMPLEMENTATION_STATUS.md +12 -3
  9. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  10. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  11. package/docs/README.en.md +2 -0
  12. package/docs/README.md +2 -0
  13. package/docs/RELEASE_NOTES_v0.10.1.en.md +41 -0
  14. package/docs/RELEASE_NOTES_v0.10.1.md +41 -0
  15. package/docs/UPGRADE_v0.10.1.en.md +66 -0
  16. package/docs/UPGRADE_v0.10.1.md +66 -0
  17. package/package.json +5 -3
  18. package/scripts/check-doc-links.mjs +2 -0
  19. package/scripts/check-image-tags.sh +1 -1
  20. package/scripts/check-php-sdk-artifacts.mjs +152 -0
  21. package/scripts/check-php-sdk-artifacts.test.mjs +99 -0
  22. package/scripts/check-release-consistency.test.mjs +2 -2
  23. package/scripts/install.sh +1 -1
  24. package/scripts/publish-images.sh +1 -1
  25. package/scripts/release-audit.mjs +5 -1
  26. package/scripts/sdk-declaration-contract-test.ts +34 -0
  27. package/scripts/sdk-p1-check.mjs +62 -26
  28. package/scripts/verify-github-repo.mjs +4 -0
  29. package/sdk/dotnet/Bailing.Connect/BailingConnect.cs +4 -4
  30. package/sdk/dotnet/README.md +8 -0
  31. package/sdk/dotnet/tests/Declaration/Declaration.csproj +11 -0
  32. package/sdk/dotnet/tests/Declaration/Program.cs +74 -0
  33. package/sdk/go/README.md +8 -0
  34. package/sdk/go/bailingconnect/connect.go +5 -5
  35. package/sdk/go/bailingconnect/declaration_test.go +107 -0
  36. package/sdk/java/README.md +13 -0
  37. package/sdk/java/src/main/java/com/bailing/connect/BailingConnect.java +4 -4
  38. package/sdk/java/tests/DeclarationTest.java +70 -0
  39. package/sdk/node/README.md +8 -0
  40. package/sdk/node/src/index.mjs +4 -4
  41. package/sdk/node/tests/declaration.test.mjs +41 -0
  42. package/sdk/php/README.md +16 -0
  43. package/sdk/php/src/Attributes/AiTool.php +4 -4
  44. package/sdk/php/src/SpecBuilder.php +8 -8
  45. package/sdk/php/tests/declaration-serialization.php +103 -0
  46. package/sdk/php7/README.md +14 -0
  47. package/sdk/php7/src/ToolDef.php +3 -3
  48. package/sdk/php7/src/ToolSpec.php +8 -13
  49. package/sdk/php7/tests/declaration-serialization.php +103 -0
  50. package/sdk/python/README.md +8 -0
  51. package/sdk/python/bailing_connect/__init__.py +6 -6
  52. package/sdk/python/tests/test_declaration.py +61 -0
  53. package/src/core/contracts/explicit-capability-values.test.ts +62 -0
  54. package/src/core/contracts/openapi-tools.ts +2 -2
  55. package/src/core/contracts/tool-annotations.ts +4 -4
  56. package/web/connect/bailing-connect-php.tgz +0 -0
  57. package/web/connect/bailing-connect-php7.tgz +0 -0
  58. package/web-admin/package-lock.json +4 -4
  59. package/web-admin/package.json +1 -1
@@ -0,0 +1,74 @@
1
+ using System.Text.Json;
2
+ using Bailing.Connect;
3
+
4
+ static JsonElement Capability(Tool tool)
5
+ {
6
+ var spec = BailingConnect.BuildOpenApiSpec("Fixture", "1", [tool]);
7
+ using var json = JsonDocument.Parse(BailingConnect.ToJson(spec));
8
+ return json.RootElement.GetProperty("paths").GetProperty("/fixture")
9
+ .GetProperty(tool.Method.ToLowerInvariant()).GetProperty("x-agent-capability").Clone();
10
+ }
11
+
12
+ static void Check(bool condition, string message)
13
+ {
14
+ if (!condition) throw new InvalidOperationException(message);
15
+ }
16
+
17
+ static Tool Fixture(string method, bool? readonlyValue = null, string risk = "", bool? idempotent = null)
18
+ {
19
+ // Exercise the real property default when risk is omitted.
20
+ if (risk == "") return new Tool
21
+ {
22
+ Name = "serialization_fixture", Description = "Declaration serialization fixture",
23
+ Scope = "fixture.write", Path = "/fixture", Method = method,
24
+ Readonly = readonlyValue, Idempotent = idempotent,
25
+ Params = [new Param { Name = "fixture" }]
26
+ };
27
+ return new Tool
28
+ {
29
+ Name = "serialization_fixture", Description = "Declaration serialization fixture",
30
+ Scope = "fixture.write", Path = "/fixture", Method = method,
31
+ Readonly = readonlyValue, Risk = risk, Idempotent = idempotent,
32
+ Params = [new Param { Name = "fixture" }]
33
+ };
34
+ }
35
+
36
+ int matrix = 0, idempotency = 0;
37
+ foreach (var method in new[] { "GET", "POST" })
38
+ {
39
+ foreach (bool? readonlyValue in new bool?[] { null, false, true })
40
+ {
41
+ foreach (var risk in new[] { "", "low", "medium", "high" })
42
+ {
43
+ var cap = Capability(Fixture(method, readonlyValue, risk));
44
+ var hasExecution = cap.TryGetProperty("execution", out var execution);
45
+ JsonElement readonlyJson = default;
46
+ var hasReadonly = hasExecution && execution.TryGetProperty("readonly", out readonlyJson);
47
+ var label = $"{method} readonly={readonlyValue} risk={risk}";
48
+ Check(hasReadonly == readonlyValue.HasValue, label + " readonly presence");
49
+ if (readonlyValue.HasValue) Check(readonlyJson.GetBoolean() == readonlyValue.Value, label + " readonly value");
50
+ var hasRisk = cap.TryGetProperty("risk", out var riskJson);
51
+ Check(hasRisk == (risk != ""), label + " risk presence");
52
+ if (hasRisk) Check(riskJson.GetProperty("level").GetString() == risk, label + " risk value");
53
+ var expectedReadonly = readonlyValue ?? (method == "GET");
54
+ var expectedRisk = risk != "" ? risk : (expectedReadonly ? "low" : "medium");
55
+ var effectiveReadonly = hasReadonly ? readonlyJson.GetBoolean() : method == "GET";
56
+ var effectiveRisk = hasRisk ? riskJson.GetProperty("level").GetString() : (effectiveReadonly ? "low" : "medium");
57
+ Check(effectiveRisk == expectedRisk, label + " effective risk");
58
+ Check(cap.GetProperty("version").GetInt32() == 1, label + " declaration version");
59
+ matrix++;
60
+ }
61
+ }
62
+ foreach (bool? value in new bool?[] { null, false, true })
63
+ {
64
+ var cap = Capability(Fixture(method, idempotent: value));
65
+ var hasExecution = cap.TryGetProperty("execution", out var execution);
66
+ JsonElement idempotentJson = default;
67
+ var present = hasExecution && execution.TryGetProperty("idempotent", out idempotentJson);
68
+ Check(present == value.HasValue, method + " idempotent presence");
69
+ if (value.HasValue) Check(idempotentJson.GetBoolean() == value.Value, method + " idempotent value");
70
+ idempotency++;
71
+ }
72
+ }
73
+ Check(matrix == 24 && idempotency == 6, "matrix completeness");
74
+ Console.WriteLine("PASS: 24 readonly/risk combinations + 6 idempotent combinations");
package/sdk/go/README.md CHANGED
@@ -31,3 +31,11 @@ ok := bailingconnect.VerifyToolCall(secret, method, pathWithQuery, rawBody, time
31
31
  ```
32
32
 
33
33
  Verification proves the call came from the hub. Your business service must still authorize `onBehalfOf` against its own permission table.
34
+
35
+ ## Omitted and explicit declaration values
36
+
37
+ Unspecified `risk`, `readonly`, and `idempotent` fields stay absent from ACC. Explicit low/medium/high risk and both boolean values are preserved, including false on GET. With risk omitted, the ACC OpenAPI binding gives an explicit readonly value precedence over the HTTP method: GET without a readonly declaration defaults to low; other non-readonly operations default to medium. Risk does not replace approval or final business authorization.
38
+
39
+ Regenerate and compare declarations when upgrading; do not turn previously omitted risk into explicit low for all operations. `Tool.Risk == ""` remains the omission marker; `Readonly` and `Idempotent` use nil for omission and pointers for explicit values.
40
+
41
+ Run `go test ./...` from `sdk/go` for the 24 readonly/risk cases and 6 idempotency cases.
@@ -129,7 +129,7 @@ func normalizeRateLimit(value string) map[string]any {
129
129
 
130
130
  func buildCapability(t Tool, method string) map[string]any {
131
131
  capability := map[string]any{"version": 1, "enabled": true, "scope": t.Scope}
132
- if t.Risk != "" && t.Risk != "low" {
132
+ if t.Risk != "" {
133
133
  capability["risk"] = map[string]any{"level": t.Risk}
134
134
  }
135
135
  if t.Confirm || len(t.ConfirmWhen) > 0 || t.ConfirmPrompt != "" {
@@ -149,11 +149,11 @@ func buildCapability(t Tool, method string) map[string]any {
149
149
  capability["subject"] = map[string]any{"required": true}
150
150
  }
151
151
  execution := map[string]any{}
152
- if t.Readonly != nil && *t.Readonly && method != "GET" {
153
- execution["readonly"] = true
152
+ if t.Readonly != nil {
153
+ execution["readonly"] = *t.Readonly
154
154
  }
155
- if t.Idempotent != nil && *t.Idempotent && method != "GET" {
156
- execution["idempotent"] = true
155
+ if t.Idempotent != nil {
156
+ execution["idempotent"] = *t.Idempotent
157
157
  }
158
158
  if rl := normalizeRateLimit(t.RateLimit); rl != nil {
159
159
  execution["rate_limit"] = rl
@@ -0,0 +1,107 @@
1
+ package bailingconnect
2
+
3
+ import (
4
+ "encoding/json"
5
+ "fmt"
6
+ "testing"
7
+ )
8
+
9
+ func declarationFixture(method string) Tool {
10
+ return Tool{Name: "serialization_fixture", Description: "Declaration serialization fixture", Scope: "fixture.write", Path: "/fixture", Method: method, Params: []Param{{Name: "fixture", Type: "string"}}}
11
+ }
12
+
13
+ func serializedCapability(t *testing.T, tool Tool) map[string]any {
14
+ t.Helper()
15
+ spec := BuildOpenAPISpec("Fixture", "1", []Tool{tool}, nil)
16
+ encoded, err := json.Marshal(spec)
17
+ if err != nil {
18
+ t.Fatal(err)
19
+ }
20
+ var decoded map[string]any
21
+ if err := json.Unmarshal(encoded, &decoded); err != nil {
22
+ t.Fatal(err)
23
+ }
24
+ method := "get"
25
+ if tool.Method == "POST" {
26
+ method = "post"
27
+ }
28
+ return decoded["paths"].(map[string]any)["/fixture"].(map[string]any)[method].(map[string]any)["x-agent-capability"].(map[string]any)
29
+ }
30
+
31
+ func executionOf(cap map[string]any) map[string]any {
32
+ if execution, ok := cap["execution"].(map[string]any); ok {
33
+ return execution
34
+ }
35
+ return map[string]any{}
36
+ }
37
+
38
+ func TestDeclarationReadonlyRiskMatrix(t *testing.T) {
39
+ no, yes := false, true
40
+ cases := 0
41
+ for _, method := range []string{"GET", "POST"} {
42
+ for ri, readonly := range []*bool{nil, &no, &yes} {
43
+ for _, risk := range []string{"", "low", "medium", "high"} {
44
+ cases++
45
+ t.Run(fmt.Sprintf("%s/readonly_%d/risk_%s", method, ri, risk), func(t *testing.T) {
46
+ tool := declarationFixture(method)
47
+ tool.Readonly, tool.Risk = readonly, risk
48
+ cap := serializedCapability(t, tool)
49
+ execution := executionOf(cap)
50
+ gotReadonly, hasReadonly := execution["readonly"]
51
+ if hasReadonly != (readonly != nil) || (readonly != nil && gotReadonly != *readonly) {
52
+ t.Fatalf("readonly not preserved: %#v", cap)
53
+ }
54
+ gotRisk, hasRisk := cap["risk"]
55
+ if hasRisk != (risk != "") || (risk != "" && gotRisk.(map[string]any)["level"] != risk) {
56
+ t.Fatalf("risk not preserved: %#v", cap)
57
+ }
58
+ expectedReadonly := method == "GET"
59
+ if readonly != nil {
60
+ expectedReadonly = *readonly
61
+ }
62
+ expectedRisk := risk
63
+ if expectedRisk == "" {
64
+ expectedRisk = "medium"
65
+ if expectedReadonly {
66
+ expectedRisk = "low"
67
+ }
68
+ }
69
+ effectiveReadonly := method == "GET"
70
+ if hasReadonly {
71
+ effectiveReadonly = gotReadonly.(bool)
72
+ }
73
+ effectiveRisk := "medium"
74
+ if effectiveReadonly {
75
+ effectiveRisk = "low"
76
+ }
77
+ if hasRisk {
78
+ effectiveRisk = gotRisk.(map[string]any)["level"].(string)
79
+ }
80
+ if effectiveRisk != expectedRisk {
81
+ t.Fatalf("effective risk = %s, want %s", effectiveRisk, expectedRisk)
82
+ }
83
+ })
84
+ }
85
+ }
86
+ }
87
+ if cases != 24 {
88
+ t.Fatalf("matrix contains %d cases", cases)
89
+ }
90
+ }
91
+
92
+ func TestDeclarationIdempotentPresence(t *testing.T) {
93
+ no, yes := false, true
94
+ for _, method := range []string{"GET", "POST"} {
95
+ for i, value := range []*bool{nil, &no, &yes} {
96
+ t.Run(fmt.Sprintf("%s/idempotent_%d", method, i), func(t *testing.T) {
97
+ tool := declarationFixture(method)
98
+ tool.Idempotent = value
99
+ execution := executionOf(serializedCapability(t, tool))
100
+ actual, present := execution["idempotent"]
101
+ if present != (value != nil) || (value != nil && actual != *value) {
102
+ t.Fatalf("idempotent not preserved: %#v", execution)
103
+ }
104
+ })
105
+ }
106
+ }
107
+ }
@@ -41,3 +41,16 @@ boolean ok = BailingConnect.verifyToolCall(
41
41
  ```
42
42
 
43
43
  Verification proves the call came from the hub. Your business service must still authorize `onBehalfOf` against its own permission table.
44
+
45
+ ## Omitted and explicit declaration values
46
+
47
+ Unspecified `risk`, `readonly`, and `idempotent` fields stay absent from ACC. Explicit low/medium/high risk and both boolean values are preserved, including false on GET. With risk omitted, the ACC OpenAPI binding gives an explicit readonly value precedence over the HTTP method: GET without a readonly declaration defaults to low; other non-readonly operations default to medium. Risk does not replace approval or final business authorization.
48
+
49
+ Regenerate and compare declarations when upgrading; do not turn previously omitted risk into explicit low for all operations. An unspecified `Tool.risk` is now null rather than `"low"`; code that reads the intermediate Tool object must handle null. `readonly` and `idempotent` remain nullable Boolean values.
50
+
51
+ ```bash
52
+ javac -d /tmp/bailing-java sdk/java/src/main/java/com/bailing/connect/BailingConnect.java sdk/java/tests/DeclarationTest.java
53
+ java -cp /tmp/bailing-java DeclarationTest
54
+ ```
55
+
56
+ This checks 24 readonly/risk combinations and 6 idempotency combinations.
@@ -88,7 +88,7 @@ public final class BailingConnect {
88
88
 
89
89
  private static Map<String, Object> buildCapability(Tool t, String method) {
90
90
  Map<String, Object> capability = mapOf("version", 1, "enabled", true, "scope", t.scope);
91
- if (t.risk != null && !"low".equals(t.risk)) capability.put("risk", mapOf("level", t.risk));
91
+ if (t.risk != null) capability.put("risk", mapOf("level", t.risk));
92
92
  if (t.confirm || !t.confirmWhen.isEmpty() || t.confirmPrompt != null) {
93
93
  Map<String, Object> approval = new LinkedHashMap<>();
94
94
  if (t.confirm) approval.put("required", true);
@@ -98,8 +98,8 @@ public final class BailingConnect {
98
98
  }
99
99
  if (t.requiresSubject) capability.put("subject", mapOf("required", true));
100
100
  Map<String, Object> execution = new LinkedHashMap<>();
101
- if (Boolean.TRUE.equals(t.readonly) && !"GET".equals(method)) execution.put("readonly", true);
102
- if (Boolean.TRUE.equals(t.idempotent) && !"GET".equals(method)) execution.put("idempotent", true);
101
+ if (t.readonly != null) execution.put("readonly", t.readonly);
102
+ if (t.idempotent != null) execution.put("idempotent", t.idempotent);
103
103
  Map<String, Object> rateLimit = normalizeRateLimit(t.rateLimit);
104
104
  if (rateLimit != null) execution.put("rate_limit", rateLimit);
105
105
  if (t.timeoutMs != null) execution.put("timeout_ms", t.timeoutMs);
@@ -285,7 +285,7 @@ public final class BailingConnect {
285
285
  public final String path;
286
286
  public String method = "GET";
287
287
  public String name;
288
- public String risk = "low";
288
+ public String risk;
289
289
  public boolean confirm;
290
290
  public Boolean readonly;
291
291
  public boolean requiresSubject;
@@ -0,0 +1,70 @@
1
+ import com.bailing.connect.BailingConnect;
2
+ import java.util.List;
3
+ import java.util.Map;
4
+ import java.util.Objects;
5
+
6
+ /** No network or business operations: exercises the actual OpenAPI builder. */
7
+ public final class DeclarationTest {
8
+ @SuppressWarnings("unchecked")
9
+ private static Map<String, Object> capability(BailingConnect.Tool tool) {
10
+ Map<String, Object> spec = BailingConnect.buildOpenApiSpec("Fixture", "1", List.of(tool), null);
11
+ Map<String, Object> paths = (Map<String, Object>) spec.get("paths");
12
+ Map<String, Object> path = (Map<String, Object>) paths.get("/fixture");
13
+ Map<String, Object> operation = (Map<String, Object>) path.get(tool.method.toLowerCase());
14
+ return (Map<String, Object>) operation.get("x-agent-capability");
15
+ }
16
+
17
+ private static void check(boolean condition, String message) {
18
+ if (!condition) throw new AssertionError(message);
19
+ }
20
+
21
+ private static BailingConnect.Tool fixture(String method) {
22
+ return new BailingConnect.Tool("Declaration serialization fixture", "fixture.write", "/fixture")
23
+ .method(method).name("serialization_fixture")
24
+ .param(new BailingConnect.Param("fixture"));
25
+ }
26
+
27
+ @SuppressWarnings("unchecked")
28
+ public static void main(String[] args) {
29
+ int matrix = 0;
30
+ int idempotency = 0;
31
+ for (String method : List.of("GET", "POST")) {
32
+ for (Boolean readonly : new Boolean[] { null, false, true }) {
33
+ for (String risk : new String[] { null, "low", "medium", "high" }) {
34
+ BailingConnect.Tool tool = fixture(method);
35
+ if (readonly != null) tool.readonly(readonly);
36
+ if (risk != null) tool.risk(risk);
37
+ Map<String, Object> cap = capability(tool);
38
+ Map<String, Object> execution = (Map<String, Object>) cap.getOrDefault("execution", Map.of());
39
+ String label = method + " readonly=" + readonly + " risk=" + risk;
40
+ check(execution.containsKey("readonly") == (readonly != null), label + " readonly presence");
41
+ if (readonly != null) check(Objects.equals(execution.get("readonly"), readonly), label + " readonly value");
42
+ check(cap.containsKey("risk") == (risk != null), label + " risk presence");
43
+ if (risk != null) check(risk.equals(((Map<?, ?>) cap.get("risk")).get("level")), label + " risk value");
44
+ boolean expectedReadonly = readonly != null ? readonly : "GET".equals(method);
45
+ String expectedRisk = risk != null ? risk : (expectedReadonly ? "low" : "medium");
46
+ boolean effectiveReadonly = (Boolean) execution.getOrDefault("readonly", "GET".equals(method));
47
+ String effectiveRisk = cap.containsKey("risk")
48
+ ? (String) ((Map<?, ?>) cap.get("risk")).get("level") : (effectiveReadonly ? "low" : "medium");
49
+ check(expectedRisk.equals(effectiveRisk), label + " effective risk");
50
+ check(Integer.valueOf(1).equals(cap.get("version")), label + " declaration version");
51
+ String json = BailingConnect.toJson(cap);
52
+ if (readonly != null) check(json.contains("\"readonly\":" + readonly), label + " serialized readonly");
53
+ if (risk != null) check(json.contains("\"level\":\"" + risk + "\""), label + " serialized risk");
54
+ matrix++;
55
+ }
56
+ }
57
+ for (Boolean value : new Boolean[] { null, false, true }) {
58
+ BailingConnect.Tool tool = fixture(method);
59
+ if (value != null) tool.idempotent(value);
60
+ Map<String, Object> cap = capability(tool);
61
+ Map<String, Object> execution = (Map<String, Object>) cap.getOrDefault("execution", Map.of());
62
+ check(execution.containsKey("idempotent") == (value != null), method + " idempotent presence");
63
+ if (value != null) check(Objects.equals(execution.get("idempotent"), value), method + " idempotent value");
64
+ idempotency++;
65
+ }
66
+ }
67
+ check(matrix == 24 && idempotency == 6, "matrix completeness");
68
+ System.out.println("PASS: 24 readonly/risk combinations + 6 idempotent combinations");
69
+ }
70
+ }
@@ -122,3 +122,11 @@ await hub.send({ requestId: `notice_${orderId}`, channel: 'team-im', to: 'user_0
122
122
 
123
123
 
124
124
  示例将准备和发送分开:先调用 `prepareBillingPlan` 并持久化 `grantInput`,再调用 `applyBillingPlan`;回包不确定时沿用已保存的输入,不能重新计算修订。服务端开通示例见 [examples/billing.mjs](examples/billing.mjs)。TypeScript 可通过 `import { UsageIssuerClient, type BillingSummary } from "@bailinghub/connect/usage"` 获取完整的套餐与身份类型。
125
+
126
+ ## 声明字段的省略与显式值
127
+
128
+ 未设置的 `risk`、`readonly`、`idempotent` 不会写入 ACC 声明。显式的 `risk: low/medium/high` 和布尔值 `false/true` 都会保留,包括 GET 上的 `false`。省略风险时,按 ACC OpenAPI binding:显式只读优先于 HTTP 方法;未声明只读的 GET 默认 low,其余非只读操作默认 medium。风险声明不代替审批或业务最终授权。
129
+
130
+ 升级后应重新生成声明并比较差异;不要把以前省略的字段一律补成 low。 `tool().risk` 在未设置时现在为 `undefined`,不再是 `low`;直接读取构建中间对象的调用方需兼容未设置状态。
131
+
132
+ 回归:`node --test sdk/node/tests/declaration.test.mjs`(24种只读/风险组合及6种幂等组合)。
@@ -60,7 +60,7 @@ export function tool(opts) {
60
60
  path: opts.path,
61
61
  method: String(opts.method || 'GET').toUpperCase(),
62
62
  name: opts.name,
63
- risk: opts.risk || 'low',
63
+ risk: opts.risk,
64
64
  confirm: !!opts.confirm,
65
65
  confirmWhen: opts.confirmWhen || [],
66
66
  readonly: opts.readonly,
@@ -100,7 +100,7 @@ function normalizeRateLimit(value) {
100
100
 
101
101
  function buildCapability(t, method) {
102
102
  const capability = { version: 1, enabled: true, scope: t.scope };
103
- if (t.risk && t.risk !== 'low') capability.risk = { level: t.risk };
103
+ if (t.risk != null) capability.risk = { level: t.risk };
104
104
  if (t.confirm || t.confirmWhen?.length || t.confirmPrompt) {
105
105
  capability.approval = {};
106
106
  if (t.confirm) capability.approval.required = true;
@@ -109,8 +109,8 @@ function buildCapability(t, method) {
109
109
  }
110
110
  if (t.requiresSubject) capability.subject = { required: true };
111
111
  const execution = {};
112
- if (t.readonly === true && method !== 'GET') execution.readonly = true;
113
- if (t.idempotent === true && method !== 'GET') execution.idempotent = true;
112
+ if (typeof t.readonly === 'boolean') execution.readonly = t.readonly;
113
+ if (typeof t.idempotent === 'boolean') execution.idempotent = t.idempotent;
114
114
  const rateLimit = normalizeRateLimit(t.rateLimit);
115
115
  if (rateLimit) execution.rate_limit = rateLimit;
116
116
  if (t.timeoutMs !== undefined) execution.timeout_ms = t.timeoutMs;
@@ -0,0 +1,41 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { buildOpenApiSpec, param, tool } from '../src/index.mjs';
4
+
5
+ function capability(method, options) {
6
+ const spec = buildOpenApiSpec({ tools: [tool({
7
+ name: 'serialization_fixture', description: 'Declaration serialization fixture',
8
+ path: '/fixture', scope: 'fixture.write', method,
9
+ params: [param('fixture', { type: 'string' })], ...options,
10
+ })] });
11
+ return JSON.parse(JSON.stringify(spec)).paths['/fixture'][method.toLowerCase()]['x-agent-capability'];
12
+ }
13
+
14
+ for (const method of ['GET', 'POST']) {
15
+ for (const readonly of [undefined, false, true]) {
16
+ for (const risk of [undefined, 'low', 'medium', 'high']) {
17
+ test(`${method}: readonly=${String(readonly)}, risk=${String(risk)}`, () => {
18
+ const options = {};
19
+ if (readonly !== undefined) options.readonly = readonly;
20
+ if (risk !== undefined) options.risk = risk;
21
+ const cap = capability(method, options);
22
+ assert.equal(Object.hasOwn(cap.execution ?? {}, 'readonly'), readonly !== undefined);
23
+ if (readonly !== undefined) assert.equal(cap.execution.readonly, readonly);
24
+ assert.equal(Object.hasOwn(cap, 'risk'), risk !== undefined);
25
+ if (risk !== undefined) assert.equal(cap.risk.level, risk);
26
+ const expectedRisk = risk ?? ((readonly ?? (method === 'GET')) ? 'low' : 'medium');
27
+ const effectiveReadonly = cap.execution?.readonly ?? (method === 'GET');
28
+ const effectiveRisk = cap.risk?.level ?? (effectiveReadonly ? 'low' : 'medium');
29
+ assert.equal(effectiveRisk, expectedRisk);
30
+ assert.equal(cap.version, 1);
31
+ });
32
+ }
33
+ }
34
+ for (const idempotent of [undefined, false, true]) {
35
+ test(`${method}: idempotent=${String(idempotent)}`, () => {
36
+ const cap = capability(method, idempotent === undefined ? {} : { idempotent });
37
+ assert.equal(Object.hasOwn(cap.execution ?? {}, 'idempotent'), idempotent !== undefined);
38
+ if (idempotent !== undefined) assert.equal(cap.execution.idempotent, idempotent);
39
+ });
40
+ }
41
+ }
package/sdk/php/README.md CHANGED
@@ -53,6 +53,22 @@ public function list() { /* 你原有的逻辑 */ }
53
53
  构建期即体检:scope 缺失、写接口无参数、工具名重复等会**直接抛异常**,
54
54
  不会等发布后才在控制台"被跳过"列表里发现。
55
55
 
56
+ ### 显式声明与缺省值
57
+
58
+ `readonly`、`idempotent` 的显式 `true` / `false` 和 `risk` 的显式 `low` / `medium` / `high` 都会原样写入 ACC;未设置的字段保持省略。按 ACC v1 的 OpenAPI binding,只有未显式声明只读性时才使用 GET 的缺省信号。因此 GET + `readonly: false` 且未设置 risk 的有效风险是 `medium`;POST + `risk: 'low'` 的有效风险是 `low`,既有审批与最终业务授权要求仍然保留。
59
+
60
+ 升级后请重新生成、核对并刷新工具源声明。过去被省略的显式值现在会出现,JSON/ETag 可能变化,但 ACC 的 `version: 1` 不变。不需要批量给写接口添加 `risk: 'low'`。
61
+
62
+ PHP 注解模型的 `AiTool::$risk` 现在是 `?string`,默认 `null` 表示未设置;构造参数名称和顺序不变。已有显式字符串声明保持兼容;若接入代码自行读取该属性,应处理 `null`,不要把它解释为统一的 low 风险。
63
+
64
+ 实际生成器回归(24 种 readonly/risk 组合、6 种幂等声明组合及审批/主体保留检查):
65
+
66
+ ```bash
67
+ php tests/declaration-serialization.php
68
+ # 用同一套测试检查另一个解包目录:
69
+ php tests/declaration-serialization.php /path/to/bailing-connect-php
70
+ ```
71
+
56
72
  ## 第二步:发布 spec(约定路径)
57
73
 
58
74
  ```
@@ -38,17 +38,17 @@ final class AiTool
38
38
  public string $method = 'GET',
39
39
  /** 工具名(operationId),缺省 = 蛇形(类名去Controller)_蛇形(方法名),如 StaffController::list → staff_list。建议显式指定;定了就别改:改名会让 AI 认为这是另一个新工具 */
40
40
  public ?string $name = null,
41
- /** 风险级:low(默认,直接放行)/ medium(放行留痕)/ high(先进人工审批) */
42
- public string $risk = 'low',
41
+ /** 显式风险级 low / medium / high;null 表示省略,由 ACC 及 binding 缺省规则推导。 */
42
+ public ?string $risk = null,
43
43
  /** true = 不论风险级一律先人工审批(批准后任务自动重跑执行) */
44
44
  public bool $confirm = false,
45
45
  /** 参数级确认规则,如 [['param' => 'amount', 'op' => '>', 'value' => 500, 'label' => '大额退款需确认']] */
46
46
  public array $confirmWhen = [],
47
- /** 语义只读声明:GET 默认只读;POST 实现的查询接口务必标 true,AI 才敢放心调用 */
47
+ /** 显式只读声明,true/false 均保留;null 表示省略,由 binding 解释 GET 等缺省信号。 */
48
48
  public ?bool $readonly = null,
49
49
  /** true = 必须有操作主体(X-Bailing-On-Behalf-Of)才有意义;匿名任务(网页访客)直接看不到该工具 */
50
50
  public bool $requiresSubject = false,
51
- /** 可安全重试(GET 默认 true);网络抖动时大脑可凭此决定是否自动重发 */
51
+ /** 显式幂等提示,true/false 均保留;null 表示省略,不替运行时决定重试。 */
52
52
  public ?bool $idempotent = null,
53
53
  /** true = 参数含敏感数据(手机号/身份证等):中枢审计只记参数键名不记值 */
54
54
  public bool $sensitive = false,
@@ -101,7 +101,7 @@ final class SpecBuilder
101
101
  if (trim($t->scope) === '') {
102
102
  throw new InvalidArgumentException("{$where}: scope 不能为空(中枢会直接跳过该接口)");
103
103
  }
104
- if (!in_array($t->risk, ['low', 'medium', 'high'], true)) {
104
+ if ($t->risk !== null && !in_array($t->risk, ['low', 'medium', 'high'], true)) {
105
105
  throw new InvalidArgumentException("{$where}: risk 仅支持 low/medium/high,收到 {$t->risk}");
106
106
  }
107
107
  if ($t->rateLimit !== null && self::parseRateLimit($t->rateLimit) === null) {
@@ -194,10 +194,10 @@ final class SpecBuilder
194
194
  }
195
195
 
196
196
  /** @return array<string,mixed> */
197
- private function buildCapability(AiTool $t, string $method): array
197
+ private function buildCapability(AiTool $t): array
198
198
  {
199
199
  $capability = ['version' => 1, 'enabled' => true, 'scope' => $t->scope];
200
- if ($t->risk !== 'low') {
200
+ if ($t->risk !== null) {
201
201
  $capability['risk'] = ['level' => $t->risk];
202
202
  }
203
203
  if ($t->confirm || $t->confirmWhen || $t->confirmPrompt !== null) {
@@ -217,11 +217,11 @@ final class SpecBuilder
217
217
  $capability['subject'] = ['required' => true];
218
218
  }
219
219
  $execution = [];
220
- if (($t->readonly ?? ($method === 'GET')) && $method !== 'GET') {
221
- $execution['readonly'] = true;
220
+ if ($t->readonly !== null) {
221
+ $execution['readonly'] = $t->readonly;
222
222
  }
223
- if (($t->idempotent ?? ($method === 'GET')) && $method !== 'GET') {
224
- $execution['idempotent'] = true;
223
+ if ($t->idempotent !== null) {
224
+ $execution['idempotent'] = $t->idempotent;
225
225
  }
226
226
  $rateLimit = self::parseRateLimit($t->rateLimit);
227
227
  if ($rateLimit !== null) {
@@ -261,7 +261,7 @@ final class SpecBuilder
261
261
  $op = [
262
262
  'operationId' => $name,
263
263
  'summary' => $t->description,
264
- 'x-agent-capability' => $this->buildCapability($t, $method),
264
+ 'x-agent-capability' => $this->buildCapability($t),
265
265
  ];
266
266
  // 非核心 OpenAPI 字段才继续落到 operation 顶层;治理字段统一放入 ACC。
267
267
  if ($t->tags) {
@@ -0,0 +1,103 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ // An optional SDK root verifies the same cases against an extracted distribution.
6
+ $sdkRoot = isset($argv[1]) ? rtrim($argv[1], '/\\') : dirname(__DIR__);
7
+ require_once $sdkRoot . '/src/Attributes/AiTool.php';
8
+ require_once $sdkRoot . '/src/Attributes/AiParam.php';
9
+ require_once $sdkRoot . '/src/SpecBuilder.php';
10
+
11
+ use Bailing\Connect\SpecBuilder;
12
+
13
+ $checks = 0;
14
+ $errors = [];
15
+ $matrix = [];
16
+ $idempotence = [];
17
+
18
+ function serializationCheck(bool $condition, string $label): void
19
+ {
20
+ global $checks, $errors;
21
+ $checks++;
22
+ if (!$condition) $errors[] = $label;
23
+ }
24
+
25
+ function generatedCapability(string $method, ?bool $readonly, ?string $risk, ?bool $idempotent = null, bool $governance = false): array
26
+ {
27
+ static $case = 0;
28
+ $class = 'SyntheticDeclarationCase' . ++$case;
29
+ $arguments = [
30
+ 'description' => 'Synthetic declaration regression case',
31
+ 'scope' => 'example.record.read', 'path' => '/serialization-case',
32
+ 'method' => $method, 'name' => 'serialization_case',
33
+ ];
34
+ if ($readonly !== null) $arguments['readonly'] = $readonly;
35
+ if ($risk !== null) $arguments['risk'] = $risk;
36
+ if ($idempotent !== null) $arguments['idempotent'] = $idempotent;
37
+ if ($governance) {
38
+ $arguments['requiresSubject'] = true;
39
+ $arguments['confirm'] = true;
40
+ $arguments['confirmPrompt'] = 'Approve {record_id}';
41
+ $arguments['confirmWhen'] = [['param' => 'record_id', 'op' => '>', 'value' => 100]];
42
+ }
43
+ $attributeArguments = [];
44
+ foreach ($arguments as $key => $value) $attributeArguments[] = $key . ': ' . var_export($value, true);
45
+ // Only fixed synthetic values are evaluated. SpecBuilder must discover and
46
+ // instantiate the real attributes through ReflectionClass/ReflectionMethod.
47
+ eval('class ' . $class . ' {' .
48
+ '#[\\Bailing\\Connect\\Attributes\\AiTool(' . implode(', ', $attributeArguments) . ')]' .
49
+ '#[\\Bailing\\Connect\\Attributes\\AiParam("record_id", type: "integer", required: true)]' .
50
+ 'public function execute(): void {} }');
51
+ $spec = json_decode((new SpecBuilder('Synthetic declaration regression'))->addClass($class)->buildJson(false), true, 512, JSON_THROW_ON_ERROR);
52
+ return $spec['paths']['/serialization-case'][strtolower($method)]['x-agent-capability'];
53
+ }
54
+
55
+ foreach (['GET', 'POST'] as $method) {
56
+ foreach ([null, false, true] as $readonly) {
57
+ foreach ([null, 'low', 'medium', 'high'] as $risk) {
58
+ $capability = generatedCapability($method, $readonly, $risk);
59
+ $execution = $capability['execution'] ?? [];
60
+ $label = $method . '/readonly=' . json_encode($readonly) . '/risk=' . json_encode($risk);
61
+ serializationCheck($capability['version'] === 1 && $capability['enabled'] === true && $capability['scope'] === 'example.record.read', $label . ': declaration identity');
62
+ serializationCheck(array_key_exists('risk', $capability) === ($risk !== null), $label . ': risk presence');
63
+ if ($risk !== null) serializationCheck(($capability['risk']['level'] ?? null) === $risk, $label . ': risk value');
64
+ serializationCheck(array_key_exists('readonly', $execution) === ($readonly !== null), $label . ': readonly presence');
65
+ if ($readonly !== null) serializationCheck(array_key_exists('readonly', $execution) && $execution['readonly'] === $readonly, $label . ': readonly value');
66
+ serializationCheck(!array_key_exists('idempotent', $execution), $label . ': unset idempotent remains omitted');
67
+
68
+ // ACC v1 + OpenAPI binding: explicit values win; GET is only a fallback.
69
+ $expectedReadonly = $readonly === null ? $method === 'GET' : $readonly;
70
+ $expectedRisk = $risk ?? ($expectedReadonly ? 'low' : 'medium');
71
+ $wireReadonly = array_key_exists('readonly', $execution) ? $execution['readonly'] : $method === 'GET';
72
+ $effectiveRisk = $capability['risk']['level'] ?? ($wireReadonly ? 'low' : 'medium');
73
+ serializationCheck($effectiveRisk === $expectedRisk, $label . ': effective risk');
74
+ $matrix[] = ['method' => $method, 'readonly' => $readonly, 'risk' => $risk, 'capability' => $capability, 'expectedRisk' => $expectedRisk, 'effectiveRisk' => $effectiveRisk];
75
+ }
76
+ }
77
+ foreach ([null, false, true] as $idempotent) {
78
+ $capability = generatedCapability($method, null, null, $idempotent);
79
+ $execution = $capability['execution'] ?? [];
80
+ $label = $method . '/idempotent=' . json_encode($idempotent);
81
+ serializationCheck(array_key_exists('idempotent', $execution) === ($idempotent !== null), $label . ': presence');
82
+ if ($idempotent !== null) serializationCheck(array_key_exists('idempotent', $execution) && $execution['idempotent'] === $idempotent, $label . ': value');
83
+ serializationCheck(!array_key_exists('risk', $capability) && !array_key_exists('readonly', $execution), $label . ': unrelated unset fields remain omitted');
84
+ $idempotence[] = ['method' => $method, 'idempotent' => $idempotent, 'capability' => $capability];
85
+ }
86
+ }
87
+
88
+ $governance = generatedCapability('POST', false, 'low', false, true);
89
+ serializationCheck($governance === [
90
+ 'version' => 1, 'enabled' => true, 'scope' => 'example.record.read',
91
+ 'risk' => ['level' => 'low'],
92
+ 'approval' => ['required' => true, 'when' => [['param' => 'record_id', 'op' => '>', 'value' => 100]], 'prompt' => 'Approve {record_id}'],
93
+ 'subject' => ['required' => true],
94
+ 'execution' => ['readonly' => false, 'idempotent' => false],
95
+ ], 'explicit low and false do not remove approval or subject requirements');
96
+
97
+ echo json_encode([
98
+ 'sdk' => 'php', 'phpVersion' => PHP_VERSION,
99
+ 'matrixCases' => count($matrix), 'idempotenceCases' => count($idempotence),
100
+ 'checks' => $checks, 'passed' => !$errors, 'errors' => $errors,
101
+ 'matrix' => $matrix, 'idempotence' => $idempotence,
102
+ ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n";
103
+ exit($errors ? 1 : 0);
@@ -67,6 +67,20 @@ $spec = ToolSpec::create('示例业务系统') // 标题随便填
67
67
 
68
68
  构建期即体检:scope 缺失、写接口无参数、工具名/路由重复、risk 非法等会**直接抛 `InvalidArgumentException`**,CI 跑构建即完成体检,不会等发布后才在控制台"被跳过"列表里发现。
69
69
 
70
+ ### 显式声明与缺省值
71
+
72
+ `readonly(false)` / `readonly(true)`、`idempotent(false)` / `idempotent(true)` 和显式 `risk('low'|'medium'|'high')` 都会原样写入 ACC。未调用相应方法时保持省略,由 ACC v1 及 OpenAPI binding 的缺省规则推导:GET + `readonly(false)` 且未设置 risk 为 `medium`;非只读 POST 显式 `risk('low')` 仍为 `low`。风险值不取消既有审批与最终业务授权要求。
73
+
74
+ 升级后请重新生成、核对并刷新工具源声明。过去被省略的显式值现在会出现,JSON/ETag 可能变化,方法签名与 ACC 的 `version: 1` 不变。不需要批量给写接口添加 `risk('low')`。
75
+
76
+ 实际生成器回归兼容 PHP 7.3,覆盖 24 种 readonly/risk 组合、6 种幂等声明组合及审批/主体保留检查:
77
+
78
+ ```bash
79
+ php tests/declaration-serialization.php
80
+ # 用同一套测试检查另一个解包目录:
81
+ php tests/declaration-serialization.php /path/to/bailing-connect-php7
82
+ ```
83
+
70
84
  ## 第二步:发布 spec
71
85
 
72
86
  把 `buildJson()` 的产物挂到中枢「工具源」登记的 `spec_url`。裸 PHP 单文件: