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

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 (49) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +1 -0
  3. package/dist/ai/index.d.ts +2 -2
  4. package/dist/ai/index.js +1 -1
  5. package/dist/ai-provider/index.d.ts +21 -1
  6. package/dist/ai-provider/index.js +270 -93
  7. package/dist/analytics/index.js +1 -1
  8. package/dist/auth/index.js +1 -1
  9. package/dist/better-auth/index.js +2 -2
  10. package/dist/{client-DZZEzs2l.js → client-B-Zlh9In.js} +2 -2
  11. package/dist/{client-C1yI9DiK.js → client-B1KTMiad.js} +2 -2
  12. package/dist/{client-C7k9bCwh.js → client-B6_Xb3wb.js} +2 -2
  13. package/dist/{client-DMvufVds.js → client-BPkjuPIU.js} +22 -13
  14. package/dist/{client-Dsz0BzpO.d.ts → client-CD6uK0dA.d.ts} +3 -2
  15. package/dist/{client-COlwskCB.js → client-CRa691YR.js} +2 -2
  16. package/dist/{client-Bi-KSU_r.d.ts → client-CRgkPwMT.d.ts} +32 -12
  17. package/dist/{client-UI1-_F9P.js → client-CRpW6BTX.js} +11 -5
  18. package/dist/{client-CLsqp1Jn.js → client-CSgUG6cr.js} +2 -2
  19. package/dist/{client-t7ASsw2Q.js → client-Ds11v9rE.js} +2 -2
  20. package/dist/{client-DEMD0Wo5.js → client-DsDLAw6j.js} +4 -4
  21. package/dist/{client-BrR3dzC_.js → client-DzT410Wt.js} +8 -5
  22. package/dist/{client-4x4xlk9N.js → client-XKbUKjFD.js} +3 -3
  23. package/dist/{client-DVIuxsN7.js → client-eFjdCptM.js} +2 -2
  24. package/dist/cms/index.js +1 -1
  25. package/dist/{config-Cb96ydFD.js → config-2_4Q71Vj.js} +2 -2
  26. package/dist/eav/index.js +2 -2
  27. package/dist/feedback/index.js +1 -1
  28. package/dist/files/index.js +1 -1
  29. package/dist/{http-client-DIewtTz2.js → http-client-DUR4EBMw.js} +29 -6
  30. package/dist/{index-VolJHcFS.d.ts → index-Bxfokriz.d.ts} +23 -4
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.js +12 -12
  33. package/dist/installation/index.js +3 -3
  34. package/dist/logout/index.js +1 -1
  35. package/dist/machine/index.js +1 -1
  36. package/dist/plans/index.d.ts +1 -1
  37. package/dist/plans/index.js +1 -1
  38. package/dist/push/index.js +1 -1
  39. package/dist/{query-jbkDQ1o2.js → query-CXZTvFbH.js} +2 -2
  40. package/dist/react/hooks.d.ts +2 -2
  41. package/dist/social/index.d.ts +284 -0
  42. package/dist/social/index.js +306 -0
  43. package/dist/terms/index.js +1 -1
  44. package/dist/testing/index.d.ts +1 -1
  45. package/dist/workspace/index.js +1 -1
  46. package/docs/api-reference.md +54 -9
  47. package/docs/machine.md +5 -0
  48. package/docs/social.md +92 -0
  49. package/package.json +7 -3
