@reopt-ai/brandapp-sdk 4.7.0-rc.1 → 4.7.0-rc.10

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 (92) hide show
  1. package/CHANGELOG.md +226 -0
  2. package/README.md +181 -59
  3. package/dist/ai/index.d.ts +52 -2
  4. package/dist/ai/index.js +32 -2
  5. package/dist/ai-provider/index.d.ts +57 -5
  6. package/dist/ai-provider/index.js +456 -119
  7. package/dist/analytics/index.d.ts +1 -1
  8. package/dist/analytics/index.js +1 -1
  9. package/dist/auth/index.d.ts +1 -1
  10. package/dist/auth/index.js +1 -1
  11. package/dist/better-auth/client.d.ts +7 -2
  12. package/dist/better-auth/client.js +5 -4
  13. package/dist/better-auth/index.d.ts +32 -6
  14. package/dist/better-auth/index.js +30 -9
  15. package/dist/{client-VKEJtLH0.js → client-B281w6RL.js} +2 -2
  16. package/dist/{client-Cod87ThY.d.ts → client-BL-Ljwki.d.ts} +2 -2
  17. package/dist/{client-C-LdW4gY.js → client-BPcoDnOd.js} +3 -3
  18. package/dist/{client-CsWSxMhB.d.ts → client-BbmslwWV.d.ts} +2 -2
  19. package/dist/{client-CLZie3Ym.js → client-Brv0KsDM.js} +2 -2
  20. package/dist/{client-CslasnqK.js → client-BxrWT0mi.js} +2 -2
  21. package/dist/client-C7z5-izC.js +745 -0
  22. package/dist/{client-BQJepjoD.d.ts → client-CD6uK0dA.d.ts} +47 -6
  23. package/dist/{client-BFl6cDAE.js → client-CGy4Z0JO.js} +46 -2
  24. package/dist/{client-C6lx3RUQ.d.ts → client-CJFsLk3_.d.ts} +2 -2
  25. package/dist/{client-C2W4RAZV.d.ts → client-CJRjPSf7.d.ts} +2 -2
  26. package/dist/{client-Cnq_X3Wp.d.ts → client-CP1Jgq4R.d.ts} +139 -13
  27. package/dist/{client-DGKq4Ml5.js → client-CmV48bW0.js} +3 -3
  28. package/dist/{client-BJQzInqD.js → client-D8d3xsYm.js} +51 -12
  29. package/dist/{client-BZ8-vFjk.js → client-D97Ylva1.js} +40 -6
  30. package/dist/{client-MDNS9Ubf.d.ts → client-DF-tOyrY.d.ts} +2 -2
  31. package/dist/client-DlgVNj3w.d.ts +72 -0
  32. package/dist/{client-Db6Etco9.js → client-Dv7WwJr-.js} +2 -2
  33. package/dist/{client-CSl3o0s3.d.ts → client-Dwf6UuGH.d.ts} +2 -2
  34. package/dist/{client-DfnaH99z.d.ts → client-NUhpPkl2.d.ts} +2 -2
  35. package/dist/{client-Bf8mW6uO.js → client-ey80gKM_.js} +11 -5
  36. package/dist/{client-_2Avom0q.js → client-m4e-HwMX.js} +2 -2
  37. package/dist/client-seu-0lbh.d.ts +654 -0
  38. package/dist/{client-xblzWFAL.d.ts → client-wNzcgEJu.d.ts} +2 -2
  39. package/dist/cms/index.d.ts +1 -1
  40. package/dist/cms/index.js +1 -1
  41. package/dist/{config-CnFnzh7Q.d.ts → config-BGT9h1OW.d.ts} +7 -5
  42. package/dist/{config-Dy2oBn1a.js → config-DaSeKofC.js} +59 -8
  43. package/dist/dev/index.js +71 -3
  44. package/dist/eav/index.d.ts +3 -3
  45. package/dist/eav/index.js +2 -2
  46. package/dist/eav/migrate.d.ts +2 -2
  47. package/dist/eav/schema.d.ts +2 -2
  48. package/dist/{errors-U3TsyWVq.d.ts → errors-D-Va8oeC.d.ts} +5 -2
  49. package/dist/feedback/index.d.ts +1 -1
  50. package/dist/feedback/index.js +1 -1
  51. package/dist/files/index.d.ts +1 -1
  52. package/dist/files/index.js +1 -1
  53. package/dist/{http-client-CW9wXANY.js → http-client-BCZhLtY5.js} +29 -6
  54. package/dist/{index-Bkci7euU.d.ts → index-CaXrNTtU.d.ts} +42 -15
  55. package/dist/index.d.ts +6 -6
  56. package/dist/index.js +12 -12
  57. package/dist/installation/index.d.ts +415 -0
  58. package/dist/installation/index.js +841 -0
  59. package/dist/logout/index.d.ts +1 -1
  60. package/dist/logout/index.js +1 -1
  61. package/dist/machine/index.d.ts +2 -71
  62. package/dist/machine/index.js +1 -1
  63. package/dist/plans/index.d.ts +1 -1
  64. package/dist/plans/index.js +1 -1
  65. package/dist/push/index.d.ts +1 -1
  66. package/dist/push/index.js +1 -1
  67. package/dist/{query-DPD0WYlB.js → query-B8Hg9bub.js} +2 -2
  68. package/dist/react/hooks.d.ts +5 -5
  69. package/dist/resource/index.d.ts +176 -0
  70. package/dist/resource/index.js +345 -0
  71. package/dist/social/index.d.ts +284 -0
  72. package/dist/social/index.js +306 -0
  73. package/dist/{sse-parser-FMjxM7sY.js → sse-parser-D65dmL4A.js} +15 -18
  74. package/dist/superadmin/index.d.ts +80 -0
  75. package/dist/superadmin/index.js +148 -0
  76. package/dist/terms/index.d.ts +1 -1
  77. package/dist/terms/index.js +1 -1
  78. package/dist/testing/index.d.ts +1 -1
  79. package/dist/types-DGAVaUCc.js +17 -0
  80. package/dist/{types-MXLudLBP.d.ts → types-FazBnzhg.d.ts} +8 -2
  81. package/dist/workspace/index.d.ts +2 -654
  82. package/dist/workspace/index.js +2 -735
  83. package/docs/api-reference.md +191 -12
  84. package/docs/environment.md +30 -15
  85. package/docs/errors.md +54 -0
  86. package/docs/installation.md +128 -0
  87. package/docs/machine.md +5 -0
  88. package/docs/resource.md +75 -0
  89. package/docs/social.md +92 -0
  90. package/docs/superadmin.md +55 -0
  91. package/package.json +20 -4
  92. package/dist/types-DjDRszNj.js +0 -11
