@acosmi/sdk-ts 2.0.0 → 2.1.0

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.
@@ -1010,6 +1010,21 @@ function apiResponseBusinessError(r) {
1010
1010
 
1011
1011
  // src/auth/auth.ts
1012
1012
  var authTimeoutMs = 3e4;
1013
+ var OAuthTokenEndpointError = class extends Error {
1014
+ status;
1015
+ oauthError;
1016
+ errorDescription;
1017
+ constructor(status, oauthError, errorDescription) {
1018
+ super(`token: HTTP ${status}: ${errorDescription || oauthError}`);
1019
+ this.name = "OAuthTokenEndpointError";
1020
+ this.status = status;
1021
+ this.oauthError = oauthError;
1022
+ this.errorDescription = errorDescription;
1023
+ }
1024
+ };
1025
+ function isInvalidGrantError(err) {
1026
+ return err instanceof OAuthTokenEndpointError && err.oauthError === "invalid_grant";
1027
+ }
1013
1028
  async function discoverWithProfile(serverURL, profile, signal) {
1014
1029
  let parsed;
1015
1030
  try {
@@ -1386,7 +1401,9 @@ async function postToken(endpoint, data, signal) {
1386
1401
  errBody = await resp.json();
1387
1402
  } catch {
1388
1403
  }
1389
- throw new Error(`token: HTTP ${resp.status}: ${errBody.error_description ?? ""}`);
1404
+ const oauthError = typeof errBody.error === "string" ? errBody.error : "";
1405
+ const errorDescription = typeof errBody.error_description === "string" ? errBody.error_description : "";
1406
+ throw new OAuthTokenEndpointError(resp.status, oauthError, errorDescription);
1390
1407
  }
1391
1408
  try {
1392
1409
  return await resp.json();
@@ -1996,6 +2013,53 @@ var FilterStatusFallbackTkdistSkew = "fallback-tkdist-deployment-skew";
1996
2013
  var FilterStatusFallbackNoBuckets = "fallback-no-buckets";
1997
2014
  var FilterStatusFallbackMissingUser = "fallback-missing-userid";
1998
2015
  var FilterStatusUnknown = "";
2016
+ var DEFAULT_GATEWAY_BASE_URL = "https://acosmi.com";
2017
+ function normalizeGatewayBaseURL(input) {
2018
+ if (typeof input !== "string") {
2019
+ throw new TypeError(
2020
+ "Acosmi Gateway URL must be a string (see docs/audit/sdk-remote-control-contract-2026-05-27.md \xA72)"
2021
+ );
2022
+ }
2023
+ const trimmed = input.trim();
2024
+ if (trimmed.length === 0) {
2025
+ throw new Error("Acosmi Gateway URL is empty");
2026
+ }
2027
+ let parsed;
2028
+ try {
2029
+ parsed = new URL(trimmed);
2030
+ } catch {
2031
+ throw new Error(`Acosmi Gateway URL is not a valid URL: ${trimmed}`);
2032
+ }
2033
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
2034
+ throw new Error(
2035
+ `Acosmi Gateway URL only allows http/https, got ${parsed.protocol} (${trimmed}). CrabCode --sdk-url (ws/wss) is the RemoteIO session channel, not a SDK gateway URL \u2014 see docs/audit/sdk-remote-control-contract-2026-05-27.md \xA71.`
2036
+ );
2037
+ }
2038
+ if (!parsed.host) {
2039
+ throw new Error(`Acosmi Gateway URL has empty host: ${trimmed}`);
2040
+ }
2041
+ if (parsed.search.length > 0 || parsed.hash.length > 0) {
2042
+ throw new Error(`Acosmi Gateway URL must not contain query or hash: ${trimmed}`);
2043
+ }
2044
+ const path = parsed.pathname.replace(/\/+$/, "");
2045
+ return path ? `${parsed.origin}${path}` : parsed.origin;
2046
+ }
2047
+ function pickAndNormalizeGatewayURL(cfg) {
2048
+ const inputs = [];
2049
+ if (cfg.serverURL !== void 0) inputs.push(["serverURL", cfg.serverURL]);
2050
+ if (cfg.baseURL !== void 0) inputs.push(["baseURL", cfg.baseURL]);
2051
+ if (cfg.baseUrl !== void 0) inputs.push(["baseUrl", cfg.baseUrl]);
2052
+ if (inputs.length === 0) return null;
2053
+ const normalized = inputs.map(([n, v]) => [n, normalizeGatewayBaseURL(v)]);
2054
+ for (let i = 1; i < normalized.length; i++) {
2055
+ if (normalized[i][1] !== normalized[0][1]) {
2056
+ throw new Error(
2057
+ `Acosmi Gateway URL conflict: Config.${normalized[0][0]}=${normalized[0][1]} vs Config.${normalized[i][0]}=${normalized[i][1]} \u2014 pass only one field.`
2058
+ );
2059
+ }
2060
+ }
2061
+ return normalized[0][1];
2062
+ }
1999
2063
  var ErrOAuthCORSBlocked = "oauth_cors_blocked";
2000
2064
  var ErrRefreshProxyFailed = "refresh_proxy_failed";
2001
2065
  var ErrTokenExpired = "token_expired";
@@ -2053,7 +2117,8 @@ var Client = class _Client {
2053
2117
  /** 串行化锁 (替代 Go sync.Mutex) */
2054
2118
  coefMu = Promise.resolve();
2055
2119
  constructor(cfg = {}) {
2056
- this.serverURL = (cfg.serverURL ?? "https://acosmi.com").replace(/\/+$/, "");
2120
+ const picked = pickAndNormalizeGatewayURL(cfg);
2121
+ this.serverURL = picked ?? DEFAULT_GATEWAY_BASE_URL;
2057
2122
  this.complianceBaseURL = cfg.complianceBaseURL ? cfg.complianceBaseURL.replace(/\/+$/, "") : null;
2058
2123
  this.oauthMetadataProfile = cfg.oauthMetadataProfile ?? "desktop";
2059
2124
  this.browserRefreshMode = cfg.browserRefreshMode ?? "direct";
@@ -2088,6 +2153,20 @@ var Client = class _Client {
2088
2153
  isAuthorized() {
2089
2154
  return this.tokens != null;
2090
2155
  }
2156
+ /**
2157
+ * 返回归一化后的 Acosmi Gateway URL (= `serverURL` 字段). readonly helper.
2158
+ *
2159
+ * Phase 0 §2 红线:
2160
+ * - 不要 mutate `client.serverURL` 字段实现 base 切换; 用 per-base Client 实例.
2161
+ * - 该值仅供日志/排查/上层缓存键使用, 不重新 normalize 它 (构造期已 normalize).
2162
+ */
2163
+ getServerURL() {
2164
+ return this.serverURL;
2165
+ }
2166
+ /** `getServerURL()` 的 alias — Phase 0 §2 baseURL 与 serverURL 同义. */
2167
+ getBaseURL() {
2168
+ return this.serverURL;
2169
+ }
2091
2170
  /** 当前 token 信息 (用于 CLI whoami 显示) */
2092
2171
  getTokenSet() {
2093
2172
  return this.tokens;
@@ -2354,6 +2433,10 @@ var Client = class _Client {
2354
2433
  );
2355
2434
  } catch (e) {
2356
2435
  const message = e instanceof Error ? e.message : String(e);
2436
+ if (isInvalidGrantError(e)) {
2437
+ await this.clearInvalidRefreshToken();
2438
+ throw new Error(`refresh token invalid; local tokens cleared: ${message}`);
2439
+ }
2357
2440
  if (isLikelyBrowserOAuthCORSError(message)) {
2358
2441
  throw new Error(`${ErrOAuthCORSBlocked}: refresh token: ${message}`);
2359
2442
  }
@@ -2388,11 +2471,18 @@ var Client = class _Client {
2388
2471
  }
2389
2472
  if (!resp.ok) {
2390
2473
  let message = "";
2474
+ let oauthError = "";
2391
2475
  try {
2392
2476
  const body2 = await resp.json();
2393
2477
  if (typeof body2.error === "string") message = body2.error;
2478
+ if (typeof body2.error === "string") oauthError = body2.error;
2479
+ if (typeof body2.error_description === "string") message = body2.error_description;
2394
2480
  } catch {
2395
2481
  }
2482
+ if (oauthError === "invalid_grant") {
2483
+ await this.clearInvalidRefreshToken();
2484
+ throw new Error(`${ErrRefreshProxyFailed}: refresh token invalid; local tokens cleared`);
2485
+ }
2396
2486
  throw new Error(`${ErrRefreshProxyFailed}: HTTP ${resp.status}: ${message}`);
2397
2487
  }
2398
2488
  let body;
@@ -2419,6 +2509,20 @@ var Client = class _Client {
2419
2509
  );
2420
2510
  }
2421
2511
  }
2512
+ async clearInvalidRefreshToken() {
2513
+ this.tokens = null;
2514
+ this.meta = null;
2515
+ this.loginInFlight = false;
2516
+ this.tokenReady = newDeferred();
2517
+ this.tokenReadyResolved = false;
2518
+ try {
2519
+ await this.store.clear();
2520
+ } catch (e) {
2521
+ console.warn(
2522
+ `[acosmi-sdk] warning: clear invalid token failed: ${e instanceof Error ? e.message : String(e)}`
2523
+ );
2524
+ }
2525
+ }
2422
2526
  /** 互斥锁 helper (替代 Go sync.Mutex) */
2423
2527
  withMu(fn) {
2424
2528
  const next = this.mu.then(fn, fn);
@@ -3617,6 +3721,10 @@ function complianceErrorToRetryAdvice(info) {
3617
3721
  var ScopeAI = "ai";
3618
3722
  var ScopeSkills = "skills";
3619
3723
  var ScopeAccount = "account";
3724
+ var ScopeRemoteControl = "remote_control";
3725
+ var ScopeRemoteControlAgentRun = "remote_control:agent-run";
3726
+ var ScopeRemoteControlSessionControl = "remote_control:session-control";
3727
+ var ScopeRemoteControlPermissionResponse = "remote_control:permission-response";
3620
3728
  var ScopeModels = "models";
3621
3729
  var ScopeModelsChat = "models:chat";
3622
3730
  var ScopeEntitlements = "entitlements";
@@ -3639,6 +3747,9 @@ function commerceScopes() {
3639
3747
  function skillScopes() {
3640
3748
  return [ScopeSkills];
3641
3749
  }
3750
+ function remoteControlScopes() {
3751
+ return [ScopeRemoteControl];
3752
+ }
3642
3753
 
3643
3754
  // src/models/index.ts
3644
3755
  init_types();
@@ -4484,6 +4595,136 @@ var AgentRunStreamError = class extends Error {
4484
4595
  }
4485
4596
  };
4486
4597
 
4598
+ // src/agent-runs/remote-control.ts
4599
+ function asRecord(v) {
4600
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return null;
4601
+ return v;
4602
+ }
4603
+ function str(rec, key) {
4604
+ const v = rec[key];
4605
+ return typeof v === "string" ? v : void 0;
4606
+ }
4607
+ function num(rec, key) {
4608
+ const v = rec[key];
4609
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
4610
+ }
4611
+ function bool(rec, key) {
4612
+ const v = rec[key];
4613
+ return typeof v === "boolean" ? v : void 0;
4614
+ }
4615
+ function parseRemoteControlEvent(raw) {
4616
+ const rec = asRecord(raw);
4617
+ if (!rec) return null;
4618
+ const type = str(rec, "type");
4619
+ if (!type) return null;
4620
+ switch (type) {
4621
+ case "text_delta": {
4622
+ const index = num(rec, "index");
4623
+ const text = str(rec, "text");
4624
+ if (typeof index !== "number" || typeof text !== "string") return null;
4625
+ return { type: "text_delta", index, text };
4626
+ }
4627
+ case "reasoning_delta": {
4628
+ const index = num(rec, "index");
4629
+ const text = str(rec, "text");
4630
+ if (typeof index !== "number" || typeof text !== "string") return null;
4631
+ return { type: "reasoning_delta", index, text };
4632
+ }
4633
+ case "tool_call": {
4634
+ const toolCallId = str(rec, "tool_call_id") ?? str(rec, "toolCallId");
4635
+ const name = str(rec, "name");
4636
+ if (!toolCallId || !name) return null;
4637
+ return {
4638
+ type: "tool_call",
4639
+ toolCallId,
4640
+ name,
4641
+ input: rec["input"],
4642
+ source: str(rec, "source")
4643
+ };
4644
+ }
4645
+ case "tool_result": {
4646
+ const toolCallId = str(rec, "tool_call_id") ?? str(rec, "toolCallId");
4647
+ const ok = bool(rec, "ok");
4648
+ if (!toolCallId || typeof ok !== "boolean") return null;
4649
+ return {
4650
+ type: "tool_result",
4651
+ toolCallId,
4652
+ ok,
4653
+ output: rec["output"],
4654
+ error: str(rec, "error")
4655
+ };
4656
+ }
4657
+ case "permission_request": {
4658
+ const requestId = str(rec, "request_id") ?? str(rec, "requestId");
4659
+ const kind = str(rec, "kind");
4660
+ if (!requestId || !kind) return null;
4661
+ return {
4662
+ type: "permission_request",
4663
+ requestId,
4664
+ kind,
4665
+ payload: rec["payload"],
4666
+ deadlineMs: num(rec, "deadline_ms") ?? num(rec, "deadlineMs")
4667
+ };
4668
+ }
4669
+ case "permission_result": {
4670
+ const requestId = str(rec, "request_id") ?? str(rec, "requestId");
4671
+ const decision = str(rec, "decision");
4672
+ if (!requestId || !decision) return null;
4673
+ return {
4674
+ type: "permission_result",
4675
+ requestId,
4676
+ decision,
4677
+ actor: str(rec, "actor"),
4678
+ decidedAt: str(rec, "decided_at") ?? str(rec, "decidedAt")
4679
+ };
4680
+ }
4681
+ case "usage": {
4682
+ return {
4683
+ type: "usage",
4684
+ inputTokens: num(rec, "input_tokens") ?? num(rec, "inputTokens"),
4685
+ outputTokens: num(rec, "output_tokens") ?? num(rec, "outputTokens"),
4686
+ cacheRead: num(rec, "cache_read") ?? num(rec, "cacheRead"),
4687
+ cacheCreate: num(rec, "cache_create") ?? num(rec, "cacheCreate"),
4688
+ exact: bool(rec, "exact")
4689
+ };
4690
+ }
4691
+ case "settle": {
4692
+ const status = str(rec, "status");
4693
+ if (!status) return null;
4694
+ return { type: "settle", status, billed: bool(rec, "billed") };
4695
+ }
4696
+ case "status": {
4697
+ const phase = str(rec, "phase");
4698
+ if (!phase) return null;
4699
+ return { type: "status", phase, message: str(rec, "message") };
4700
+ }
4701
+ case "error": {
4702
+ const code = str(rec, "code");
4703
+ const message = str(rec, "message");
4704
+ if (!code || !message) return null;
4705
+ return {
4706
+ type: "error",
4707
+ code,
4708
+ message,
4709
+ retryable: bool(rec, "retryable"),
4710
+ kind: str(rec, "kind")
4711
+ };
4712
+ }
4713
+ case "done": {
4714
+ const reason = str(rec, "reason");
4715
+ const runId = str(rec, "run_id") ?? str(rec, "runId");
4716
+ const finalStatus = str(rec, "final_status") ?? str(rec, "finalStatus");
4717
+ if (!reason || !runId || !finalStatus) return null;
4718
+ return { type: "done", reason, runId, finalStatus };
4719
+ }
4720
+ default:
4721
+ return null;
4722
+ }
4723
+ }
4724
+ function isTerminalRemoteEvent(ev) {
4725
+ return ev.type === "done" || ev.type === "settle";
4726
+ }
4727
+
4487
4728
  // src/agent-runs/client.ts
4488
4729
  var agentRunsByClient = /* @__PURE__ */ new WeakMap();
4489
4730
  Object.defineProperty(Client.prototype, "agentRuns", {
@@ -4536,6 +4777,62 @@ var AgentRunsClient = class {
4536
4777
  { retryOn401: false }
4537
4778
  ).then(fromWireRun);
4538
4779
  }
4780
+ /**
4781
+ * Create a CrabCode remote-control agent run (contract §3, ADR-2 + ADR-5).
4782
+ *
4783
+ * Equivalent to `create()` with `runtime: 'crabcode_remote'` and the required
4784
+ * `runner` + `adapter` fields set. Per-session policies (permission/workspace)
4785
+ * are forwarded to the gateway, which is the only side allowed to enforce
4786
+ * them (contract §6). The SDK never enforces remote permissions client-side.
4787
+ *
4788
+ * The corresponding stream uses `streamRemoteControl(runId)`, NOT `stream()`,
4789
+ * because the event union is different (contract §4).
4790
+ */
4791
+ async createRemoteRun(req, signal) {
4792
+ if (req.runtime !== "crabcode_remote") {
4793
+ throw new Error('createRemoteRun: runtime must be "crabcode_remote"');
4794
+ }
4795
+ if (!req.runner) throw new Error("createRemoteRun: runner is required");
4796
+ if (!req.adapter) throw new Error("createRemoteRun: adapter is required");
4797
+ return this.create(req, signal);
4798
+ }
4799
+ /**
4800
+ * Stream remote-control events for a CrabCode remote run (contract §4).
4801
+ *
4802
+ * Yields the canonical 11-event union: text_delta / reasoning_delta /
4803
+ * tool_call / tool_result / permission_request / permission_result /
4804
+ * usage / settle / status / error / done.
4805
+ *
4806
+ * Iteration ends naturally when a terminal event (`done` or `settle`) is
4807
+ * observed. Per contract §4, `error` alone is non-terminal — terminal errors
4808
+ * are carried by `done.reason` / `done.final_status`.
4809
+ *
4810
+ * Unknown event types and malformed frames are silently skipped (warn-only),
4811
+ * matching `parseRemoteControlEvent`'s null-return contract.
4812
+ */
4813
+ streamRemoteControl(runId, signal) {
4814
+ return {
4815
+ [Symbol.asyncIterator]: () => this.streamRemoteControlGen(runId, signal)
4816
+ };
4817
+ }
4818
+ async *streamRemoteControlGen(runId, signal) {
4819
+ const resp = await this.requestRaw(
4820
+ "GET",
4821
+ `/agent-runs/${encodeURIComponent(runId)}/stream`,
4822
+ null,
4823
+ signal,
4824
+ { retryOn401: true, accept: "text/event-stream" }
4825
+ );
4826
+ if (!resp.body) {
4827
+ throw new Error("remote-control stream: empty response body");
4828
+ }
4829
+ for await (const rawEvent of readAgentRunSSEFrames(resp.body)) {
4830
+ const ev = parseRemoteControlEvent(rawEvent);
4831
+ if (!ev) continue;
4832
+ yield ev;
4833
+ if (isTerminalRemoteEvent(ev)) return;
4834
+ }
4835
+ }
4539
4836
  listArtifacts(runId, signal) {
4540
4837
  return this.requestAPI(
4541
4838
  "GET",
@@ -4695,6 +4992,24 @@ var AgentRunsClient = class {
4695
4992
  return resp;
4696
4993
  }
4697
4994
  };
4995
+ function toWirePermissionPolicy(p) {
4996
+ return {
4997
+ shell_allowed: p.shellAllowed,
4998
+ shell_deny_list: p.shellDenyList,
4999
+ network_allowed: p.networkAllowed,
5000
+ write_allowed: p.writeAllowed,
5001
+ approval_timeout_ms: p.approvalTimeoutMs,
5002
+ required_actors: p.requiredActors
5003
+ };
5004
+ }
5005
+ function toWireWorkspacePolicy(p) {
5006
+ return {
5007
+ read_only: p.readOnly,
5008
+ allowed_paths: p.allowedPaths,
5009
+ denied_paths: p.deniedPaths,
5010
+ max_bytes: p.maxBytes
5011
+ };
5012
+ }
4698
5013
  function toWireCreateRequest(req) {
4699
5014
  return {
4700
5015
  app_id: req.appId,
@@ -4712,6 +5027,11 @@ function toWireCreateRequest(req) {
4712
5027
  max_bytes: req.localContextPolicy.maxBytes,
4713
5028
  allowed_tools: req.localContextPolicy.allowedTools
4714
5029
  } : void 0,
5030
+ runtime: req.runtime,
5031
+ runner: req.runner,
5032
+ adapter: req.adapter,
5033
+ permission_policy: req.permissionPolicy ? toWirePermissionPolicy(req.permissionPolicy) : void 0,
5034
+ workspace_policy: req.workspacePolicy ? toWireWorkspacePolicy(req.workspacePolicy) : void 0,
4715
5035
  artifact_policy: req.artifactPolicy ? {
4716
5036
  enabled: req.artifactPolicy.enabled,
4717
5037
  max_files: req.artifactPolicy.maxFiles
@@ -4757,6 +5077,46 @@ function fromWireArtifact(resp) {
4757
5077
  metadata: resp.metadata
4758
5078
  };
4759
5079
  }
5080
+ async function* readAgentRunSSEFrames(body) {
5081
+ let eventName = "";
5082
+ let dataLines = [];
5083
+ const flush = () => {
5084
+ if (dataLines.length === 0) return null;
5085
+ const data = dataLines.join("\n");
5086
+ dataLines = [];
5087
+ if (data === "[DONE]") return null;
5088
+ try {
5089
+ const parsed = JSON.parse(data);
5090
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
5091
+ const obj = parsed;
5092
+ if (!("type" in obj) && eventName) {
5093
+ obj.type = eventName;
5094
+ }
5095
+ return obj;
5096
+ }
5097
+ } catch {
5098
+ }
5099
+ return null;
5100
+ };
5101
+ for await (const line of iterSSELines(body)) {
5102
+ if (line === "") {
5103
+ const frame2 = flush();
5104
+ eventName = "";
5105
+ if (frame2) yield frame2;
5106
+ continue;
5107
+ }
5108
+ if (line.startsWith(":")) continue;
5109
+ if (line.startsWith("event:")) {
5110
+ eventName = line.slice("event:".length).trim();
5111
+ continue;
5112
+ }
5113
+ if (line.startsWith("data:")) {
5114
+ dataLines.push(line.slice("data:".length).trimStart());
5115
+ }
5116
+ }
5117
+ const frame = flush();
5118
+ if (frame) yield frame;
5119
+ }
4760
5120
  async function* readAgentRunEvents(body) {
4761
5121
  let eventName = "";
4762
5122
  let dataLines = [];
@@ -6146,6 +6506,11 @@ Client.prototype.listUserSubscriptions = async function(signal) {
6146
6506
  );
6147
6507
  return Array.isArray(resp.data) ? resp.data : [];
6148
6508
  };
6509
+ Client.prototype.getPlanByCode = async function(planCode, signal) {
6510
+ if (!planCode) return null;
6511
+ const plans = await this.listPlans(void 0, signal);
6512
+ return plans.find((p) => p.planCode === planCode) ?? null;
6513
+ };
6149
6514
 
6150
6515
  // src/pricing/client.ts
6151
6516
  Client.prototype.getPricingConfig = async function(key, signal) {
@@ -6519,6 +6884,41 @@ Client.prototype.listMyCorporateTransfers = async function(signal) {
6519
6884
  return resp.data ?? [];
6520
6885
  };
6521
6886
 
6522
- export { AgentRunStreamError, AgentRunsClient, AnthropicAdapter, AudienceEnum, BillingModeEnum, BucketClassCommercial, BucketClassGeneric, BusinessError, Client, ComplianceClient, CompliancePollError, LocalStorageTokenStore as DefaultBrowserTokenStore, DefaultRetryPolicy, ErrAuthDenied, ErrBillingCallbackCannotCommit, ErrBillingCommitRequiresLocalVerify, ErrBillingS2sForbidden, ErrBrowserOpen, ErrComplianceStepUpRequired, ErrDiscovery, ErrEnvelopeGateClosed, ErrOAuthCORSBlocked, ErrProviderNotConfigured, ErrProviderUnknownNoRetry, ErrRefreshProxyFailed, ErrRegistration, ErrSSLProxy, ErrSealApprovalContractHashMismatch, ErrSealApprovalExpired, ErrSealApprovalLocationMismatch, ErrSealApprovalNonceUsed, ErrSealApprovalNotApproved, ErrSealApprovalSealMismatch, ErrSealApprovalTransactorMismatch, ErrSealUseAlreadyConsumed, ErrStateMismatch, ErrTimeout, ErrTokenExchange, ErrTokenExpired, EventAuthURL, EventComplete, EventError, FileTokenStore, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, HTTPError, IdempotencyKeyHeader, InMemoryTokenStore, LocalStorageTokenStore, ModelNotFoundError, NetworkError, OpenAIAdapter, OrderTerminalError, ProductFamilyEnum, ProviderFormat, RETRY_ADVICE_REASONS, RateLimitError, RegionScopeEnum, ScopeAI, ScopeAccount, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, ServerToolTypeWebSearch, StreamError, ThinkingHigh, ThinkingHighMinMaxTokens, ThinkingMax, ThinkingMaxFallbackMaxTokens, ThinkingOff, allScopes, anthropicResponseTextContent, anthropicResponseThinkingContent, anthropicResponseToolUseBlocks, apiResponseBusinessError, apiResponseGetMessage, authorize, bucketInfoIsCommercial, bucketRowIsCommercial, buildBetas, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getAdapter, getAdapterForModel, isBillingConfirmable, isComplianceBusinessError, isComplianceTerminalError, isSSECommentLine, isSSLError, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newThinkingConfig, newTokenSet, newWebSearchTool, parseNotificationEvent, parseSettlement, parseSourcesEvent, refreshToken, register, registerWebOAuthClient, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, sanitize_exports as sanitize, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
6887
+ // src/chatbridge/types.ts
6888
+ var ALL_PLATFORMS = [
6889
+ "feishu",
6890
+ "wecom",
6891
+ "dingtalk",
6892
+ "slack",
6893
+ "teams",
6894
+ "telegram",
6895
+ "whatsapp"
6896
+ ];
6897
+ var ALL_REGIONS = ["cn", "intl"];
6898
+ var ALL_INTEGRATION_STATUS = [
6899
+ "pending",
6900
+ "active",
6901
+ "suspended",
6902
+ "revoked"
6903
+ ];
6904
+ function isPlatform(v) {
6905
+ return typeof v === "string" && ALL_PLATFORMS.includes(v);
6906
+ }
6907
+ function isRegion(v) {
6908
+ return typeof v === "string" && ALL_REGIONS.includes(v);
6909
+ }
6910
+ function isIntegrationStatus(v) {
6911
+ return typeof v === "string" && ALL_INTEGRATION_STATUS.includes(v);
6912
+ }
6913
+ function isChannelInboundEvent(v) {
6914
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return false;
6915
+ const r = v;
6916
+ return isPlatform(r.platform) && typeof r.threadHash === "string" && r.threadHash.length > 0 && typeof r.content === "string";
6917
+ }
6918
+ function asCredentialRef(s) {
6919
+ return s;
6920
+ }
6921
+
6922
+ export { ALL_INTEGRATION_STATUS, ALL_PLATFORMS, ALL_REGIONS, AgentRunStreamError, AgentRunsClient, AnthropicAdapter, AudienceEnum, BillingModeEnum, BucketClassCommercial, BucketClassGeneric, BusinessError, Client, ComplianceClient, CompliancePollError, DEFAULT_GATEWAY_BASE_URL, LocalStorageTokenStore as DefaultBrowserTokenStore, DefaultRetryPolicy, ErrAuthDenied, ErrBillingCallbackCannotCommit, ErrBillingCommitRequiresLocalVerify, ErrBillingS2sForbidden, ErrBrowserOpen, ErrComplianceStepUpRequired, ErrDiscovery, ErrEnvelopeGateClosed, ErrOAuthCORSBlocked, ErrProviderNotConfigured, ErrProviderUnknownNoRetry, ErrRefreshProxyFailed, ErrRegistration, ErrSSLProxy, ErrSealApprovalContractHashMismatch, ErrSealApprovalExpired, ErrSealApprovalLocationMismatch, ErrSealApprovalNonceUsed, ErrSealApprovalNotApproved, ErrSealApprovalSealMismatch, ErrSealApprovalTransactorMismatch, ErrSealUseAlreadyConsumed, ErrStateMismatch, ErrTimeout, ErrTokenExchange, ErrTokenExpired, EventAuthURL, EventComplete, EventError, FileTokenStore, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, HTTPError, IdempotencyKeyHeader, InMemoryTokenStore, LocalStorageTokenStore, ModelNotFoundError, NetworkError, OAuthTokenEndpointError, OpenAIAdapter, OrderTerminalError, ProductFamilyEnum, ProviderFormat, RETRY_ADVICE_REASONS, RateLimitError, RegionScopeEnum, ScopeAI, ScopeAccount, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeRemoteControl, ScopeRemoteControlAgentRun, ScopeRemoteControlPermissionResponse, ScopeRemoteControlSessionControl, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, ServerToolTypeWebSearch, StreamError, ThinkingHigh, ThinkingHighMinMaxTokens, ThinkingMax, ThinkingMaxFallbackMaxTokens, ThinkingOff, allScopes, anthropicResponseTextContent, anthropicResponseThinkingContent, anthropicResponseToolUseBlocks, apiResponseBusinessError, apiResponseGetMessage, asCredentialRef, authorize, bucketInfoIsCommercial, bucketRowIsCommercial, buildBetas, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getAdapter, getAdapterForModel, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newThinkingConfig, newTokenSet, newWebSearchTool, normalizeGatewayBaseURL, parseNotificationEvent, parseRemoteControlEvent, parseSettlement, parseSourcesEvent, refreshToken, register, registerWebOAuthClient, remoteControlScopes, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, sanitize_exports as sanitize, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
6523
6923
  //# sourceMappingURL=index.mjs.map
6524
6924
  //# sourceMappingURL=index.mjs.map