package/CHANGELOG.md CHANGED
@@ -7,6 +7,51 @@ This project adheres to [Semantic Versioning](https://semver.org/).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [4.7.0-rc.7] — 2026-10-28
11
+
12
+ Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — AI SDK provider의 도구 호출·구조화 출력·추론 파트 왕복.
13
+
14
+ ### Added
15
+
16
+ - `createBrandappProvider` — **도구 호출·구조화 출력·추론 파트 왕복**. `tools`·`toolChoice`(auto·none·required·
17
+ 특정 도구), `responseFormat: json`을 더 이상 `UnsupportedFunctionalityError`로 거절하지 않는다. 도구는 앱이
18
+ 실행하고 서버는 호출만 돌려준다 — `ToolLoopAgent`·`streamText` + `stopWhen` 루프가 그대로 동작하고, 단계마다
19
+ `providerMetadata.brandapp.creditCost`가 실린다. 스트림은 `reasoning-start/delta/end`·`tool-input-start/delta/end`·
20
+ `tool-call`(한 단계에 여럿 가능) 파트를 내고, 추론 파트의 `providerMetadata`(Anthropic 서명 등)를 다음 요청으로
21
+ 되돌린다. 도구 결과는 `execution-denied`·`content`(텍스트)까지 손실 없이 옮긴다(예전에는 텍스트로 뭉갰다).
22
+ `usage`에 캐시 읽기·쓰기·추론 토큰이 채워진다. 추론 강도는 `providerOptions.brandapp.reasoningEffort`
23
+ (또는 `anthropic.effort`·`openai.reasoningEffort`). 그 밖의 요청 단위 `providerOptions`는 무시한다.
24
+ **서버 쪽 전제**: 브랜드앱 AI 설정의 "도구 호출·구조화 출력 허용" + Business 플랜 — 아니면
25
+ `403 CLIENT_TOOLS_DISABLED` / `CLIENT_TOOLS_PLAN_REQUIRED`.
26
+ - `/ai` 타입 — `CompletionResult.content`(응답 파트), `CompletionUsage`(캐시·추론 토큰), `CompletionContentPart`,
27
+ `PartProviderMetadata`.
28
+
29
+ ### Changed
30
+
31
+ - provider 실행 도구(`type: "provider"`)는 요청 전에 `UnsupportedFunctionalityError`로 거절한다. 비전·파일 입력은
32
+ 여전히 거절한다.
33
+
34
+ - `@reopt-ai/brandapp-sdk/social` — 소셜 운영 플랫폼 API(RFC-0037 §7) 클라이언트 `createSocialClient`(scope
35
+ `social:read`·`social:write`): `accounts.list`, `contents.list/convert`, `posts.list/get/transition/propose`,
36
+ `reviews.run`. 모든 채널은 직접 게시라 플랫폼에 올리는 호출은 없고, 승인·게시 기록·취소는 승인함 **제안**이다.
37
+ - `/social` 계정 `profile.reviewChecklist`(RFC-0038) — 계정별 검수 기준 항목 `{text, severity}`. 응답·저장 스키마 둘 다 선택 칸.
38
+ `/workspace`와 요청기를 공유한다(`createPlatformRequester`). 문서 `docs/social.md`.
39
+ - `/social` — 글(`SocialPost`)에 `links`(변환이 본문 URL을 바꿔 넣은 추적 링크: `originalUrl`·`shortUrl`·`clicks`).
40
+ `clicks`는 리옵트 링크 원장의 누적 클릭이지 플랫폼 반응이 아니다.
41
+
42
+ ### Fixed
43
+
44
+ - 기계 자격(`authorization: machine.headers`, RFC-0034)이 **손으로 짠 요청 경로**에도 실린다 —
45
+ `ai.stream()`·`ai.streamWithMetadata()`(SSE), `files.upload()`, `files.readContent()`,
46
+ `createBrandappProvider`(언어·이미지 모델). 지금까지 이 경로들은 정적 `Basic base64("<clientId>:")`를
47
+ 보내 `401 Missing clientId or clientSecret`로 실패했다(`http.fetch`를 타는 `models`·`complete` 등은 정상).
48
+ DPoP 증명은 요청마다, 스트림 연결 재시도마다 새로 받는다. `createBrandappProvider`가 `authorization`을 받는다.
49
+ 손으로 요청을 짜는 코드는 `http.authorizationHeader` 대신 `http.requestAuthHeaders({ method, url })`를 쓴다.
50
+
51
+ - 서버 — `changePlan`으로 바꾼 플랜의 `paymentEnvironment`가 `null`로 오던 것. 바뀐 플랜에는 자기 체크아웃이 없어
52
+ "모름"이 됐고, 그 값으로 실 결제·테스트 결제만 인정하는 앱은 올린 고객의 이용권을 거뒀다. 이제 그 구독을 시작한
53
+ 체크아웃의 환경을 말한다(SDK 코드 변경 없음, 문서만).
54
+
10
55
  ## [4.7.0-rc.6] — 2026-10-15
11
56
 
12
57
  Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — 해지 예약 구독 재개(`plans.resume`)와 해지 기간 중 새 결제 차단.
package/README.md CHANGED
@@ -405,6 +405,7 @@ const meta = asJson<Meta>(record.values.meta); // Meta | undefined
405
405
  | `"./webhooks"` | `createWebhookHandler`, `verifySignature` | No |
406
406
  | `"./react/hooks"` | TanStack Query hooks (`useAiCredits`, `useEavRecords`, …) | No |
407
407
  | `"./workspace"` | `createPlatformClient` — workspace-scoped platform API (**server-only**) | No |
408
+ | `"./social"` | `createSocialClient` — social operations platform API: convert · review · submit · propose (**server-only**) | No |
408
409
  | `"./machine"` | `createMachineClient`, `readClientKeyRing`, `buildClientJwks` — machine credentials (**server-only**) | No (`@better-auth/core`) |
409
410
  | `"./resource"` | `createResourceVerifier`, `createRedisDpopReplayStore` — verify reopt machine tokens on your API (**server-only**) | No (`@better-auth/core`) |
410
411
  | `"./superadmin"` | `requireOperator`, `evaluateOperator`, `decodeIdTokenClaims` — operator guard from reopt id-token claims | No |
@@ -1,2 +1,2 @@
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-Bi-KSU_r.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 { _ 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 };
package/dist/ai/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { n as createReoptAiClient, t as ReoptAiClient } from "../client-BrR3dzC_.js";
1
+ import { n as createReoptAiClient, t as ReoptAiClient } from "../client-DzT410Wt.js";
2
2
 
3
3
  export { ReoptAiClient, createReoptAiClient };
@@ -1,10 +1,19 @@
1
+ import { n as ReoptSDKConfig } from "../config-BGT9h1OW.js";
1
2
  import { ImageModelV3, ImageModelV3CallOptions, LanguageModelV3, LanguageModelV3CallOptions, LanguageModelV3GenerateResult, LanguageModelV3StreamResult, ProviderV3 } from "@ai-sdk/provider";
2
3
  //#region src/ai-provider/brandapp-language-model.d.ts
3
4
  type BrandappLanguageModelConfig = {
4
5
  /** BrandApp API base URL */
5
6
  baseUrl: string;
6
- /** Basic Auth 헤더 (base64 인코딩된 clientId:clientSecret) */
7
+ /** 정적 Authorization 헤더 (Basic 또는 Bearer) — `authorization`이 없을 때만 쓴다 */
7
8
  authHeader: string;
9
+ /**
10
+ * 요청별 인증 헤더 제공자(RFC-0034 기계 클라이언트 DPoP). 있으면 `authHeader` 대신 매 요청
11
+ * 새로 받는다 — DPoP 증명은 메서드·URL에 묶이고 jti를 한 번만 쓸 수 있다.
12
+ */
13
+ authorization?: (request: {
14
+ method: string;
15
+ url: string;
16
+ }) => Promise<Record<string, string>>;
8
17
  /** 요청 타임아웃 (ms) */
9
18
  timeout: number;
10
19
  /** SDK 버전 문자열 */
@@ -14,10 +23,14 @@ type BrandappLanguageModelConfig = {
14
23
  /** 커스텀 fetch 함수 */
15
24
  fetch?: typeof globalThis.fetch;
16
25
  };
26
+ /** 추론 강도 — 지원 모델에만 전달된다(서버가 판정). */
27
+ type BrandappReasoningEffort = "low" | "medium" | "high";
17
28
  /** BrandApp 프로바이더 옵션 (providerOptions.brandapp으로 전달) */
18
29
  type BrandappProviderOptions = {
19
30
  /** BrandappCustomer ID (사용량 추적) */
20
31
  customerId?: string;
32
+ /** 추론 강도. 없으면 `anthropic.effort`·`openai.reasoningEffort`를 읽는다. */
33
+ reasoningEffort?: BrandappReasoningEffort;
21
34
  };
22
35
  declare class BrandappLanguageModel implements LanguageModelV3 {
23
36
  readonly specificationVersion: "v3";
@@ -70,6 +83,13 @@ type BrandappProviderConfig = {
70
83
  brandappId: string;
71
84
  /** Short-lived service token minted by `/token/mint`. */
72
85
  token?: string;
86
+ /**
87
+ * RFC-0034 per-request auth header provider — pass `machine.headers` from
88
+ * `createMachineClient`. Every request then carries `Authorization: DPoP …`
89
+ * plus a fresh `DPoP` proof, and no clientSecret is needed (same contract as
90
+ * `ReoptSDKConfig.authorization`).
91
+ */
92
+ authorization?: ReoptSDKConfig["authorization"];
73
93
  /**
74
94
  * 프로덕션 환경 여부.
75
95
  * - `true`: https://brandapp.reopt.ai
@@ -1,4 +1,4 @@
1
- import { i as resolveBaseUrl, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig, r as assertBrowserSafe } from "../config-Cb96ydFD.js";
1
+ import { i as resolveBaseUrl, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig, r as assertBrowserSafe } from "../config-2_4Q71Vj.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";
@@ -15,17 +15,24 @@ function newRequestId(sdkVersion) {
15
15
  return globalThis.crypto?.randomUUID?.() ?? `sdk-${sdkVersion}-${Date.now()}`;
16
16
  }
17
17
  /**
18
- * Call-invariant base headers (auth + content-type + SDK version). Compute
19
- * once per model and reuse via {@link mergeProviderHeaders} — these don't
20
- * change between requests.
18
+ * Call-invariant base headers (content-type + SDK version). Compute once per
19
+ * model and reuse via {@link mergeProviderHeaders}. Auth is **not** here — a
20
+ * machine client's DPoP proof changes per request; see {@link providerAuthHeaders}.
21
21
  */
22
22
  function buildBaseProviderHeaders(config) {
23
23
  return {
24
- Authorization: config.authHeader,
25
24
  "Content-Type": "application/json",
26
25
  "X-SDK-Version": `brandapp-sdk/${config.sdkVersion}`
27
26
  };
28
27
  }
28
+ /**
29
+ * Auth headers for one provider request: the per-request provider when set
30
+ * (fresh DPoP proof bound to method + URL), otherwise the static header.
31
+ */
32
+ async function providerAuthHeaders(config, request) {
33
+ if (config.authorization) return config.authorization(request);
34
+ return { Authorization: config.authHeader };
35
+ }
29
36
  /** Merge per-call headers onto a base, dropping `undefined` values. */
30
37
  function mergeProviderHeaders(base, extraHeaders) {
31
38
  if (!extraHeaders) return { ...base };
@@ -146,7 +153,13 @@ var BrandappImageModel = class {
146
153
  const requestId = newRequestId(this.config.sdkVersion);
147
154
  const response = await fetchWithTimeout(this.config, fetchFn, url, {
148
155
  method: "POST",
149
- headers: mergeProviderHeaders(buildProviderHeaders(this.config, options.headers), {
156
+ headers: mergeProviderHeaders({
157
+ ...await providerAuthHeaders(this.config, {
158
+ method: "POST",
159
+ url
160
+ }),
161
+ ...buildProviderHeaders(this.config, options.headers)
162
+ }, {
150
163
  "X-Request-Id": requestId,
151
164
  "Idempotency-Key": requestId
152
165
  }),
@@ -215,65 +228,82 @@ function arrayBufferToBase64(bytes) {
215
228
 
216
229
  //#endregion
217
230
  //#region src/ai-provider/convert-prompt.ts
231
+ function withProviderOptions(providerOptions) {
232
+ return providerOptions && Object.keys(providerOptions).length > 0 ? { providerOptions } : {};
233
+ }
218
234
  /**
219
- * AI SDK 프롬프트 → BrandApp API 메시지 배열 (+ 손실 변환 보고).
220
- *
221
- * BrandApp API는 텍스트 전용이라 비-text part는 손실된다. 무엇이 손실됐는지를
222
- * `droppedParts`로 돌려준다. 호출자는 파일 입력이면 요청을 거절하고,
223
- * 도구 이력의 텍스트 변환이면 warning으로 알린다.
235
+ * AI SDK 프롬프트 → BrandApp API 메시지 배열 (+ 드롭 보고).
224
236
  *
225
237
  * - system: content 문자열 그대로
226
- * - user: text part만 추출하여 결합 / file part는 드롭("file" 보고)
227
- * - assistant: text + tool-call을 텍스트로 표현("tool-call" 보고)
228
- * - tool: tool-result를 user 메시지 텍스트로 변환("tool-result" 보고)
238
+ * - user: text part를 결합한 문자열 / file part는 드롭("file" 보고)
239
+ * - assistant: 텍스트만 있으면 문자열, 추론·도구 호출이 있으면 파트 배열
240
+ * - tool: tool-result 파트 배열(승인 응답 파트는 서버로 보내지 않는다)
229
241
  */
230
242
  function convertPromptToBrandappMessages(prompt) {
231
243
  const messages = [];
232
244
  const dropped = /* @__PURE__ */ new Set();
233
- for (const message of prompt) {
234
- if (message.role !== "system" && message.content.some((part) => part.type === "file" || part.type === "tool-result" && part.output.type === "content" && part.output.value.some((item) => item.type !== "text"))) dropped.add("file");
235
- switch (message.role) {
236
- case "system":
237
- messages.push({
238
- role: "system",
239
- content: message.content
240
- });
241
- break;
242
- case "user": {
243
- const textParts = [];
244
- for (const part of message.content) if (part.type === "text") textParts.push(part.text);
245
- else dropped.add("file");
246
- if (textParts.length > 0) messages.push({
247
- role: "user",
248
- content: textParts.join("\n")
249
- });
250
- break;
251
- }
252
- case "assistant": {
253
- const textParts = message.content.filter((part) => part.type === "text").map((part) => part.text);
254
- const toolCallParts = message.content.filter((part) => part.type === "tool-call").map((part) => `[Tool Call: ${part.toolName}(${typeof part.input === "string" ? part.input : JSON.stringify(part.input)})]`);
255
- if (toolCallParts.length > 0) dropped.add("tool-call");
256
- const allText = [...textParts, ...toolCallParts].join("\n");
257
- if (allText.length > 0) messages.push({
258
- role: "assistant",
259
- content: allText
245
+ for (const message of prompt) switch (message.role) {
246
+ case "system":
247
+ messages.push({
248
+ role: "system",
249
+ content: message.content
250
+ });
251
+ break;
252
+ case "user": {
253
+ const textParts = [];
254
+ for (const part of message.content) if (part.type === "text") textParts.push(part.text);
255
+ else dropped.add("file");
256
+ if (textParts.length > 0) messages.push({
257
+ role: "user",
258
+ content: textParts.join("\n")
259
+ });
260
+ break;
261
+ }
262
+ case "assistant": {
263
+ const parts = [];
264
+ for (const part of message.content) if (part.type === "text") {
265
+ if (part.text.length > 0) parts.push({
266
+ type: "text",
267
+ text: part.text
260
268
  });
261
- break;
262
- }
263
- case "tool": {
264
- const resultParts = message.content.filter((part) => part.type === "tool-result").map((part) => {
265
- const output = typeof part.output === "string" ? part.output : JSON.stringify(part.output);
266
- return `[Tool Result: ${part.toolName}] ${output}`;
269
+ } else if (part.type === "reasoning") parts.push({
270
+ type: "reasoning",
271
+ text: part.text,
272
+ ...withProviderOptions(part.providerOptions)
273
+ });
274
+ else if (part.type === "tool-call") parts.push({
275
+ type: "tool-call",
276
+ toolCallId: part.toolCallId,
277
+ toolName: part.toolName,
278
+ input: part.input,
279
+ ...withProviderOptions(part.providerOptions)
280
+ });
281
+ else if (part.type === "file") dropped.add("file");
282
+ if (parts.length === 0) break;
283
+ messages.push({
284
+ role: "assistant",
285
+ content: parts.every((p) => p.type === "text") ? parts.map((p) => p.text).join("\n") : parts
286
+ });
287
+ break;
288
+ }
289
+ case "tool": {
290
+ const results = [];
291
+ for (const part of message.content) {
292
+ if (part.type !== "tool-result") continue;
293
+ if (part.output.type === "content" && part.output.value.some((item) => item.type !== "text")) dropped.add("file");
294
+ results.push({
295
+ type: "tool-result",
296
+ toolCallId: part.toolCallId,
297
+ toolName: part.toolName,
298
+ output: part.output,
299
+ ...withProviderOptions(part.providerOptions)
267
300
  });
268
- if (resultParts.length > 0) {
269
- dropped.add("tool-result");
270
- messages.push({
271
- role: "user",
272
- content: resultParts.join("\n")
273
- });
274
- }
275
- break;
276
301
  }
302
+ if (results.length > 0) messages.push({
303
+ role: "tool",
304
+ content: results
305
+ });
306
+ break;
277
307
  }
278
308
  }
279
309
  return {
@@ -284,6 +314,56 @@ function convertPromptToBrandappMessages(prompt) {
284
314
 
285
315
  //#endregion
286
316
  //#region src/ai-provider/brandapp-language-model.ts
317
+ const REASONING_EFFORTS = /* @__PURE__ */ new Set([
318
+ "low",
319
+ "medium",
320
+ "high"
321
+ ]);
322
+ function pickReasoningEffort(providerOptions) {
323
+ return [
324
+ providerOptions?.brandapp?.reasoningEffort,
325
+ providerOptions?.anthropic?.effort,
326
+ providerOptions?.openai?.reasoningEffort
327
+ ].find((v) => typeof v === "string" && REASONING_EFFORTS.has(v));
328
+ }
329
+ function toV3Usage(usage) {
330
+ const cacheRead = usage.cacheReadTokens;
331
+ const cacheWrite = usage.cacheWriteTokens;
332
+ const reasoning = usage.reasoningTokens;
333
+ const cached = (cacheRead ?? 0) + (cacheWrite ?? 0);
334
+ return {
335
+ inputTokens: {
336
+ total: usage.promptTokens,
337
+ noCache: cacheRead != null || cacheWrite != null ? Math.max(0, usage.promptTokens - cached) : void 0,
338
+ cacheRead,
339
+ cacheWrite
340
+ },
341
+ outputTokens: {
342
+ total: usage.completionTokens,
343
+ text: reasoning != null ? Math.max(0, usage.completionTokens - reasoning) : void 0,
344
+ reasoning
345
+ }
346
+ };
347
+ }
348
+ function toV3Content(parts) {
349
+ return parts.map((part) => {
350
+ if (part.type === "reasoning") return {
351
+ type: "reasoning",
352
+ text: part.text,
353
+ ...part.providerMetadata ? { providerMetadata: part.providerMetadata } : {}
354
+ };
355
+ if (part.type === "tool-call") return {
356
+ type: "tool-call",
357
+ toolCallId: part.toolCallId,
358
+ toolName: part.toolName,
359
+ input: part.input
360
+ };
361
+ return {
362
+ type: "text",
363
+ text: part.text
364
+ };
365
+ });
366
+ }
287
367
  var BrandappLanguageModel = class {
288
368
  specificationVersion = "v3";
289
369
  provider = "brandapp";
@@ -306,7 +386,13 @@ var BrandappLanguageModel = class {
306
386
  const requestId = newRequestId(this.config.sdkVersion);
307
387
  const response = await fetchWithTimeout(this.config, fetchFn, url, {
308
388
  method: "POST",
309
- headers: mergeProviderHeaders(this.baseHeaders, {
389
+ headers: mergeProviderHeaders({
390
+ ...this.baseHeaders,
391
+ ...await providerAuthHeaders(this.config, {
392
+ method: "POST",
393
+ url
394
+ })
395
+ }, {
310
396
  ...options.headers,
311
397
  "X-Request-Id": requestId,
312
398
  "Idempotency-Key": requestId
@@ -319,7 +405,7 @@ var BrandappLanguageModel = class {
319
405
  const { data } = json;
320
406
  const responseHeaders = extractResponseHeaders(response);
321
407
  return {
322
- content: [{
408
+ content: data.content ? toV3Content(data.content) : [{
323
409
  type: "text",
324
410
  text: data.message.content
325
411
  }],
@@ -330,19 +416,7 @@ var BrandappLanguageModel = class {
330
416
  unified: "stop",
331
417
  raw: "stop"
332
418
  },
333
- usage: {
334
- inputTokens: {
335
- total: data.usage.promptTokens,
336
- noCache: void 0,
337
- cacheRead: void 0,
338
- cacheWrite: void 0
339
- },
340
- outputTokens: {
341
- total: data.usage.completionTokens,
342
- text: void 0,
343
- reasoning: void 0
344
- }
345
- },
419
+ usage: toV3Usage(data.usage),
346
420
  providerMetadata: { brandapp: {
347
421
  creditCost: data.usage.creditCost,
348
422
  creditsRemaining: data.creditsRemaining,
@@ -371,9 +445,16 @@ var BrandappLanguageModel = class {
371
445
  });
372
446
  let response;
373
447
  try {
448
+ const authHeaders = await providerAuthHeaders(this.config, {
449
+ method: "POST",
450
+ url
451
+ });
374
452
  response = await fetchFn(url, {
375
453
  method: "POST",
376
- headers: mergeProviderHeaders(this.baseHeaders, {
454
+ headers: mergeProviderHeaders({
455
+ ...this.baseHeaders,
456
+ ...authHeaders
457
+ }, {
377
458
  ...options.headers,
378
459
  Accept: "text/event-stream",
379
460
  "X-Request-Id": requestId,
@@ -403,13 +484,24 @@ var BrandappLanguageModel = class {
403
484
  }
404
485
  buildRequestBody(options, stream, messages) {
405
486
  const brandappOptions = options.providerOptions?.brandapp;
487
+ const tools = options.tools?.flatMap((t) => t.type === "function" ? [{
488
+ type: "function",
489
+ name: t.name,
490
+ ...t.description ? { description: t.description } : {},
491
+ inputSchema: t.inputSchema
492
+ }] : []);
493
+ const reasoningEffort = pickReasoningEffort(options.providerOptions);
406
494
  return {
407
495
  model: this.modelId,
408
496
  messages,
409
497
  maxTokens: options.maxOutputTokens,
410
498
  temperature: options.temperature,
411
499
  stream,
412
- customerId: brandappOptions?.customerId ?? this.config.customerId
500
+ customerId: brandappOptions?.customerId ?? this.config.customerId,
501
+ ...tools?.length ? { tools } : {},
502
+ ...tools?.length && options.toolChoice ? { toolChoice: options.toolChoice } : {},
503
+ ...options.responseFormat?.type === "json" ? { responseFormat: options.responseFormat } : {},
504
+ ...reasoningEffort ? { reasoningEffort } : {}
413
505
  };
414
506
  }
415
507
  collectWarnings(options, droppedParts = []) {
@@ -418,10 +510,9 @@ var BrandappLanguageModel = class {
418
510
  functionality: "image/file input",
419
511
  message: "BrandApp AI API accepts text only. File input cannot be omitted."
420
512
  });
421
- for (const part of droppedParts) warnings.push({
422
- type: "unsupported",
423
- feature: part,
424
- details: `BrandApp AI API does not support ${part} parts natively; converted to text (lossy).`
513
+ if (options.tools?.some((t) => t.type !== "function")) throw new UnsupportedFunctionalityError({
514
+ functionality: "provider-defined tools",
515
+ message: "BrandApp AI API runs no provider tools. Define the tool as a function tool and execute it in your app."
425
516
  });
426
517
  if (options.topP != null) warnings.push({
427
518
  type: "unsupported",
@@ -448,10 +539,6 @@ var BrandappLanguageModel = class {
448
539
  feature: "stopSequences",
449
540
  details: "BrandApp AI API does not support stopSequences parameter"
450
541
  });
451
- if (options.responseFormat?.type === "json" || options.tools?.length || options.toolChoice && options.toolChoice.type !== "none" && options.toolChoice.type !== "auto") throw new UnsupportedFunctionalityError({
452
- functionality: options.responseFormat?.type === "json" ? "structured output" : "tool calling",
453
- message: "BrandApp AI API supports text generation only. This request cannot be executed as plain text."
454
- });
455
542
  if (options.seed != null) warnings.push({
456
543
  type: "unsupported",
457
544
  feature: "seed",
@@ -468,6 +555,24 @@ var BrandappLanguageModel = class {
468
555
  let emittedFinish = false;
469
556
  let emittedError = false;
470
557
  const textId = "text-0";
558
+ /** 열렸지만 아직 닫히지 않은 추론 블록 — 스트림이 끊겨도 닫아 준다. */
559
+ const openReasoning = /* @__PURE__ */ new Set();
560
+ /** JSON 이벤트 본문 — 깨졌으면 스트림 오류로 알린다(조용히 건너뛰면 도구 호출을 잃는다). */
561
+ function parseJson(data, controller) {
562
+ try {
563
+ return JSON.parse(data);
564
+ } catch {
565
+ emittedError = true;
566
+ controller.enqueue({
567
+ type: "error",
568
+ error: /* @__PURE__ */ new Error(`Invalid BrandApp stream event: ${data.slice(0, 200)}`)
569
+ });
570
+ return;
571
+ }
572
+ }
573
+ function metadataOf(value) {
574
+ return value && typeof value === "object" ? { providerMetadata: value } : {};
575
+ }
471
576
  function processSSEEvent({ event, data }, controller) {
472
577
  if (includeRawChunks) controller.enqueue({
473
578
  type: "raw",
@@ -491,6 +596,79 @@ var BrandappLanguageModel = class {
491
596
  delta: data
492
597
  });
493
598
  break;
599
+ case "reasoning-start": {
600
+ const ev = parseJson(data, controller);
601
+ if (!ev) break;
602
+ openReasoning.add(ev.id);
603
+ controller.enqueue({
604
+ type: "reasoning-start",
605
+ id: ev.id,
606
+ ...metadataOf(ev.providerMetadata)
607
+ });
608
+ break;
609
+ }
610
+ case "reasoning-delta": {
611
+ const ev = parseJson(data, controller);
612
+ if (!ev) break;
613
+ controller.enqueue({
614
+ type: "reasoning-delta",
615
+ id: ev.id,
616
+ delta: ev.delta,
617
+ ...metadataOf(ev.providerMetadata)
618
+ });
619
+ break;
620
+ }
621
+ case "reasoning-end": {
622
+ const ev = parseJson(data, controller);
623
+ if (!ev) break;
624
+ openReasoning.delete(ev.id);
625
+ controller.enqueue({
626
+ type: "reasoning-end",
627
+ id: ev.id,
628
+ ...metadataOf(ev.providerMetadata)
629
+ });
630
+ break;
631
+ }
632
+ case "tool-input-start": {
633
+ const ev = parseJson(data, controller);
634
+ if (!ev) break;
635
+ controller.enqueue({
636
+ type: "tool-input-start",
637
+ id: ev.id,
638
+ toolName: ev.toolName
639
+ });
640
+ break;
641
+ }
642
+ case "tool-input-delta": {
643
+ const ev = parseJson(data, controller);
644
+ if (!ev) break;
645
+ controller.enqueue({
646
+ type: "tool-input-delta",
647
+ id: ev.id,
648
+ delta: ev.delta
649
+ });
650
+ break;
651
+ }
652
+ case "tool-input-end": {
653
+ const ev = parseJson(data, controller);
654
+ if (!ev) break;
655
+ controller.enqueue({
656
+ type: "tool-input-end",
657
+ id: ev.id
658
+ });
659
+ break;
660
+ }
661
+ case "tool-call": {
662
+ const ev = parseJson(data, controller);
663
+ if (!ev) break;
664
+ controller.enqueue({
665
+ type: "tool-call",
666
+ toolCallId: ev.toolCallId,
667
+ toolName: ev.toolName,
668
+ input: ev.input
669
+ });
670
+ break;
671
+ }
494
672
  case "done":
495
673
  if (emittedTextStart && !emittedTextEnd) {
496
674
  controller.enqueue({
@@ -499,6 +677,11 @@ var BrandappLanguageModel = class {
499
677
  });
500
678
  emittedTextEnd = true;
501
679
  }
680
+ for (const id of openReasoning) controller.enqueue({
681
+ type: "reasoning-end",
682
+ id
683
+ });
684
+ openReasoning.clear();
502
685
  try {
503
686
  const meta = JSON.parse(data);
504
687
  if (![
@@ -509,19 +692,7 @@ var BrandappLanguageModel = class {
509
692
  ].every(Number.isFinite)) throw new Error("Invalid BrandApp completion metadata");
510
693
  controller.enqueue({
511
694
  type: "finish",
512
- usage: {
513
- inputTokens: {
514
- total: meta.usage.promptTokens,
515
- noCache: void 0,
516
- cacheRead: void 0,
517
- cacheWrite: void 0
518
- },
519
- outputTokens: {
520
- total: meta.usage.completionTokens,
521
- text: void 0,
522
- reasoning: void 0
523
- }
524
- },
695
+ usage: toV3Usage(meta.usage),
525
696
  finishReason: emittedError ? {
526
697
  unified: "error",
527
698
  raw: "stream_error"
@@ -615,6 +786,10 @@ var BrandappLanguageModel = class {
615
786
  type: "text-end",
616
787
  id: textId
617
788
  });
789
+ for (const id of openReasoning) controller.enqueue({
790
+ type: "reasoning-end",
791
+ id
792
+ });
618
793
  if (!emittedFinish) controller.enqueue({
619
794
  type: "finish",
620
795
  usage: {
@@ -731,6 +906,7 @@ function createBrandappProvider(config) {
731
906
  clientSecret: config.clientSecret,
732
907
  brandappId: config.brandappId,
733
908
  token: config.token,
909
+ authorization: config.authorization,
734
910
  isProduction: config.isProduction,
735
911
  baseUrl: config.baseUrl
736
912
  };
@@ -738,6 +914,7 @@ function createBrandappProvider(config) {
738
914
  const modelConfig = {
739
915
  baseUrl: resolveBaseUrl(sdkConfig) + `/api/v1/brandapp/${config.brandappId}/ai`,
740
916
  authHeader: createAuthHeader(sdkConfig),
917
+ authorization: config.authorization,
741
918
  timeout: config.timeout ?? 6e4,
742
919
  sdkVersion: SDK_VERSION,
743
920
  customerId: config.customerId,
@@ -1,4 +1,4 @@
1
- import { n as createReoptAnalyticsClient, t as ReoptAnalyticsClient } from "../client-COlwskCB.js";
1
+ import { n as createReoptAnalyticsClient, t as ReoptAnalyticsClient } from "../client-CRa691YR.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-DZZEzs2l.js";
1
+ import { n as createReoptAuthClient, t as ReoptAuthClient } from "../client-B-Zlh9In.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-Cb96ydFD.js";
2
- import { t as BaseHttpClient } from "../http-client-DIewtTz2.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-2_4Q71Vj.js";
2
+ import { t as BaseHttpClient } from "../http-client-DUR4EBMw.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-DIewtTz2.js";
1
+ import { t as BaseHttpClient } from "./http-client-DUR4EBMw.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-DZZEzs2l.js.map
53
+ //# sourceMappingURL=client-B-Zlh9In.js.map