package/CHANGELOG.md CHANGED
@@ -7,6 +7,232 @@ This project adheres to [Semantic Versioning](https://semver.org/).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [4.7.0-rc.10] — 2026-11-02
11
+
12
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — 스트리밍 줄바꿈 결함 수정. rc.9에서 `sdk.ai.stream`으로 받은
13
+ YAML·Markdown 펜스가 한 줄로 붙었다면 이 버전으로 올린다.
14
+
15
+ ### Fixed
16
+
17
+ - SSE 파서가 줄바꿈만 있는 `text-delta`를 버리고, 줄바꿈으로 시작하는 델타의 앞머리 줄바꿈을 잃던 것.
18
+ 서버는 규격대로 `"\n"`을 `data: \ndata: \n\n`으로 보내는데 파서가 빈 `data:` 값을 "데이터 없음"으로
19
+ 읽었다 — 줄바꿈이 문법인 YAML·Markdown 펜스가 한 줄로 붙었다(`sdk.ai.stream`·`streamWithMetadata`·
20
+ `/ai-provider` 공통). `data:` 줄을 봤는지를 값과 따로 기억한다.
21
+ - dev 서버 `/ai/evaluations`의 choice 답이 고른 선택지 하나만 담은 분포(`{ [choice]: 1 }`)를 내 AI SDK
22
+ `experimental_decide`가 "complete distribution"으로 거절하던 것 — 이제 선택지 전부를 덮는다(고른 것 1, 나머지 0).
23
+ `sdk.ai.evaluate`·json-render 평가자는 영향이 없었다.
24
+
25
+ ### Docs
26
+
27
+ - AI SDK 결정 함수 이름을 `experimental_decide`로 고쳤다 — `experimental_evaluate`는 AI SDK가 deprecated로 남긴
28
+ 옛 이름인데 주석이 거꾸로 적고 있었다. 과금 호출이라 `maxRetries: 0`을 권한다.
29
+
30
+ ## [4.7.0-rc.9] — 2026-10-30
31
+
32
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — 평가(Jev)·json-render 조립(RFC-0041). 서버 평가 중계는
33
+ 플랫폼이 열기 전까지 503 `EVALUATIONS_UNAVAILABLE`이다 — 그동안은 dev 서버로 개발한다.
34
+
35
+ ### Added
36
+
37
+ - `sdk.ai.evaluate()` — 평가 모델(Jev)에 상태와 질문(choice·score·boolean, 최대 128개)을 보내 답과 확률을 받는다
38
+ (`POST /ai/evaluations`, RFC-0041). 브랜드앱 AI 설정 "평가 허용"이 켜져 있어야 하고, 답을 못 준 호출은
39
+ 과금되지 않으며, 과금 호출이라 재시도하지 않는다.
40
+ - `createBrandappEvaluator(sdk)` — json-render `experimental_composeSpec`의 `evaluate`에 그대로 꽂는 평가자.
41
+ json-render를 의존성으로 들이지 않는다(구조 호환, 테스트가 실제 `composeSpec`으로 확인).
42
+ `onEvaluation` 콜백으로 평가마다의 실제 크레딧(`creditCostMilli`)을 받는다.
43
+ - `brandapp.decisionModel()`(`/ai-provider`) — AI SDK `experimental_evaluate`용 결정 모델(`Experimental_DecisionModelV4`).
44
+ `evaluationModel()`은 옛 이름. 크레딧은 `providerMetadata.brandapp`. 중계하지 않는 모델 id는 `NoSuchModelError`.
45
+ - dev 서버 `/ai/evaluations` — 결정적인 흉내(실서버와 같은 상한)로 json-render 조립이 오프라인에서 끝까지 돈다.
46
+ - 평가 오류 코드 7종의 `diagnostic`(원인·해결·과금 여부)과 `docs/errors.md` 표. 평가 타입을 루트에서도 export한다.
47
+
48
+ ### Fixed
49
+
50
+ - AI provider가 503 `EVALUATIONS_UNAVAILABLE`을 재시도 가능으로 표시하던 것 — 다시 보내도 같은 답이라 AI SDK의 자동
51
+ 재시도가 헛돈다.
52
+
53
+ ### Docs
54
+
55
+ - `/ai-provider` 진입점 주석이 도구 호출·구조화 출력을 "미지원"으로 적고 있었다(실제로는 4.7부터 지원) —
56
+ 지원 범위를 구현과 맞추고, 예시를 기계 자격(`authorization: machine.headers`) 기준으로 바꿨다.
57
+ - `docs/api-reference.md`에 json-render(Standalone·Inline) 연결 예시를 더했다.
58
+
59
+ ## [4.7.0-rc.8] — 2026-10-29
60
+
61
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — 도구 루프 정산·경고·끊김 처리.
62
+
63
+ ### Added
64
+
65
+ - `usage.creditCostMilli`·`providerMetadata.brandapp.creditCostMilli` — 실제 사용량(1/1000 크레딧).
66
+ `creditCost`는 올림한 정수 표시값이라 1크레딧 미만 단계도 1로 보인다. 도구 루프처럼 한 턴에 여러 단계를
67
+ 부르는 앱은 milli를 더한 뒤 한 번만 올림한다. 옛 서버 응답에는 없으므로 선택 필드다.
68
+ - 서버·모델 경고가 AI SDK의 `warnings`로 온다 — 모델이 무시한 설정, 도구 강제로 꺼진 thinking 등. 비스트리밍은
69
+ 응답 `warnings`, 스트리밍은 첫 `warnings` SSE 이벤트(SDK가 `stream-start`에 합친다). `sdk.ai` 타입에
70
+ `CompletionWarning`을 더했다.
71
+ - 403 `CLIENT_TOOLS_DISABLED`·`CLIENT_TOOLS_PLAN_REQUIRED`의 `diagnostic`이 고칠 자리(AI 설정의 도구 호출
72
+ 허용 · Business 플랜)를 가리킨다.
73
+
74
+ ### Changed
75
+
76
+ - 비스트리밍(`generateText`)의 기본 한도를 응답 전체 300초로 늘렸다 — 예전에는 스트리밍 유휴 한도와 같은
77
+ 60초가 응답 본문까지 덮어 추론·긴 JSON 응답이 끊겼다. 스트리밍은 그대로 청크 사이 60초다. `timeout`을
78
+ 지정하면 둘 다 그 값이다.
79
+ - 서버: 호출 앱이 연결을 끊으면(`abortSignal`, 탭 닫기) 모델 호출도 멈춘다 — 예전에는 끝까지 생성하고 전액
80
+ 과금했다. 끊긴 단계는 읽은 입력 + 이미 보낸 출력으로 과금한다.
81
+ - 서버: `maxTokens`(AI SDK `maxOutputTokens`)를 주지 않으면 4096이 아니라 앱 AI 설정의 최대 출력 토큰
82
+ (기본 8192)까지 쓴다 — 추론 모델과 큰 JSON 응답이 잘렸다.
83
+ - 서버: `-thinking` Anthropic 모델에 사고 요약(`display: "summarized"`)을 요청한다 — Claude 5 계열 기본값
84
+ (`omitted`)에서는 추론 파트가 텍스트 없이 서명만 왔다.
85
+
86
+ ## [4.7.0-rc.7] — 2026-10-28
87
+
88
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — AI SDK provider의 도구 호출·구조화 출력·추론 파트 왕복.
89
+
90
+ ### Added
91
+
92
+ - `createBrandappProvider` — **도구 호출·구조화 출력·추론 파트 왕복**. `tools`·`toolChoice`(auto·none·required·
93
+ 특정 도구), `responseFormat: json`을 더 이상 `UnsupportedFunctionalityError`로 거절하지 않는다. 도구는 앱이
94
+ 실행하고 서버는 호출만 돌려준다 — `ToolLoopAgent`·`streamText` + `stopWhen` 루프가 그대로 동작하고, 단계마다
95
+ `providerMetadata.brandapp.creditCost`가 실린다. 스트림은 `reasoning-start/delta/end`·`tool-input-start/delta/end`·
96
+ `tool-call`(한 단계에 여럿 가능) 파트를 내고, 추론 파트의 `providerMetadata`(Anthropic 서명 등)를 다음 요청으로
97
+ 되돌린다. 도구 결과는 `execution-denied`·`content`(텍스트)까지 손실 없이 옮긴다(예전에는 텍스트로 뭉갰다).
98
+ `usage`에 캐시 읽기·쓰기·추론 토큰이 채워진다. 추론 강도는 `providerOptions.brandapp.reasoningEffort`
99
+ (또는 `anthropic.effort`·`openai.reasoningEffort`). 그 밖의 요청 단위 `providerOptions`는 무시한다.
100
+ **서버 쪽 전제**: 브랜드앱 AI 설정의 "도구 호출·구조화 출력 허용" + Business 플랜 — 아니면
101
+ `403 CLIENT_TOOLS_DISABLED` / `CLIENT_TOOLS_PLAN_REQUIRED`.
102
+ - `/ai` 타입 — `CompletionResult.content`(응답 파트), `CompletionUsage`(캐시·추론 토큰), `CompletionContentPart`,
103
+ `PartProviderMetadata`.
104
+
105
+ ### Changed
106
+
107
+ - provider 실행 도구(`type: "provider"`)는 요청 전에 `UnsupportedFunctionalityError`로 거절한다. 비전·파일 입력은
108
+ 여전히 거절한다.
109
+
110
+ - `@reopt-ai/brandapp-sdk/social` — 소셜 운영 플랫폼 API(RFC-0037 §7) 클라이언트 `createSocialClient`(scope
111
+ `social:read`·`social:write`): `accounts.list`, `contents.list/convert`, `posts.list/get/transition/propose`,
112
+ `reviews.run`. 모든 채널은 직접 게시라 플랫폼에 올리는 호출은 없고, 승인·게시 기록·취소는 승인함 **제안**이다.
113
+ - `/social` 계정 `profile.reviewChecklist`(RFC-0038) — 계정별 검수 기준 항목 `{text, severity}`. 응답·저장 스키마 둘 다 선택 칸.
114
+ `/workspace`와 요청기를 공유한다(`createPlatformRequester`). 문서 `docs/social.md`.
115
+ - `/social` — 글(`SocialPost`)에 `links`(변환이 본문 URL을 바꿔 넣은 추적 링크: `originalUrl`·`shortUrl`·`clicks`).
116
+ `clicks`는 리옵트 링크 원장의 누적 클릭이지 플랫폼 반응이 아니다.
117
+
118
+ ### Fixed
119
+
120
+ - 기계 자격(`authorization: machine.headers`, RFC-0034)이 **손으로 짠 요청 경로**에도 실린다 —
121
+ `ai.stream()`·`ai.streamWithMetadata()`(SSE), `files.upload()`, `files.readContent()`,
122
+ `createBrandappProvider`(언어·이미지 모델). 지금까지 이 경로들은 정적 `Basic base64("<clientId>:")`를
123
+ 보내 `401 Missing clientId or clientSecret`로 실패했다(`http.fetch`를 타는 `models`·`complete` 등은 정상).
124
+ DPoP 증명은 요청마다, 스트림 연결 재시도마다 새로 받는다. `createBrandappProvider`가 `authorization`을 받는다.
125
+ 손으로 요청을 짜는 코드는 `http.authorizationHeader` 대신 `http.requestAuthHeaders({ method, url })`를 쓴다.
126
+
127
+ - 서버 — `changePlan`으로 바꾼 플랜의 `paymentEnvironment`가 `null`로 오던 것. 바뀐 플랜에는 자기 체크아웃이 없어
128
+ "모름"이 됐고, 그 값으로 실 결제·테스트 결제만 인정하는 앱은 올린 고객의 이용권을 거뒀다. 이제 그 구독을 시작한
129
+ 체크아웃의 환경을 말한다(SDK 코드 변경 없음, 문서만).
130
+
131
+ ## [4.7.0-rc.6] — 2026-10-15
132
+
133
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — 해지 예약 구독 재개(`plans.resume`)와 해지 기간 중 새 결제 차단.
134
+
135
+ ### Added
136
+
137
+ - `plans.resume(accessToken)` — 결제한 기간이 남은 해지 예약 구독을 되살린다(`POST /me/subscription/resume`, Lemon
138
+ Squeezy). 같은 구독이 갱신일 그대로 이어지고 바뀐 플랜(`getMyPlan`과 같은 모양)을 돌려준다. 거절은
139
+ `NO_RESUMABLE_SUBSCRIPTION`(409), 결제사 실패는 `PROVIDER_ERROR`(502, 재시도).
140
+
141
+ ### Changed
142
+
143
+ - `plans.createCheckout` — 해지 예약 구독이 결제한 기간을 남기고 있으면 `SUBSCRIPTION_CANCEL_PENDING`(409)으로
144
+ 거절한다. 새 구독을 열면 옛 구독과 겹친 기간을 두 번 내기 때문이다 — `resume` 뒤 다른 플랜이면 `changePlan`.
145
+
146
+ ## [4.7.0-rc.5] — 2026-10-14
147
+
148
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — 구독 중 플랜 변경(`plans.changePlan`)과 Lemon Squeezy 해지 계약, 5xx 오류 코드 보존.
149
+
150
+ ### Added
151
+
152
+ - `plans.changePlan(planId, accessToken)` — 구독 중인 플랜을 바꾼다(`POST /me/subscription/change`).
153
+ 새 체크아웃 없이 결제사 구독의 가격을 그 자리에서 바꾸므로 구독은 하나이고 갱신일이 이어진다.
154
+ 즉시 적용되고 바뀐 플랜(`getMyPlan`과 같은 모양)을 돌려준다. 올리면 차액을 지금 청구하고 내리면
155
+ 다음 청구서에서 차감한다. Lemon Squeezy 구독만 지원한다.
156
+
157
+ ### Changed
158
+
159
+ - 5xx 오류가 서버가 준 코드와 실제 상태를 담는다 — 상류(결제사) 실패는 `ServerError`이면서 `code`가
160
+ `PROVIDER_ERROR`·`PROVIDER_CANCEL_FAILED`, `status`가 502다. 코드 없는 5xx는 예전처럼 `SERVER_ERROR`이고
161
+ `status`는 실제 응답 상태다(전에는 항상 500).
162
+ - `plans.cancel` — Lemon Squeezy 구독은 결제사 해지가 먼저다. 결제사 해지가 실패하면 아무것도 바뀌지
163
+ 않고 `PROVIDER_CANCEL_FAILED`(HTTP 502)로 실패한다 — 다시 시도하면 된다. 성공하면 `accessUntil`이
164
+ 결제사의 결제 기간 끝이다.
165
+
166
+ ## [4.7.0-rc.4] — 2026-10-14
167
+
168
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — EAV `listAll()` 커서 훑기와 설치 back-channel 재생 거절 보강.
169
+
170
+ ### Changed
171
+
172
+ - **`eav.records.listAll()`이 커서로 훑는다.** 번호 페이지로 훑으면 필터가 있을 때 서버가 페이지마다 조건에 맞는 행
173
+ 전체를 다시 읽어 그 페이지만 잘랐다 — 훑는 비용이 행 수의 제곱이었다. 이제 `GET …/records?cursor=`로 앞 페이지의
174
+ 마지막 자리 다음부터 그 페이지 분량만 읽는다. 호출부는 바꿀 것이 없다(`backfill()`·typed `entity().listAll()` 포함).
175
+ - 정렬이 `createdAt`(기본)·`updatedAt`일 때만 커서를 쓴다. 커스텀 속성 정렬은 종전대로 번호 페이지다.
176
+ - 커서를 모르는 서버(이전 버전의 reopt, 로컬 dev 서버)는 `cursor`를 무시하고 1페이지를 주므로, 그때는 2페이지부터
177
+ 번호로 이어 간다 — 결과는 같다.
178
+ - 같은 정렬 키를 가진 행들의 순서는 커서 방식에서 id가 정한다(번호 페이지는 createdAt → id). `updatedAt` 정렬로
179
+ 훑는 도중 갱신된 행은 자리를 옮기므로, 전 행을 정확히 한 번씩 읽어야 하면 기본값인 `createdAt`을 쓴다.
180
+ - SQL로 좁혀지지 않는 필터(`neq`·`not_in`·`after`·`before`)로 큰 엔티티를 훑어도 `QUERY_TOO_BROAD`(422)가 나지
181
+ 않는다 — 서버가 요청 한 건이 읽는 행 수를 묶고 커서로 이어 준다.
182
+ - 새 에러 코드 `CURSOR_SCAN_INTERRUPTED`(훑는 도중 커서를 모르는 인스턴스가 응답 — 처음부터 다시),
183
+ `CURSOR_SCAN_STALLED`(서버가 커서를 전진시키지 않음).
184
+
185
+ ### Fixed
186
+
187
+ - **`createInstallationBackchannelHandler`의 재생 거절에 빈틈이 있었다.** 통지의 jti를 `exp`까지만 기억했는데 검증은
188
+ `clockToleranceSeconds`(기본 60초)만큼 더 받아 주므로, `exp` 직후 그 시간 동안은 같은 통지가 다시 통과했다. 이제
189
+ 받아 줄 수 있는 마지막 순간(`exp + clockTolerance`)까지 기억한다.
190
+ - `createMemoryBackchannelReplayStore(now?)` — 시계를 받는다. 핸들러의 `now` 옵션이 기본 메모리 저장소에도 적용돼
191
+ 만료 판정과 기억을 지우는 시점이 같은 시계를 본다(예전에는 저장소만 실제 시계를 봤다).
192
+
193
+ ## [4.7.0-rc.3] — 2026-10-11
194
+
195
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — RFC-0034 2·3단계: 리소스 서버 검증기와 운영자 가드.
196
+
197
+ ### Added
198
+
199
+ - **`@reopt-ai/brandapp-sdk/resource`** (RFC-0034 §4.3) — 서브 제품 API가 리옵트 id의 기계 토큰(`at+jwt` + DPoP)을 받는
200
+ 검증기 **한 벌**. `createResourceVerifier({ issuer, audience, jwks?, dpop: { required, replayStore }, allowUserTokens?, publicUrl? })`
201
+ → `verify(request, { scope })`는 `MachinePrincipal`을 주거나 `ResourceAuthError`(`code` 12종, `status` 401|403,
202
+ `wwwAuthenticate()`)를 던진다. `verify.safe()`·`verify.looksLikeAccessToken()`. 저수준 `verifyMachineToken(input)`(결과 유니언),
203
+ `createRedisDpopReplayStore(redis, { keyPrefix, onFallback })`(`SET NX PX`, fail-closed)·`createMemoryDpopReplayStore()`,
204
+ `resolvePublicRequestUrl()`(proxy 뒤 `x-forwarded-*` → DPoP `htu`). 리옵트 본체의 플랫폼·브랜드앱 미들웨어도 같은 구현을 쓴다.
205
+ - **`@reopt-ai/brandapp-sdk/superadmin`** (RFC-0034 §5.2) — 운영자 가드. 리옵트가 id token·userinfo·access token에
206
+ `reopt_operator`·`reopt_mfa`·`auth_time`을 싣고, `evaluateOperator(claims, { maxAuthAgeSeconds })`/`requireOperator()`가
207
+ ① claim ② 운영자 ③ 2단계 인증 **수행** ④ 로그인 나이 순으로 판정한다(`OperatorAccessError`: `no_claims`·`not_operator`·
208
+ `mfa_not_performed`·`reauth_required`, 403). `decodeIdTokenClaims()`(백채널 id token 전용, 서명 미검증), `latestReoptAccount()`,
209
+ `stepUpAuthorizationParams()`, `OPERATOR_ACCESS_MESSAGES`. 서브 제품은 자기 allowlist를 지운다.
210
+ - **`@reopt-ai/brandapp-sdk/installation`** (RFC-0034 §6–§8) — 설치(리옵트 연결). `installationManifestSchema`·`manifestHash`·
211
+ `signManifest`/`verifyManifestJws`(본문의 `jwksUri`에서 키를 받아 검증, `ManifestVerifyError`), `deriveInstallationManifest`
212
+ (RFC-0030 선언 파일 → 매니페스트, 웹훅 `secret` 필수), `signInstallationAssertion`(`reopt-installation-assertion+jwt`),
213
+ `createInstallationClient`(`request`·`get`·`reinstall`·`revoke`·`refreshJwks`·`health` — 승인 전엔 단언, 활성 뒤엔 설치의
214
+ machine 토큰), `createInstallationBackchannelHandler`(`reopt-installation-event+jwt`, id JWKS·iss·aud·재생 검사),
215
+ `createReoptConnection`(§7.6 headless 상태 `unconnected|pending|connected|suspended|rejected|revoked` + `describe()` 문구),
216
+ `selfCheckJwks`, `planKeyRotation`/`confirmKeyRecognized`(회전 ②, 최대 5분 재시도). 서버 전용, `zod` 필요.
217
+ - `createMachineClient`: `scopes: []`면 토큰 요청에 `scope`를 **보내지 않는다** — id가 클라이언트 행에 등록된 scope 전부를 발급한다
218
+ (설치 클라이언트의 최소 권한). 예전엔 빈 문자열을 보냈다.
219
+ - `createReoptOAuth({ stepUp: true | seconds })` — step-up 재로그인 제공자 `reopt-step-up`(`prompt=login&max_age`)을 함께 등록한다.
220
+ `signInWithReopt(client, { stepUp: true })`가 그 제공자로 authorize를 다시 탄다. `REOPT_PROVIDER_IDS`를
221
+ `account.accountLinking.trustedProviders`에 넣고, 콜백 `/api/auth/callback/reopt-step-up`을 리옵트 클라이언트에 등록한다.
222
+
223
+ ### Changed
224
+
225
+ - 문서·예제를 서버 자격 기준으로 바꿨다 — README Quick Start·`createReoptSDK` JSDoc·`createReoptAdapter` JSDoc·설정 표·env 표가
226
+ `createMachineClient({ keyRing })` + `authorization: machine.headers`를 먼저 보여 주고, `clientSecret`은 로그인 클라이언트의
227
+ code 교환(과도기 Basic)으로만 남긴다. `validateConfig`의 자격 누락 메시지도 `authorization`을 첫 선택지로 안내한다(동작 변화 없음).
228
+
229
+ ## [4.7.0-rc.2] — 2026-10-10
230
+
231
+ ### Changed
232
+
233
+ - peer `better-auth` `^1.7.4` → `^1.7.7`. `/machine`이 쓰는 `@better-auth/core/oauth2`의 DPoP·private_key_jwt 자재는
234
+ 1.7.7부터라, 1.7.4~1.7.6 앱은 core peer가 unmet으로 떴다(핸드북 실측). 두 peer가 같은 버전을 가리킨다.
235
+
10
236
  ## [4.7.0-rc.1] — 2026-10-10
11
237
 
12
238
  Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — RFC-0034 machine credentials. Everything below ships here.
package/README.md CHANGED
@@ -18,22 +18,133 @@ npm install @reopt-ai/brandapp-sdk
18
18
 
19
19
  ## Quick Start
20
20
 
21
- ### Better Auth (Recommended)
21
+ Two kinds of credential (RFC-0034): a **login client** (`purpose: web`) whose
22
+ secret is only used to exchange the login code, and **server credentials**
23
+ (`purpose: machine` for data/AI/files/platform calls, `purpose: adapter` for
24
+ the remote Better Auth adapter) that authenticate with a private key —
25
+ `private_key_jwt` assertions plus DPoP-bound tokens — so Reopt never holds a
26
+ shared secret for server-to-server calls. Login clients are issued in the
27
+ platform console; server credentials are registered by Reopt for now.
28
+
29
+ ### Server credentials (4.7+, recommended for every server call)
30
+
31
+ ```sh
32
+ npx --package @reopt-ai/brandapp-sdk reopt-keygen # prints REOPT_CLIENT_PRIVATE_KEY_JWK='{…}'
33
+ ```
34
+
35
+ ```ts
36
+ // app/.well-known/reopt-client-jwks.json/route.ts — publish the public key
37
+ import {
38
+ buildClientJwks,
39
+ readClientKeyRing,
40
+ } from "@reopt-ai/brandapp-sdk/machine";
41
+
42
+ export const GET = () => {
43
+ const ring = readClientKeyRing();
44
+ return ring
45
+ ? Response.json(buildClientJwks(ring.published))
46
+ : new Response(null, { status: 404 });
47
+ };
48
+ ```
49
+
50
+ ```ts
51
+ // lib/reopt.ts — the unified SDK with a machine credential
52
+ import { createReoptSDK } from "@reopt-ai/brandapp-sdk";
53
+ import {
54
+ createMachineClient,
55
+ readClientKeyRing,
56
+ } from "@reopt-ai/brandapp-sdk/machine";
57
+
58
+ const machine = createMachineClient({
59
+ clientId: process.env.BRANDAPP_MACHINE_CLIENT_ID!,
60
+ keyRing: readClientKeyRing()!, // REOPT_CLIENT_PRIVATE_KEY_JWK
61
+ resource: "https://brandapp.reopt.ai", // the token's audience — exactly one
62
+ scopes: ["brandapp:read", "brandapp:write"], // brandapp:write implies eav:*
63
+ });
64
+
65
+ export const sdk = createReoptSDK({
66
+ brandappId: process.env.BRANDAPP_ID!,
67
+ clientId: machine.clientId,
68
+ authorization: machine.headers, // Authorization: DPoP … + a DPoP proof per request
69
+ });
70
+
71
+ const entities = await sdk.eav.entities.list();
72
+ ```
73
+
74
+ Register `${origin}/.well-known/reopt-client-jwks.json` as the client's
75
+ `jwksUri`. Rotation, errors and the platform client are in
76
+ [`docs/machine.md`](./docs/machine.md).
77
+
78
+ ### Connect to Reopt (installation, 4.7+)
79
+
80
+ A product declares its resources once (`reopt.workspace.ts`), signs the derived
81
+ manifest with the same private key, and asks Reopt to install it. An operator
82
+ approves in the console; the clients, API resources and webhooks are created
83
+ and their `client_id`s come back over the back-channel (or `refresh()`).
84
+
85
+ ```ts
86
+ import {
87
+ createInstallationClient,
88
+ createReoptConnection,
89
+ deriveInstallationManifest,
90
+ } from "@reopt-ai/brandapp-sdk/installation";
91
+
92
+ const manifest = deriveInstallationManifest({
93
+ declaration: workspace, // RFC-0030 declaration file
94
+ slug: "my-product",
95
+ name: "My Product",
96
+ workspaceId: process.env.REOPT_WORKSPACE_ID!,
97
+ jwksUri: "https://my-product.example/.well-known/reopt-client-jwks.json",
98
+ clients: [{ purpose: "machine", scopes: ["works:read", "works:write"] }],
99
+ });
100
+ const connection = createReoptConnection({
101
+ client: createInstallationClient({ keyRing: readClientKeyRing()! }),
102
+ manifest,
103
+ store, // one row in your DB holding the installation record
104
+ });
105
+ await connection.requestConnection(); // pending until an operator approves
106
+ ```
107
+
108
+ States, the back-channel receiver and key rotation: [`docs/installation.md`](./docs/installation.md).
109
+
110
+ ### Better Auth
111
+
112
+ Login goes through the login client; the remote adapter (users and sessions
113
+ stored in Reopt) authenticates as the `adapter` credential with the same key
114
+ ring.
22
115
 
23
116
  ```typescript
24
117
  // auth.ts
25
118
  import { betterAuth } from "better-auth";
26
- import { createReoptBetterAuth } from "@reopt-ai/brandapp-sdk/better-auth";
27
-
28
- const reopt = createReoptBetterAuth({
29
- clientId: process.env.BRANDAPP_CLIENT_ID!,
30
- clientSecret: process.env.BRANDAPP_CLIENT_SECRET!,
31
- brandappId: process.env.BRANDAPP_ID!,
119
+ import {
120
+ createReoptAdapter,
121
+ createReoptOAuth,
122
+ } from "@reopt-ai/brandapp-sdk/better-auth";
123
+ import {
124
+ createMachineClient,
125
+ readClientKeyRing,
126
+ } from "@reopt-ai/brandapp-sdk/machine";
127
+
128
+ const adapter = createMachineClient({
129
+ clientId: process.env.BRANDAPP_ADAPTER_CLIENT_ID!,
130
+ keyRing: readClientKeyRing()!,
131
+ resource: "https://brandapp.reopt.ai",
132
+ scopes: ["brandapp:auth-adapter"],
32
133
  });
33
134
 
34
135
  export const auth = betterAuth({
35
- database: reopt.database,
36
- plugins: [reopt.oauth],
136
+ database: createReoptAdapter({
137
+ brandappId: process.env.BRANDAPP_ID!,
138
+ clientId: adapter.clientId,
139
+ authorization: adapter.headers,
140
+ }),
141
+ plugins: [
142
+ createReoptOAuth({
143
+ clientId: process.env.BRANDAPP_CLIENT_ID!, // login client
144
+ clientSecret: process.env.BRANDAPP_CLIENT_SECRET!, // code exchange only
145
+ brandappId: process.env.BRANDAPP_ID!,
146
+ }),
147
+ ],
37
148
  });
38
149
  ```
39
150
 
@@ -54,19 +165,11 @@ signInWithReopt(authClient, { callbackURL: "/dashboard" });
54
165
  > registered; if you registered a custom redirect URI, add the new path in the
55
166
  > studio before upgrading.
56
167
 
57
- ### Unified SDK
58
-
59
- ```typescript
60
- import { createReoptSDK } from "@reopt-ai/brandapp-sdk";
61
-
62
- const sdk = createReoptSDK({
63
- clientId: process.env.BRANDAPP_CLIENT_ID!,
64
- clientSecret: process.env.BRANDAPP_CLIENT_SECRET!,
65
- brandappId: process.env.BRANDAPP_ID!,
66
- });
67
-
68
- const entities = await sdk.eav.entities.list();
69
- ```
168
+ > **Shared secret (transitional).** `createReoptSDK({ clientId, clientSecret })`
169
+ > and `createReoptBetterAuth({ clientId, clientSecret })` still work for login
170
+ > clients that keep transitional machine scopes, but those scopes close once an
171
+ > app has moved to a key — new integrations should start with server
172
+ > credentials.
70
173
 
71
174
  ### External marketing site (1.8+)
72
175
 
@@ -175,9 +278,9 @@ const contacts = defineEntity({
175
278
  const schema = defineSchema({ entities: { contacts } });
176
279
 
177
280
  const sdk = createReoptSDK({
178
- clientId: process.env.BRANDAPP_CLIENT_ID!,
179
- clientSecret: process.env.BRANDAPP_CLIENT_SECRET!,
180
281
  brandappId: process.env.BRANDAPP_ID!,
282
+ clientId: machine.clientId, // see "Server credentials"
283
+ authorization: machine.headers,
181
284
  schema,
182
285
  });
183
286
 
@@ -200,9 +303,9 @@ import { createLazySDK } from "@reopt-ai/brandapp-sdk";
200
303
  import schema from "./eav.schema";
201
304
 
202
305
  export const sdk = createLazySDK(() => ({
203
- clientId: process.env.BRANDAPP_CLIENT_ID!,
204
- clientSecret: process.env.BRANDAPP_CLIENT_SECRET!,
205
306
  brandappId: process.env.BRANDAPP_ID!,
307
+ clientId: machine.clientId,
308
+ authorization: machine.headers,
206
309
  schema,
207
310
  }));
208
311
 
@@ -216,7 +319,7 @@ Or use the explicit init/get pattern:
216
319
  import { initReoptSDK, getReoptSDK } from "@reopt-ai/brandapp-sdk";
217
320
 
218
321
  // At app startup
219
- initReoptSDK({ clientId, clientSecret, brandappId, schema });
322
+ initReoptSDK({ brandappId, clientId, authorization: machine.headers, schema });
220
323
 
221
324
  // Anywhere else
222
325
  const sdk = getReoptSDK();
@@ -281,28 +384,32 @@ const meta = asJson<Meta>(record.values.meta); // Meta | undefined
281
384
 
282
385
  ## Exports
283
386
 
284
- | Path | Main Exports | Requires `better-auth` |
285
- | ---------------------------- | -------------------------------------------------------------------------------------- | ---------------------- |
286
- | `"."` | `createReoptSDK`, `createLazySDK`, `initReoptSDK`, `getReoptSDK`, errors | No |
287
- | `"./better-auth"` | `createReoptBetterAuth`, `createReoptAdapter`, `createReoptOAuth` | Yes |
288
- | `"./better-auth/client"` | `signInWithReopt`, `linkReoptAccount`, `REOPT_PROVIDER_ID` | Yes |
289
- | `"./eav"` | `createReoptEavClient`, `collectAll`, EAV types, `TypedEavRecord`, `EntityClient` | No |
290
- | `"./eav/schema"` | `defineEntity`, `defineSchema`, `syncSchema`, `computeDiff`, schema/sync types | No |
291
- | `"./eav/coerce"` | `asString`, `asNumber`, `asBoolean`, `asDate`, `asJson`, `asStringArray` | No |
292
- | `"./eav/migrate"` | `defineMigration`, `runMigrations`, migration types | No |
293
- | `"./ai"` / `"./ai-provider"` | `ReoptAiClient` / `createBrandappProvider` (Vercel AI SDK) | No |
294
- | `"./auth"` | `getSessionFromCookies`, `verifySession`, `sdk.auth` client | No |
295
- | `"./cms"` | `sdk.cms` types + `toMetadata` / `toSitemapItems` / `toRssFeed` / `EditorSpec` | No |
296
- | `"./files"` | file client types + `optimizeUrl`, `createImageLoader` | No |
297
- | `"./terms"` | Terms list / consent / withdraw types | No |
298
- | `"./plans"` | `createReoptPlansClient`, `Plan` / `CheckoutSession` / `CurrentPlan` types | No |
299
- | `"./push"` | Customer device token register / unregister / list types | No |
300
- | `"./feedback"` | Customer feedback submission types | No |
301
- | `"./logout"` | `createBackchannelLogoutHandler`, `verifyBackchannelLogoutToken`, `buildEndSessionUrl` | No |
302
- | `"./webhooks"` | `createWebhookHandler`, `verifySignature` | No |
303
- | `"./react/hooks"` | TanStack Query hooks (`useAiCredits`, `useEavRecords`, …) | No |
304
- | `"./workspace"` | `createPlatformClient` — workspace-scoped platform API (**server-only**) | No |
305
- | `"./dev"` / `"./testing"` | `createDevServer` / `createTestSDK` (local dev + fixtures) | No |
387
+ | Path | Main Exports | Requires `better-auth` |
388
+ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------ |
389
+ | `"."` | `createReoptSDK`, `createLazySDK`, `initReoptSDK`, `getReoptSDK`, errors | No |
390
+ | `"./better-auth"` | `createReoptBetterAuth`, `createReoptAdapter`, `createReoptOAuth` | Yes |
391
+ | `"./better-auth/client"` | `signInWithReopt` (`{ stepUp }`), `linkReoptAccount`, `REOPT_PROVIDER_ID(S)` | Yes |
392
+ | `"./eav"` | `createReoptEavClient`, `collectAll`, EAV types, `TypedEavRecord`, `EntityClient` | No |
393
+ | `"./eav/schema"` | `defineEntity`, `defineSchema`, `syncSchema`, `computeDiff`, schema/sync types | No |
394
+ | `"./eav/coerce"` | `asString`, `asNumber`, `asBoolean`, `asDate`, `asJson`, `asStringArray` | No |
395
+ | `"./eav/migrate"` | `defineMigration`, `runMigrations`, migration types | No |
396
+ | `"./ai"` / `"./ai-provider"` | `ReoptAiClient` / `createBrandappProvider` (Vercel AI SDK) | No |
397
+ | `"./auth"` | `getSessionFromCookies`, `verifySession`, `sdk.auth` client | No |
398
+ | `"./cms"` | `sdk.cms` types + `toMetadata` / `toSitemapItems` / `toRssFeed` / `EditorSpec` | No |
399
+ | `"./files"` | file client types + `optimizeUrl`, `createImageLoader` | No |
400
+ | `"./terms"` | Terms list / consent / withdraw types | No |
401
+ | `"./plans"` | `createReoptPlansClient`, `Plan` / `CheckoutSession` / `CurrentPlan` types | No |
402
+ | `"./push"` | Customer device token register / unregister / list types | No |
403
+ | `"./feedback"` | Customer feedback submission types | No |
404
+ | `"./logout"` | `createBackchannelLogoutHandler`, `verifyBackchannelLogoutToken`, `buildEndSessionUrl` | No |
405
+ | `"./webhooks"` | `createWebhookHandler`, `verifySignature` | No |
406
+ | `"./react/hooks"` | TanStack Query hooks (`useAiCredits`, `useEavRecords`, …) | No |
407
+ | `"./workspace"` | `createPlatformClient` — workspace-scoped platform API (**server-only**) | No |
408
+ | `"./social"` | `createSocialClient` — social operations platform API: convert · review · submit · propose (**server-only**) | No |
409
+ | `"./machine"` | `createMachineClient`, `readClientKeyRing`, `buildClientJwks` — machine credentials (**server-only**) | No (`@better-auth/core`) |
410
+ | `"./resource"` | `createResourceVerifier`, `createRedisDpopReplayStore` — verify reopt machine tokens on your API (**server-only**) | No (`@better-auth/core`) |
411
+ | `"./superadmin"` | `requireOperator`, `evaluateOperator`, `decodeIdTokenClaims` — operator guard from reopt id-token claims | No |
412
+ | `"./dev"` / `"./testing"` | `createDevServer` / `createTestSDK` (local dev + fixtures) | No |
306
413
 
307
414
  > Full signatures for every sub-path: [`docs/api-reference.md`](./docs/api-reference.md).
308
415
 
@@ -318,9 +425,15 @@ const meta = asJson<Meta>(record.values.meta); // Meta | undefined
318
425
 
319
426
  ```typescript
320
427
  {
321
- clientId: string; // OAuth Client ID (required)
322
- clientSecret: string; // OAuth Client Secret (required)
323
428
  brandappId: string; // Brandapp ID (required)
429
+ clientId: string; // OAuth Client ID (required unless `token`)
430
+ authorization?: (req: { method: string; url: string }) =>
431
+ Promise<Record<string, string>>;
432
+ // Per-request auth headers — pass a machine
433
+ // client's `headers` (private_key_jwt + DPoP).
434
+ // No clientSecret needed.
435
+ clientSecret?: string; // Shared secret (Basic) — transitional; only for
436
+ // login clients that still hold machine scopes
324
437
  token?: string; // Short-lived Bearer token (Phase D-2b) —
325
438
  // overrides Basic Auth when set
326
439
  isProduction?: boolean; // true → brandapp.reopt.ai, false → brand.local.reopt.io
@@ -355,16 +468,25 @@ const meta = asJson<Meta>(record.values.meta); // Meta | undefined
355
468
 
356
469
  ## Environment Variables
357
470
 
358
- SDK는 `process.env`를 자동으로 읽습니다. 필수 변수 3개만 설정하면 나머지는
471
+ SDK는 `process.env`를 자동으로 읽습니다. 자격 변수만 설정하면 나머지는
359
472
  `NODE_ENV` 기반으로 알아서 분기합니다.
360
473
 
361
- **필수**
474
+ **자격 — 서버 자격(권장)**
475
+
476
+ | 변수 | 용도 |
477
+ | ----------------------------------- | -------------------------------------------------------------------------------------- |
478
+ | `REOPT_CLIENT_PRIVATE_KEY_JWK` | 개인키(JWK) — `reopt-keygen` 출력, 서버 전용. `readClientKeyRing()`이 읽는다 |
479
+ | `REOPT_CLIENT_PRIVATE_KEY_JWK_NEXT` | 회전 중 다음 키 — JWKS에 둘 다 실리고 서명은 NEXT로 옮겨 간다 |
480
+ | `BRANDAPP_MACHINE_CLIENT_ID` | 용도 machine 클라이언트 ID(데이터·AI·파일·플랫폼 API) — 이름은 관례, SDK가 읽지 않는다 |
481
+ | `BRANDAPP_ADAPTER_CLIENT_ID` | 용도 adapter 클라이언트 ID(원격 Better Auth 어댑터) — 위와 같음 |
482
+ | `BRANDAPP_ID` | BrandApp 고유 ID |
483
+
484
+ **자격 — 로그인 클라이언트**
362
485
 
363
- | 변수 | 용도 |
364
- | ------------------------ | --------------------------------------------------- |
365
- | `BRANDAPP_CLIENT_ID` | OAuth Client ID — Studio → BrandApp → 설정에서 발급 |
366
- | `BRANDAPP_CLIENT_SECRET` | OAuth Client Secret (1회 노출) |
367
- | `BRANDAPP_ID` | BrandApp 고유 ID |
486
+ | 변수 | 용도 |
487
+ | ------------------------ | ------------------------------------------------------------------- |
488
+ | `BRANDAPP_CLIENT_ID` | 로그인(용도 web) Client ID — 플랫폼 콘솔 → 브랜드앱 → 설정에서 발급 |
489
+ | `BRANDAPP_CLIENT_SECRET` | 로그인 Client Secret (1회 노출) — code 교환에만 |
368
490
 
369
491
  **선택 (없으면 `NODE_ENV`로 자동 분기)**
370
492
 
@@ -380,7 +502,7 @@ SDK는 `process.env`를 자동으로 읽습니다. 필수 변수 3개만 설정
380
502
  패턴은 **[docs/environment.md](./docs/environment.md)**.
381
503
 
382
504
  > **네이밍 원칙** — `BRANDAPP_*`는 consumer 자격/식별자, `REOPT_*`는 reopt 플랫폼
383
- > 호스트 정보, `BRANDAPP_SDK_*`는 SDK 자체 동작 제어.
505
+ > 호스트 정보와 서명 키, `BRANDAPP_SDK_*`는 SDK 자체 동작 제어.
384
506
 
385
507
  ## Error Handling
386
508
 
@@ -1,2 +1,52 @@
1
- import { a as CompletionOptions, c as FinishReason, d as MessageRole, f as ModelInfo, i as ChatMessage, l as ImageGenerateOptions, m as StreamEvent, n as createReoptAiClient, o as CompletionResult, p as StreamDoneData, r as AgentInfo, s as CreditInfo, t as ReoptAiClient, u as ImageGenerateResult } from "../client-Cnq_X3Wp.js";
2
- export { type AgentInfo, type ChatMessage, type CompletionOptions, type CompletionResult, type CreditInfo, type FinishReason, type ImageGenerateOptions, type ImageGenerateResult, type MessageRole, type ModelInfo, ReoptAiClient, type StreamDoneData, type StreamEvent, createReoptAiClient };
1
+ import { C as StreamEvent, S as StreamDoneData, _ as ImageGenerateOptions, a as CompletionContentPart, b as ModelInfo, c as CompletionUsage, d as EvaluateOptions, f as EvaluationAnswer, g as FinishReason, h as EvaluationResult, i as ChatMessage, l as CompletionWarning, m as EvaluationQuestion, n as createReoptAiClient, o as CompletionOptions, p as EvaluationInput, r as AgentInfo, s as CompletionResult, t as ReoptAiClient, u as CreditInfo, v as ImageGenerateResult, x as PartProviderMetadata, y as MessageRole } from "../client-CP1Jgq4R.js";
2
+ //#region src/ai/evaluator.d.ts
3
+ /**
4
+ * json-render `experimental_composeSpec`의 `evaluate`와 같은 모양(0.21 `Experimental_CompositionEvaluator`).
5
+ * json-render를 의존성으로 들이지 않으려고 구조만 같게 적는다 — 호환은 테스트가 실제 `composeSpec`에
6
+ * 꽂아 확인한다.
7
+ */
8
+ type BrandappCompositionEvaluator = (request: {
9
+ state: Record<string, unknown>;
10
+ questions: Record<string, {
11
+ type: "choice";
12
+ instructions: string;
13
+ criteria: Record<string, string>;
14
+ }>;
15
+ signal: AbortSignal;
16
+ }) => Promise<{
17
+ answers: Record<string, {
18
+ choice: string;
19
+ confidence?: number;
20
+ }>;
21
+ usage?: {
22
+ inputTokens?: number;
23
+ };
24
+ }>;
25
+ type EvaluatorSource = Pick<ReoptAiClient, "evaluate"> | {
26
+ ai: Pick<ReoptAiClient, "evaluate">;
27
+ };
28
+ /**
29
+ * 브랜드앱 크레딧으로 도는 json-render 평가자(4.7+, RFC-0041).
30
+ *
31
+ * ```ts
32
+ * for await (const event of experimental_composeSpec({
33
+ * catalog, candidates, prompt,
34
+ * evaluate: createBrandappEvaluator(sdk, { customerId }),
35
+ * })) { … }
36
+ * ```
37
+ *
38
+ * 질문은 그대로 보내고 답을 json-render 모양(`{ choice, confidence? }`)으로 옮긴다. 모델이 답을
39
+ * 거부했거나 choice가 아닌 답이 오면 던진다 — json-render는 평가자 오류를 던져 조립을 끝내고
40
+ * 마지막 스냅샷을 남기는 설계다. **서버 전용**(브라우저에서 앱 자격을 쓰지 않는다).
41
+ */
42
+ type BrandappEvaluatorOptions = Pick<EvaluateOptions, "customerId" | "timeoutMs"> & {
43
+ /**
44
+ * 평가 한 번이 끝날 때마다(성공만) 부른다 — 조립 한 번의 실제 비용을 앱이 셀 자리다. json-render는
45
+ * 입력 토큰만 넘기므로 크레딧은 여기서만 보인다. 합산은 `usage.creditCostMilli`를 더한 뒤 한 번 올림.
46
+ */
47
+ onEvaluation?: (result: EvaluationResult) => void;
48
+ };
49
+ declare function createBrandappEvaluator(source: EvaluatorSource, options?: BrandappEvaluatorOptions): BrandappCompositionEvaluator;
50
+ //#endregion
51
+ export { type AgentInfo, type BrandappCompositionEvaluator, type BrandappEvaluatorOptions, type ChatMessage, type CompletionContentPart, type CompletionOptions, type CompletionResult, type CompletionUsage, type CompletionWarning, type CreditInfo, type EvaluateOptions, type EvaluationAnswer, type EvaluationInput, type EvaluationQuestion, type EvaluationResult, type FinishReason, type ImageGenerateOptions, type ImageGenerateResult, type MessageRole, type ModelInfo, type PartProviderMetadata, ReoptAiClient, type StreamDoneData, type StreamEvent, createBrandappEvaluator, createReoptAiClient };
52
+ //# sourceMappingURL=index.d.ts.map
package/dist/ai/index.js CHANGED
@@ -1,3 +1,33 @@
1
- import { n as createReoptAiClient, t as ReoptAiClient } from "../client-BZ8-vFjk.js";
1
+ import { S as ReoptSDKError } from "../config-DaSeKofC.js";
2
+ import { n as createReoptAiClient, t as ReoptAiClient } from "../client-D97Ylva1.js";
2
3
 
3
- export { ReoptAiClient, createReoptAiClient };
4
+ //#region src/ai/evaluator.ts
5
+ function createBrandappEvaluator(source, options = {}) {
6
+ const client = "ai" in source ? source.ai : source;
7
+ return async ({ state, questions, signal }) => {
8
+ const result = await client.evaluate({
9
+ state,
10
+ questions,
11
+ ...options.timeoutMs != null ? { timeoutMs: options.timeoutMs } : {},
12
+ ...options.customerId ? { customerId: options.customerId } : {}
13
+ }, { signal });
14
+ options.onEvaluation?.(result);
15
+ const answers = {};
16
+ for (const id of Object.keys(questions)) {
17
+ const answer = result.answers[id];
18
+ if (!answer || answer.type !== "choice") throw new ReoptSDKError(answer?.type === "refusal" ? `Evaluation model declined to answer "${id}"` : `Evaluation returned no choice for "${id}"`, 502, answer?.type === "refusal" ? "EVALUATION_REFUSED" : "EVALUATION_INVALID_ANSWER");
19
+ answers[id] = {
20
+ choice: answer.choice,
21
+ ...answer.confidence != null ? { confidence: answer.confidence } : {}
22
+ };
23
+ }
24
+ return {
25
+ answers,
26
+ ...result.usage.inputTokens != null ? { usage: { inputTokens: result.usage.inputTokens } } : {}
27
+ };
28
+ };
29
+ }
30
+
31
+ //#endregion
32
+ export { ReoptAiClient, createBrandappEvaluator, createReoptAiClient };
33
+ //# sourceMappingURL=index.js.map