@reopt-ai/brandapp-sdk 4.7.0-rc.7 → 4.7.0-rc.9

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 (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/ai/index.d.ts +52 -2
  3. package/dist/ai/index.js +32 -2
  4. package/dist/ai-provider/index.d.ts +36 -4
  5. package/dist/ai-provider/index.js +186 -26
  6. package/dist/analytics/index.js +1 -1
  7. package/dist/auth/index.js +1 -1
  8. package/dist/better-auth/index.js +2 -2
  9. package/dist/{client-B-Zlh9In.js → client-BSkEu3Bv.js} +2 -2
  10. package/dist/{client-CRgkPwMT.d.ts → client-CP1Jgq4R.d.ts} +108 -2
  11. package/dist/{client-CSgUG6cr.js → client-CezHrq4c.js} +2 -2
  12. package/dist/{client-DsDLAw6j.js → client-D5rvzXf3.js} +4 -4
  13. package/dist/{client-Ds11v9rE.js → client-D6BIpDuI.js} +2 -2
  14. package/dist/{client-XKbUKjFD.js → client-DNs5PvB4.js} +3 -3
  15. package/dist/{client-B6_Xb3wb.js → client-DmfPn8Fe.js} +2 -2
  16. package/dist/{client-BPkjuPIU.js → client-DvBL8-qz.js} +3 -3
  17. package/dist/{client-CRpW6BTX.js → client-DywMETbG.js} +3 -3
  18. package/dist/{client-eFjdCptM.js → client-Dz-IP_n_.js} +2 -2
  19. package/dist/{client-CRa691YR.js → client-Ghq4BgoW.js} +2 -2
  20. package/dist/{client-DzT410Wt.js → client-Nv1DvsTh.js} +35 -4
  21. package/dist/{client-B1KTMiad.js → client-aQa7wcA1.js} +2 -2
  22. package/dist/cms/index.js +1 -1
  23. package/dist/{config-2_4Q71Vj.js → config-CkG8Anez.js} +53 -5
  24. package/dist/dev/index.js +59 -0
  25. package/dist/eav/index.js +2 -2
  26. package/dist/feedback/index.js +1 -1
  27. package/dist/files/index.js +1 -1
  28. package/dist/{http-client-DUR4EBMw.js → http-client-C1Ahb6A0.js} +2 -2
  29. package/dist/{index-Bxfokriz.d.ts → index-CaXrNTtU.d.ts} +2 -2
  30. package/dist/index.d.ts +3 -3
  31. package/dist/index.js +12 -12
  32. package/dist/installation/index.js +3 -3
  33. package/dist/logout/index.js +1 -1
  34. package/dist/machine/index.js +1 -1
  35. package/dist/plans/index.js +1 -1
  36. package/dist/push/index.js +1 -1
  37. package/dist/{query-CXZTvFbH.js → query-5kxgEXLX.js} +2 -2
  38. package/dist/react/hooks.d.ts +2 -2
  39. package/dist/social/index.js +1 -1
  40. package/dist/terms/index.js +1 -1
  41. package/dist/testing/index.d.ts +1 -1
  42. package/dist/workspace/index.js +1 -1
  43. package/docs/api-reference.md +114 -7
  44. package/docs/errors.md +15 -0
  45. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,62 @@ This project adheres to [Semantic Versioning](https://semver.org/).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [4.7.0-rc.9] — 2026-10-30
11
+
12
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — 평가(Jev)·json-render 조립(RFC-0041). 서버 평가 중계는
13
+ 플랫폼이 열기 전까지 503 `EVALUATIONS_UNAVAILABLE`이다 — 그동안은 dev 서버로 개발한다.
14
+
15
+ ### Added
16
+
17
+ - `sdk.ai.evaluate()` — 평가 모델(Jev)에 상태와 질문(choice·score·boolean, 최대 128개)을 보내 답과 확률을 받는다
18
+ (`POST /ai/evaluations`, RFC-0041). 브랜드앱 AI 설정 "평가 허용"이 켜져 있어야 하고, 답을 못 준 호출은
19
+ 과금되지 않으며, 과금 호출이라 재시도하지 않는다.
20
+ - `createBrandappEvaluator(sdk)` — json-render `experimental_composeSpec`의 `evaluate`에 그대로 꽂는 평가자.
21
+ json-render를 의존성으로 들이지 않는다(구조 호환, 테스트가 실제 `composeSpec`으로 확인).
22
+ `onEvaluation` 콜백으로 평가마다의 실제 크레딧(`creditCostMilli`)을 받는다.
23
+ - `brandapp.decisionModel()`(`/ai-provider`) — AI SDK `experimental_evaluate`용 결정 모델(`Experimental_DecisionModelV4`).
24
+ `evaluationModel()`은 옛 이름. 크레딧은 `providerMetadata.brandapp`. 중계하지 않는 모델 id는 `NoSuchModelError`.
25
+ - dev 서버 `/ai/evaluations` — 결정적인 흉내(실서버와 같은 상한)로 json-render 조립이 오프라인에서 끝까지 돈다.
26
+ - 평가 오류 코드 7종의 `diagnostic`(원인·해결·과금 여부)과 `docs/errors.md` 표. 평가 타입을 루트에서도 export한다.
27
+
28
+ ### Fixed
29
+
30
+ - AI provider가 503 `EVALUATIONS_UNAVAILABLE`을 재시도 가능으로 표시하던 것 — 다시 보내도 같은 답이라 AI SDK의 자동
31
+ 재시도가 헛돈다.
32
+
33
+ ### Docs
34
+
35
+ - `/ai-provider` 진입점 주석이 도구 호출·구조화 출력을 "미지원"으로 적고 있었다(실제로는 4.7부터 지원) —
36
+ 지원 범위를 구현과 맞추고, 예시를 기계 자격(`authorization: machine.headers`) 기준으로 바꿨다.
37
+ - `docs/api-reference.md`에 json-render(Standalone·Inline) 연결 예시를 더했다.
38
+
39
+ ## [4.7.0-rc.8] — 2026-10-29
40
+
41
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — 도구 루프 정산·경고·끊김 처리.
42
+
43
+ ### Added
44
+
45
+ - `usage.creditCostMilli`·`providerMetadata.brandapp.creditCostMilli` — 실제 사용량(1/1000 크레딧).
46
+ `creditCost`는 올림한 정수 표시값이라 1크레딧 미만 단계도 1로 보인다. 도구 루프처럼 한 턴에 여러 단계를
47
+ 부르는 앱은 milli를 더한 뒤 한 번만 올림한다. 옛 서버 응답에는 없으므로 선택 필드다.
48
+ - 서버·모델 경고가 AI SDK의 `warnings`로 온다 — 모델이 무시한 설정, 도구 강제로 꺼진 thinking 등. 비스트리밍은
49
+ 응답 `warnings`, 스트리밍은 첫 `warnings` SSE 이벤트(SDK가 `stream-start`에 합친다). `sdk.ai` 타입에
50
+ `CompletionWarning`을 더했다.
51
+ - 403 `CLIENT_TOOLS_DISABLED`·`CLIENT_TOOLS_PLAN_REQUIRED`의 `diagnostic`이 고칠 자리(AI 설정의 도구 호출
52
+ 허용 · Business 플랜)를 가리킨다.
53
+
54
+ ### Changed
55
+
56
+ - 비스트리밍(`generateText`)의 기본 한도를 응답 전체 300초로 늘렸다 — 예전에는 스트리밍 유휴 한도와 같은
57
+ 60초가 응답 본문까지 덮어 추론·긴 JSON 응답이 끊겼다. 스트리밍은 그대로 청크 사이 60초다. `timeout`을
58
+ 지정하면 둘 다 그 값이다.
59
+ - 서버: 호출 앱이 연결을 끊으면(`abortSignal`, 탭 닫기) 모델 호출도 멈춘다 — 예전에는 끝까지 생성하고 전액
60
+ 과금했다. 끊긴 단계는 읽은 입력 + 이미 보낸 출력으로 과금한다.
61
+ - 서버: `maxTokens`(AI SDK `maxOutputTokens`)를 주지 않으면 4096이 아니라 앱 AI 설정의 최대 출력 토큰
62
+ (기본 8192)까지 쓴다 — 추론 모델과 큰 JSON 응답이 잘렸다.
63
+ - 서버: `-thinking` Anthropic 모델에 사고 요약(`display: "summarized"`)을 요청한다 — Claude 5 계열 기본값
64
+ (`omitted`)에서는 추론 파트가 텍스트 없이 서명만 왔다.
65
+
10
66
  ## [4.7.0-rc.7] — 2026-10-28
11
67
 
12
68
  Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — AI SDK provider의 도구 호출·구조화 출력·추론 파트 왕복.
@@ -1,2 +1,52 @@
1
- import { _ as StreamEvent, a as CompletionContentPart, c as CompletionUsage, d as ImageGenerateOptions, f as ImageGenerateResult, g as StreamDoneData, h as PartProviderMetadata, i as ChatMessage, l as CreditInfo, m as ModelInfo, n as createReoptAiClient, o as CompletionOptions, p as MessageRole, r as AgentInfo, s as CompletionResult, t as ReoptAiClient, u as FinishReason } from "../client-CRgkPwMT.js";
2
- export { type AgentInfo, type ChatMessage, type CompletionContentPart, type CompletionOptions, type CompletionResult, type CompletionUsage, type CreditInfo, type FinishReason, type ImageGenerateOptions, type ImageGenerateResult, type MessageRole, type ModelInfo, type PartProviderMetadata, 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-DzT410Wt.js";
1
+ import { S as ReoptSDKError } from "../config-CkG8Anez.js";
2
+ import { n as createReoptAiClient, t as ReoptAiClient } from "../client-Nv1DvsTh.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
@@ -1,5 +1,5 @@
1
1
  import { n as ReoptSDKConfig } from "../config-BGT9h1OW.js";
2
- import { ImageModelV3, ImageModelV3CallOptions, LanguageModelV3, LanguageModelV3CallOptions, LanguageModelV3GenerateResult, LanguageModelV3StreamResult, ProviderV3 } from "@ai-sdk/provider";
2
+ import { Experimental_DecisionModelV4, Experimental_DecisionModelV4CallOptions, Experimental_DecisionModelV4Result, ImageModelV3, ImageModelV3CallOptions, LanguageModelV3, LanguageModelV3CallOptions, LanguageModelV3GenerateResult, LanguageModelV3StreamResult, ProviderV3 } from "@ai-sdk/provider";
3
3
  //#region src/ai-provider/brandapp-language-model.d.ts
4
4
  type BrandappLanguageModelConfig = {
5
5
  /** BrandApp API base URL */
@@ -14,8 +14,13 @@ type BrandappLanguageModelConfig = {
14
14
  method: string;
15
15
  url: string;
16
16
  }) => Promise<Record<string, string>>;
17
- /** 요청 타임아웃 (ms) */
17
+ /** 요청 타임아웃 (ms) — 스트리밍에서는 청크 사이의 유휴 한도다. */
18
18
  timeout: number;
19
+ /**
20
+ * 비스트리밍(`doGenerate`)의 전체 한도(ms) — 응답 본문까지 기다린다. 추론·긴 JSON 응답은
21
+ * 60초를 넘기 쉬워 따로 둔다. 없으면 `timeout`.
22
+ */
23
+ generateTimeout?: number;
19
24
  /** SDK 버전 문자열 */
20
25
  sdkVersion: string;
21
26
  /** BrandappCustomer ID (사용량 추적) */
@@ -48,6 +53,26 @@ declare class BrandappLanguageModel implements LanguageModelV3 {
48
53
  private createStreamPartTransform;
49
54
  }
50
55
  //#endregion
56
+ //#region src/ai-provider/brandapp-decision-model.d.ts
57
+ /** 서버가 중계하는 평가 모델 — 지금은 Jev 하나다(서버가 고정 버전으로 부른다). */
58
+ declare const BRANDAPP_DECISION_MODEL_IDS: readonly ["typesafe-ai/jev", "typesafe-ai/jev-1.14.0"];
59
+ type BrandappDecisionModelId = (typeof BRANDAPP_DECISION_MODEL_IDS)[number];
60
+ type BrandappDecisionProviderOptions = {
61
+ /** BrandappCustomer ID (사용량 귀속) */
62
+ customerId?: string;
63
+ /** 서버 상한 1000~10000ms (기본 10000). 넘으면 504 — 과금 없음. */
64
+ timeoutMs?: number;
65
+ };
66
+ declare class BrandappDecisionModel implements Experimental_DecisionModelV4 {
67
+ readonly specificationVersion: "v4";
68
+ readonly provider = "brandapp";
69
+ readonly modelId: string;
70
+ readonly supportedQuestionTypes: readonly ["choice", "score", "boolean"];
71
+ private readonly config;
72
+ constructor(modelId: string, config: BrandappLanguageModelConfig);
73
+ doDecide(options: Experimental_DecisionModelV4CallOptions): Promise<Experimental_DecisionModelV4Result>;
74
+ }
75
+ //#endregion
51
76
  //#region src/ai-provider/brandapp-image-model.d.ts
52
77
  type BrandappImageProviderOptions = {
53
78
  /** BrandappCustomer ID (사용량 추적) */
@@ -99,7 +124,10 @@ type BrandappProviderConfig = {
99
124
  isProduction?: boolean;
100
125
  /** 커스텀 base URL */
101
126
  baseUrl?: string;
102
- /** 요청 타임아웃 ms (기본 60000 — AI 응답은 시간이 걸림) */
127
+ /**
128
+ * 요청 타임아웃 ms. 스트리밍은 청크 사이 유휴 한도(기본 60000), 비스트리밍(`generateText`)은
129
+ * 응답 전체 한도(기본 300000 — 추론·긴 JSON 응답). 지정하면 둘 다 이 값이다.
130
+ */
103
131
  timeout?: number;
104
132
  /** 기본 customerId (모든 요청에 적용) */
105
133
  customerId?: string;
@@ -126,7 +154,11 @@ type BrandappProviderConfig = {
126
154
  declare function createBrandappProvider(config: BrandappProviderConfig): BrandappProvider;
127
155
  type BrandappProvider = ProviderV3 & {
128
156
  (modelId: string): LanguageModelV3;
157
+ /** 평가 모델(Jev) — AI SDK `experimental_evaluate`의 `model`. 생략하면 `typesafe-ai/jev`. */
158
+ decisionModel(modelId?: string): BrandappDecisionModel;
159
+ /** @deprecated `decisionModel`과 같다(AI SDK의 옛 이름). */
160
+ evaluationModel(modelId?: string): BrandappDecisionModel;
129
161
  };
130
162
  //#endregion
131
- export { BrandappImageModel, type BrandappImageProviderOptions, BrandappLanguageModel, type BrandappLanguageModelConfig, BrandappProvider, BrandappProviderConfig, type BrandappProviderOptions, createBrandappProvider };
163
+ export { BRANDAPP_DECISION_MODEL_IDS, BrandappDecisionModel, type BrandappDecisionModelId, type BrandappDecisionProviderOptions, BrandappImageModel, type BrandappImageProviderOptions, BrandappLanguageModel, type BrandappLanguageModelConfig, BrandappProvider, BrandappProviderConfig, type BrandappProviderOptions, createBrandappProvider };
132
164
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,4 @@
1
- import { i as resolveBaseUrl, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig, r as assertBrowserSafe } from "../config-2_4Q71Vj.js";
1
+ import { i as resolveBaseUrl, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig, r as assertBrowserSafe } from "../config-CkG8Anez.js";
2
2
  import { t as createManagedAbort } from "../abort--nOBFN4M.js";
3
3
  import { t as createAuthHeader } from "../encoding-Bwfm3iaE.js";
4
4
  import { t as createSSELineProcessor } from "../sse-parser-FMjxM7sY.js";
@@ -90,6 +90,8 @@ async function fetchWithTimeout(config, fetchFn, url, init) {
90
90
  * `sdk.ai.*` 경로와 **동일한 코드/진단**을 노출한다(공유 mapper 사용).
91
91
  * 소비처: `err.data?.code`, `err.data?.diagnostic`, `err.cause`(ReoptSDKError).
92
92
  */
93
+ /** 플랫폼 설정이 바뀌기 전에는 같은 답이 오는 코드(예: 평가가 아직 열리지 않음 — RFC-0041). */
94
+ const NON_RETRYABLE_CODES = /* @__PURE__ */ new Set(["EVALUATIONS_UNAVAILABLE"]);
93
95
  async function throwProviderApiError(response, url, requestBodyValues, requestId) {
94
96
  const body = await response.json().catch(() => ({}));
95
97
  const code = body.error?.code;
@@ -106,7 +108,7 @@ async function throwProviderApiError(response, url, requestBodyValues, requestId
106
108
  statusCode: response.status,
107
109
  responseHeaders: extractResponseHeaders(response),
108
110
  responseBody: JSON.stringify(body),
109
- isRetryable: response.status === 429 || response.status >= 500,
111
+ isRetryable: (response.status === 429 || response.status >= 500) && !NON_RETRYABLE_CODES.has(code ?? ""),
110
112
  data: {
111
113
  code: reoptError.code,
112
114
  diagnostic: reoptError.diagnostic,
@@ -123,6 +125,106 @@ function extractResponseHeaders(response) {
123
125
  return headers;
124
126
  }
125
127
 
128
+ //#endregion
129
+ //#region src/ai-provider/brandapp-decision-model.ts
130
+ /**
131
+ * BrandApp AI SDK 결정(평가) 모델 — `Experimental_DecisionModelV4` 구현 (4.7+, RFC-0041)
132
+ *
133
+ * AI SDK의 `experimental_evaluate`(옛 이름 `experimental_decide`)를 브랜드앱 크레딧으로 돌린다.
134
+ * `/ai/evaluations`를 부르고, 서버가 덧붙인 `confidence`를 걷어 사업자 답 그대로 돌려준다 —
135
+ * 확률 분포(`probabilities`)가 같은 정보를 담고, AI SDK가 답을 스스로 검증한다.
136
+ *
137
+ * ```ts
138
+ * import { experimental_evaluate as evaluate } from "ai";
139
+ *
140
+ * const { answers, providerMetadata } = await evaluate({
141
+ * model: brandapp.decisionModel(),
142
+ * state: { ticket: "환불해 주세요" },
143
+ * questions: { intent: { type: "choice", instructions: "의도", criteria: { refund: null, other: null } } },
144
+ * });
145
+ * providerMetadata?.brandapp?.creditCostMilli;
146
+ * ```
147
+ */
148
+ /** 서버가 중계하는 평가 모델 — 지금은 Jev 하나다(서버가 고정 버전으로 부른다). */
149
+ const BRANDAPP_DECISION_MODEL_IDS = ["typesafe-ai/jev", "typesafe-ai/jev-1.14.0"];
150
+ var BrandappDecisionModel = class {
151
+ specificationVersion = "v4";
152
+ provider = "brandapp";
153
+ modelId;
154
+ supportedQuestionTypes = [
155
+ "choice",
156
+ "score",
157
+ "boolean"
158
+ ];
159
+ config;
160
+ constructor(modelId, config) {
161
+ if (!BRANDAPP_DECISION_MODEL_IDS.includes(modelId)) throw new NoSuchModelError({
162
+ modelId,
163
+ modelType: "languageModel",
164
+ message: `BrandApp evaluations relay ${BRANDAPP_DECISION_MODEL_IDS.join(", ")} only`
165
+ });
166
+ this.modelId = modelId;
167
+ this.config = config;
168
+ }
169
+ async doDecide(options) {
170
+ const brandappOptions = options.providerOptions?.brandapp;
171
+ const customerId = brandappOptions?.customerId ?? this.config.customerId;
172
+ const body = {
173
+ state: options.state,
174
+ questions: options.questions,
175
+ ...brandappOptions?.timeoutMs != null ? { timeoutMs: brandappOptions.timeoutMs } : {},
176
+ ...customerId ? { customerId } : {}
177
+ };
178
+ const url = `${this.config.baseUrl}/evaluations`;
179
+ const requestId = newRequestId(this.config.sdkVersion);
180
+ const response = await fetchWithTimeout(this.config, this.config.fetch ?? globalThis.fetch, url, {
181
+ method: "POST",
182
+ headers: mergeProviderHeaders({
183
+ ...await providerAuthHeaders(this.config, {
184
+ method: "POST",
185
+ url
186
+ }),
187
+ ...buildProviderHeaders(this.config, options.headers)
188
+ }, { "X-Request-Id": requestId }),
189
+ body: JSON.stringify(body),
190
+ signal: options.abortSignal
191
+ });
192
+ if (!response.ok) await throwProviderApiError(response, url, body, requestId);
193
+ const { data } = await response.json();
194
+ const answers = {};
195
+ for (const [id, answer] of Object.entries(data.answers)) if (answer.type === "choice") answers[id] = {
196
+ type: "choice",
197
+ choice: answer.choice,
198
+ ...answer.probabilities ? { probabilities: answer.probabilities } : {}
199
+ };
200
+ else if (answer.type === "score") answers[id] = {
201
+ type: "score",
202
+ score: answer.score,
203
+ ...answer.probabilities ? { probabilities: answer.probabilities } : {}
204
+ };
205
+ else answers[id] = answer;
206
+ return {
207
+ answers,
208
+ usage: {
209
+ ...data.usage.inputTokens != null ? { inputTokens: data.usage.inputTokens } : {},
210
+ ...data.usage.outputTokens != null ? { outputTokens: data.usage.outputTokens } : {}
211
+ },
212
+ warnings: [],
213
+ providerMetadata: { brandapp: {
214
+ creditCost: data.usage.creditCost,
215
+ creditCostMilli: data.usage.creditCostMilli,
216
+ creditsRemaining: data.creditsRemaining,
217
+ ...data.creditLimited ? { creditLimited: true } : {}
218
+ } },
219
+ response: {
220
+ id: data.id,
221
+ modelId: data.model,
222
+ headers: extractResponseHeaders(response)
223
+ }
224
+ };
225
+ }
226
+ };
227
+
126
228
  //#endregion
127
229
  //#region src/ai-provider/brandapp-image-model.ts
128
230
  var BrandappImageModel = class {
@@ -326,6 +428,22 @@ function pickReasoningEffort(providerOptions) {
326
428
  providerOptions?.openai?.reasoningEffort
327
429
  ].find((v) => typeof v === "string" && REASONING_EFFORTS.has(v));
328
430
  }
431
+ /** `warnings` SSE 이벤트 본문 — 깨졌으면 버린다(경고 때문에 스트림을 죽이지 않는다). */
432
+ function parseWarnings(data) {
433
+ try {
434
+ const parsed = JSON.parse(data);
435
+ return Array.isArray(parsed) ? parsed : [];
436
+ } catch {
437
+ return [];
438
+ }
439
+ }
440
+ /**
441
+ * 실제 사용량(1/1000 크레딧)을 providerMetadata.brandapp에 싣는다 — `creditCost`는 올림한
442
+ * 표시값이라 단계마다 더하면 과대 계상된다. 옛 서버는 보내지 않으므로 있을 때만 싣는다.
443
+ */
444
+ function milliOf(usage) {
445
+ return Number.isFinite(usage.creditCostMilli) ? { creditCostMilli: usage.creditCostMilli } : {};
446
+ }
329
447
  function toV3Usage(usage) {
330
448
  const cacheRead = usage.cacheReadTokens;
331
449
  const cacheWrite = usage.cacheWriteTokens;
@@ -384,7 +502,10 @@ var BrandappLanguageModel = class {
384
502
  const fetchFn = this.config.fetch ?? globalThis.fetch;
385
503
  const url = `${this.config.baseUrl}/chat/completions`;
386
504
  const requestId = newRequestId(this.config.sdkVersion);
387
- const response = await fetchWithTimeout(this.config, fetchFn, url, {
505
+ const response = await fetchWithTimeout({
506
+ ...this.config,
507
+ timeout: this.config.generateTimeout ?? this.config.timeout
508
+ }, fetchFn, url, {
388
509
  method: "POST",
389
510
  headers: mergeProviderHeaders({
390
511
  ...this.baseHeaders,
@@ -419,6 +540,7 @@ var BrandappLanguageModel = class {
419
540
  usage: toV3Usage(data.usage),
420
541
  providerMetadata: { brandapp: {
421
542
  creditCost: data.usage.creditCost,
543
+ ...milliOf(data.usage),
422
544
  creditsRemaining: data.creditsRemaining,
423
545
  responseId: data.id
424
546
  } },
@@ -428,7 +550,7 @@ var BrandappLanguageModel = class {
428
550
  body: json,
429
551
  modelId: data.model
430
552
  },
431
- warnings
553
+ warnings: [...warnings, ...data.warnings ?? []]
432
554
  };
433
555
  }
434
556
  async doStream(options) {
@@ -705,6 +827,7 @@ var BrandappLanguageModel = class {
705
827
  },
706
828
  providerMetadata: { brandapp: {
707
829
  creditCost: meta.usage.creditCost,
830
+ ...milliOf(meta.usage),
708
831
  creditsRemaining: meta.creditsRemaining
709
832
  } }
710
833
  });
@@ -759,19 +882,30 @@ var BrandappLanguageModel = class {
759
882
  return body.pipeThrough(new TransformStream({
760
883
  transform(chunk, controller) {
761
884
  managed.kick();
762
- if (!emittedStreamStart) {
763
- controller.enqueue({
764
- type: "stream-start",
765
- warnings
766
- });
767
- controller.enqueue({
768
- type: "response-metadata",
769
- timestamp: /* @__PURE__ */ new Date(),
770
- modelId
771
- });
772
- emittedStreamStart = true;
773
- }
774
885
  if (!processor) processor = createSSELineProcessor((sseEvent) => {
886
+ if (!emittedStreamStart) {
887
+ const serverWarnings = sseEvent.event === "warnings" ? parseWarnings(sseEvent.data) : [];
888
+ controller.enqueue({
889
+ type: "stream-start",
890
+ warnings: [...warnings, ...serverWarnings]
891
+ });
892
+ controller.enqueue({
893
+ type: "response-metadata",
894
+ timestamp: /* @__PURE__ */ new Date(),
895
+ modelId
896
+ });
897
+ emittedStreamStart = true;
898
+ if (sseEvent.event === "warnings") {
899
+ if (includeRawChunks) controller.enqueue({
900
+ type: "raw",
901
+ rawValue: {
902
+ event: sseEvent.event,
903
+ data: sseEvent.data
904
+ }
905
+ });
906
+ return;
907
+ }
908
+ }
775
909
  processSSEEvent(sseEvent, controller);
776
910
  });
777
911
  processor.feed(decoder.decode(chunk, { stream: true }));
@@ -822,24 +956,37 @@ var BrandappLanguageModel = class {
822
956
  *
823
957
  * Vercel AI SDK와 호환되는 커스텀 프로바이더를 생성합니다.
824
958
  *
825
- * **지원**: `generateText()`, `streamText()` (텍스트 생성), `generateImage()`
826
- * (이미지 생성), `providerMetadata.brandapp`(사용량/사용량), `providerOptions.brandapp`.
959
+ * **지원**: `generateText()`, `streamText()`, `ToolLoopAgent`, `experimental_evaluate`(평가 모델
960
+ * `brandapp.decisionModel()` — Jev, RFC-0041) — 텍스트·도구 호출(도구는 호출
961
+ * 앱이 실행)·구조화 출력(`responseFormat: json`)·추론 파트 왕복, `generateImage()`(이미지 생성),
962
+ * `providerMetadata.brandapp`(사용량), `providerOptions.brandapp`. 도구·구조화 출력은 브랜드앱 AI
963
+ * 설정의 "도구 호출·구조화 출력 허용"이 켜져 있어야 한다(꺼져 있으면 403 `CLIENT_TOOLS_DISABLED`).
964
+ * 범위의 정본은 `brandapp-language-model.ts` 머리 주석과 `docs/api-reference.md`다.
827
965
  *
828
- * **미지원** (호출 시 `warnings`로 알리고 해당 부분은 무시됨): tool/function calling,
829
- * 구조화 출력(`generateObject`/`responseFormat: json`), 비전·파일 입력, `topP`/`topK`/
830
- * `frequencyPenalty`/`presencePenalty`/`stopSequences`/`seed`. BrandApp AI API는 멀티
831
- * 테넌트 안전을 위해 텍스트·이미지 표면만 노출한다. 임베딩/음성/전사 모델은 없다
832
- * (`NoSuchModelError`).
966
+ * **미지원**: 비전·파일 입력과 provider 실행 도구(요청 전에 거절), `topP`/`topK`/
967
+ * `frequencyPenalty`/`presencePenalty`/`stopSequences`/`seed`(warnings로 알리고 무시).
968
+ * 임베딩/음성/전사 모델은 없다(`NoSuchModelError`).
969
+ *
970
+ * **서버 전용**이다 — 브라우저에서 `clientSecret`을 주면 거절한다. 서버 간 호출은 기계 자격
971
+ * (`@reopt-ai/brandapp-sdk/machine`)을 `authorization`으로 꽂는 것이 기본이고, `clientSecret`
972
+ * (Basic)은 그 클라이언트에 기계 scope가 남아 있을 때만 통한다(RFC-0034).
833
973
  *
834
974
  * @example
835
975
  * ```ts
836
976
  * import { createBrandappProvider } from "@reopt-ai/brandapp-sdk/ai-provider";
977
+ * import { createMachineClient, readClientKeyRing } from "@reopt-ai/brandapp-sdk/machine";
837
978
  * import { generateText, streamText } from "ai";
838
979
  *
980
+ * const machine = createMachineClient({
981
+ * clientId: process.env.BRANDAPP_MACHINE_CLIENT_ID!,
982
+ * keyRing: readClientKeyRing()!,
983
+ * resource: "https://brandapp.reopt.ai",
984
+ * scopes: ["brandapp:read", "brandapp:write"],
985
+ * });
839
986
  * const brandapp = createBrandappProvider({
840
- * clientId: process.env.BRANDAPP_CLIENT_ID!,
841
- * clientSecret: process.env.BRANDAPP_CLIENT_SECRET!,
987
+ * clientId: machine.clientId,
842
988
  * brandappId: process.env.BRANDAPP_ID!,
989
+ * authorization: machine.headers,
843
990
  * });
844
991
  *
845
992
  * // Non-streaming
@@ -916,12 +1063,14 @@ function createBrandappProvider(config) {
916
1063
  authHeader: createAuthHeader(sdkConfig),
917
1064
  authorization: config.authorization,
918
1065
  timeout: config.timeout ?? 6e4,
1066
+ generateTimeout: config.timeout ?? 3e5,
919
1067
  sdkVersion: SDK_VERSION,
920
1068
  customerId: config.customerId,
921
1069
  fetch: config.fetch
922
1070
  };
923
1071
  const languageModelCache = /* @__PURE__ */ new Map();
924
1072
  const imageModelCache = /* @__PURE__ */ new Map();
1073
+ const decisionModelCache = /* @__PURE__ */ new Map();
925
1074
  function provider(modelId) {
926
1075
  let model = languageModelCache.get(modelId);
927
1076
  if (!model) {
@@ -940,6 +1089,17 @@ function createBrandappProvider(config) {
940
1089
  }
941
1090
  return model;
942
1091
  };
1092
+ const decisionModel = (modelId = BRANDAPP_DECISION_MODEL_IDS[0]) => {
1093
+ let model = decisionModelCache.get(modelId);
1094
+ if (!model) {
1095
+ model = new BrandappDecisionModel(modelId, modelConfig);
1096
+ decisionModelCache.set(modelId, model);
1097
+ }
1098
+ return model;
1099
+ };
1100
+ provider.decisionModel = decisionModel;
1101
+ /** @deprecated AI SDK가 `decisionModel`로 이름을 바꿨다 — 같은 모델이다. */
1102
+ provider.evaluationModel = decisionModel;
943
1103
  provider.embeddingModel = (modelId) => {
944
1104
  throw new NoSuchModelError({
945
1105
  modelId,
@@ -968,5 +1128,5 @@ function createBrandappProvider(config) {
968
1128
  }
969
1129
 
970
1130
  //#endregion
971
- export { BrandappImageModel, BrandappLanguageModel, createBrandappProvider };
1131
+ export { BRANDAPP_DECISION_MODEL_IDS, BrandappDecisionModel, BrandappImageModel, BrandappLanguageModel, createBrandappProvider };
972
1132
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { n as createReoptAnalyticsClient, t as ReoptAnalyticsClient } from "../client-CRa691YR.js";
1
+ import { n as createReoptAnalyticsClient, t as ReoptAnalyticsClient } from "../client-Ghq4BgoW.js";
2
2
  import { getInstance, identify, init, pageView, setConsent, track } from "@reopt-ai/data-sdk";
3
3
 
4
4
  //#region src/analytics/browser.ts
@@ -1,4 +1,4 @@
1
- import { n as createReoptAuthClient, t as ReoptAuthClient } from "../client-B-Zlh9In.js";
1
+ import { n as createReoptAuthClient, t as ReoptAuthClient } from "../client-BSkEu3Bv.js";
2
2
 
3
3
  //#region src/auth/session.ts
4
4
  /**
@@ -1,5 +1,5 @@
1
- import { O as isReoptSDKError, S as ReoptSDKError, a as resolveIdBaseUrl, s as AuthError, t as REOPT_BASE_URLS, w as ServerError, x as RateLimitError } from "../config-2_4Q71Vj.js";
2
- import { t as BaseHttpClient } from "../http-client-DUR4EBMw.js";
1
+ import { O as isReoptSDKError, S as ReoptSDKError, a as resolveIdBaseUrl, s as AuthError, t as REOPT_BASE_URLS, w as ServerError, x as RateLimitError } from "../config-CkG8Anez.js";
2
+ import { t as BaseHttpClient } from "../http-client-C1Ahb6A0.js";
3
3
  import { o as readClientKeyRing } from "../keys-B_R_lsyF.js";
4
4
  import { a as STEP_UP_MAX_AUTH_AGE_SECONDS, i as REOPT_STEP_UP_PROVIDER_ID, n as REOPT_PROVIDER_ID, r as REOPT_PROVIDER_IDS, t as REOPT_DEFAULT_SCOPES } from "../types-DGAVaUCc.js";
5
5
  import { createAdapterFactory } from "better-auth/adapters";
@@ -1,4 +1,4 @@
1
- import { t as BaseHttpClient } from "./http-client-DUR4EBMw.js";
1
+ import { t as BaseHttpClient } from "./http-client-C1Ahb6A0.js";
2
2
 
3
3
  //#region src/auth/client.ts
4
4
  function unwrap(body) {
@@ -50,4 +50,4 @@ function createReoptAuthClient(config) {
50
50
 
51
51
  //#endregion
52
52
  export { createReoptAuthClient as n, ReoptAuthClient as t };
53
- //# sourceMappingURL=client-B-Zlh9In.js.map
53
+ //# sourceMappingURL=client-BSkEu3Bv.js.map