@tansr/sdk 0.8.0 → 0.10.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.
package/dist/index.d.ts CHANGED
@@ -14390,6 +14390,66 @@ interface McpLazyManager extends McpExpandView {
14390
14390
  forToolset(toolset: McpToolset): McpExpandView;
14391
14391
  }
14392
14392
 
14393
+ /**
14394
+ * T-C8 — 内核侧价格表:内置条目 + refreshPricing() 注入缝。
14395
+ *
14396
+ * 分层铁律(AGENTS.md):kernel(L2)不得 import providers(L1)实现。本表在
14397
+ * kernel 侧独立内置,形态与 providers/src/registry/capability-defaults.ts 的
14398
+ * pricing 对齐(同源自 doc/10 §4.1,同为 protocol PricingSchema 形态),但零
14399
+ * import 关系;providers 侧价目变更须同步本表(两处注释互指)。
14400
+ *
14401
+ * 索引粒度 = (provider, model) 二元组(W0 Spike③ 实证:MaaS 聚合工作空间同一
14402
+ * endpoint 路由多厂商,见 spikes/endpoint/REPORT.md §四.5),大小写不敏感。
14403
+ *
14404
+ * 数据溯源(逐条注释;查不到的价目一律登记为「已收录无价」条目,不编造——
14405
+ * 缺价降级路径会记 usage 不记金额并产结构化诊断):doc/10 §4.1 旗舰编码模型
14406
+ * 价位参考(¥/百万 token,输入未命中/命中/输出)。
14407
+ *
14408
+ * 来源优先级:user(用户配置)> refreshed(运行期在线刷新)> builtin(内置)。
14409
+ * 在线刷新不覆盖用户显式配置;同层重复 refresh 为 last-write-wins。
14410
+ */
14411
+
14412
+ /**
14413
+ * 内核成本计价形态:protocol Pricing 的结构超集——增补可选缓存写入价
14414
+ * (显式缓存创建溢价:Anthropic 型 1.25×/1h 2×,doc/02 §8.1、doc/80 §一;
14415
+ * 百炼显式面创建 125%——qwen3.7-max 官方价目页有 15 CNY/M 明码,doc/110 A4
14416
+ * 补录;隐式面 kimi/deepseek/glm 官方无写价 SKU(doc/80 §2.3「写免费」),
14417
+ * 该键恒不填)。填值纪律:只填文件内注释或 doc/80 §一价表已有官方出处的
14418
+ * 行,恒不臆造;缺席时 tracker 写量按 inputPerMillion 回退计(见 tracker.ts)。
14419
+ * protocol Pricing 值可直接赋值本类型;contract-v0.5(RFC-B3-3)起 Pricing 原生
14420
+ * 携带可选 tiers 阶梯,本形态自动继承(tracker 选档消费见 selectPricingTier)。
14421
+ */
14422
+ interface CostPricing extends Pricing {
14423
+ /** 缓存写入价(¥或$/百万 token);缺省时缓存写入按 inputPerMillion 计 */
14424
+ cacheWriteInputPerMillion?: number;
14425
+ }
14426
+ /**
14427
+ * 币种词表 v1(T-B2,《18》§8-2 币种裁决):国内试点两币种,ISO 4217 代码。
14428
+ * 扩词表走 RFC(与 tansrd budget.currency 同词表同节奏);金额聚合按币种
14429
+ * 分桶(tracker.ts),严禁跨币种直加——归一呈现是报表层职责(记账汇率)。
14430
+ */
14431
+ declare const PRICING_CURRENCIES: readonly ["USD", "CNY"];
14432
+ type PricingCurrency = (typeof PRICING_CURRENCIES)[number];
14433
+ /**
14434
+ * refreshPricing 的更新单元。
14435
+ * pricing 三态:对象 = 设置价目;undefined(缺省)= 登记「已收录无价」条目;
14436
+ * null = 清除该来源层的条目(恢复下层生效)。
14437
+ */
14438
+ interface PricingUpdate {
14439
+ providerId: string;
14440
+ modelName: string;
14441
+ /**
14442
+ * 缺省 'CNY'——kernel 面「缺省 = 现状语义零变化」:本表自 T-C8 起内置与
14443
+ * 注入缺省皆为人民币价(doc/10 §4.1),与 tansrd budget.pricing 的缺省
14444
+ * 'USD'(其现状 = USD/百万 token 语义)各自守现状,不互相迁就(T-B2)。
14445
+ */
14446
+ currency?: PricingCurrency;
14447
+ pricing?: CostPricing | null;
14448
+ /** 名义价标注(T-B1;语义见 PricingEntry.nominal);缺省 = 真实价 */
14449
+ nominal?: boolean;
14450
+ note?: string;
14451
+ }
14452
+
14393
14453
  /**
14394
14454
  * T-G3 — command 执行体:子进程 exec-form + stdin/exit-code/stdout 协议。
14395
14455
  *
@@ -15516,6 +15576,19 @@ type AppCapabilities = z.infer<typeof AppCapabilitiesSchema>;
15516
15576
  /** 平台缺省档(保守值;终值⏸候拍板⑥,doc/83 §八) */
15517
15577
  declare const DEFAULT_APP_CAPABILITIES: AppCapabilities;
15518
15578
 
15579
+ /**
15580
+ * bundle 模型计价段(api /t1/config 既有键;DECIMAL 串形与 cli
15581
+ * remote-bundle RemoteBundleModel.pricing 同形)。doc/110 B7 起 SDK 解析:
15582
+ * serve 平台内置形据此喂 CostTracker 价格簿(会话级 budget 闸的金额维)。
15583
+ * 服务端 t.usage 恒为计费权威,本地估算仅闸门/展示口径。
15584
+ */
15585
+ interface AppBundleModelPricing {
15586
+ currency: string;
15587
+ inPerMillion: string;
15588
+ outPerMillion: string;
15589
+ cacheReadPerMillion: string;
15590
+ cacheWritePerMillion: string;
15591
+ }
15519
15592
  /** bundle 内单模型条目(SDK 消费子集) */
15520
15593
  interface AppBundleModel {
15521
15594
  handle: string;
@@ -15533,6 +15606,8 @@ interface AppBundleModel {
15533
15606
  protocol: string;
15534
15607
  capabilities: Record<string, unknown>;
15535
15608
  contextWindow: number | null;
15609
+ /** 计价段(doc/110 B7 加法解析;缺键/坏形状 = null,恒不猜价) */
15610
+ pricing: AppBundleModelPricing | null;
15536
15611
  }
15537
15612
  /**
15538
15613
  * 图像模型受理约束(bundle platformModels.imageGen 行 constraints 加法键,
@@ -15593,6 +15668,12 @@ interface VideoModelConstraints {
15593
15668
  interface AppBundleMediaModel {
15594
15669
  model: string;
15595
15670
  displayName: string;
15671
+ /**
15672
+ * 产出托管地(S-ARCH P2-c 加法键 2026-09-02;平台媒体探针按产出 URL 宿主定性):
15673
+ * overseas = 境外托管(中国大陆网络可能无法直接访问,veo/grok 教训)/ domestic /
15674
+ * inline(b64 内联返回,无托管地问题)。缺席 = 未探/未识别(旧 api 同形)。
15675
+ */
15676
+ outputHosting?: 'domestic' | 'overseas' | 'inline';
15596
15677
  }
15597
15678
  interface AppBundleImageModel extends AppBundleMediaModel {
15598
15679
  constraints?: ImageModelConstraints;
@@ -15628,6 +15709,15 @@ declare const TANSR_PROVIDER_ID = "tansr";
15628
15709
  * 真实鉴权头由 createAppTokenFetch 包装覆写,令牌恒不进 registry env)。
15629
15710
  */
15630
15711
  declare const APP_TOKEN_PLACEHOLDER_ENV = "TANSR_SDK_APP_TOKEN_TIER";
15712
+ /**
15713
+ * doc/110 B7 — bundle 计价 → kernel 价格簿注入行(refreshed 层;cli
15714
+ * remote-bundle mapBundleToFragment 同律):币种走白名单(USD/CNY),其余
15715
+ * 币种如实跳过(tracker 侧不猜币种不误标);DECIMAL 串 → 数值,必要价
15716
+ * NaN 整条丢弃;缓存读价 >0 才落 cachedInputPerMillion;缓存写价 >0 落
15717
+ * cacheWriteInputPerMillion(CostPricing 写溢价维,doc/110 A4 同口径)。
15718
+ * 键 = (tansr, handle),与 twp 计量事件 provider/model 同口径。
15719
+ */
15720
+ declare function appBundlePricingUpdates(bundle: AppBundle): PricingUpdate[];
15631
15721
  /**
15632
15722
  * bundle 载荷 → SDK 消费子集。顶层形状非法返回 null(调用方结构化报错);
15633
15723
  * 条目级损坏逐条跳过。capabilities 段严格校验,失败回落平台缺省档
@@ -15929,6 +16019,13 @@ interface AssembledPlatformModel {
15929
16019
  * 集成方零手配)。旧 api 无段 = 双空集如实。
15930
16020
  */
15931
16021
  platformModels: AppBundlePlatformModels;
16022
+ /**
16023
+ * doc/110 B7 — bundle 计价 → kernel 价格簿注入行((tansr, handle) 键,
16024
+ * USD/CNY 白名单;appBundlePricingUpdates 语义)。消费方(serve 平台内置
16025
+ * 形)经 PricingBook.refreshPricing(rows, 'refreshed') 喂 CostTracker,
16026
+ * 会话级 budget 闸的金额维自此对 tansr 模型出数。无计价段 = 空数组。
16027
+ */
16028
+ pricingUpdates: PricingUpdate[];
15932
16029
  }
15933
16030
  /**
15934
16031
  * 令牌头注入 fetch 包装:剥 AK/SK 双头与签名三头(值只是占位哑值,但
@@ -16060,6 +16157,8 @@ interface SessionRecordMeta {
16060
16157
  * 平台会话 id(ULID 26 位 Crockford;doc/91 拍板⑤):令牌档 createSession
16061
16158
  * per-AgentSession 铸造并经 twp meta.sessionId 出线,ULID↔内核 UUID 映射
16062
16159
  * 落在此键——平台侧会话行(归因/续租/亲和)与本地记录互认的桥。
16160
+ * doc/110 B2(2026-09-02 翻案拍板⑤实施语义):resume 径**沿用**此键——
16161
+ * 缓存键/粘性/归因跨 resume 延续;旧记录无键时 resume 铸新并补录。
16063
16162
  */
16064
16163
  platformSessionId?: string;
16065
16164
  /** 开发者自留元数据域(SDK 恒不消费其内容) */
@@ -16069,7 +16168,10 @@ interface SessionRecordMeta {
16069
16168
  interface SessionStoreCreateInit {
16070
16169
  sessionId?: string;
16071
16170
  title?: string;
16072
- /** 平台会话 ULID(令牌档装配注入;重复登记时以新值对账更新) */
16171
+ /**
16172
+ * 平台会话 ULID(令牌档装配注入;重复登记时以新值对账更新——doc/110 B2
16173
+ * 起 resume 恒沿用已存值,故在场值只会是同值或旧记录无键的首次补录)
16174
+ */
16073
16175
  platformSessionId?: string;
16074
16176
  meta?: Record<string, unknown>;
16075
16177
  }
@@ -16094,7 +16196,8 @@ interface SessionRecord {
16094
16196
  * 验收:改坏存储文件须报错不静默);
16095
16197
  * - list 恒不携消息内容(枚举是元数据面);
16096
16198
  * - create 幂等(同 sessionId 重复登记返回既有记录,platformSessionId
16097
- * 以新值对账更新——resume 后的新 AgentSession 铸新平台 ULID 经此落位)。
16199
+ * 以新值对账更新——doc/110 B2:resume 后的 AgentSession **沿用**记录已存
16200
+ * 平台 ULID,本对账写只在旧记录无键(2026-09-02 前落盘)时补录新铸值)。
16098
16201
  */
16099
16202
  interface SessionStore {
16100
16203
  /** 建会话(登记 meta;id 由 store 铸造或调用方供给;幂等) */
@@ -16282,8 +16385,10 @@ declare class AgentSession {
16282
16385
  constructor(init: AgentSessionInit);
16283
16386
  get sessionId(): string;
16284
16387
  /**
16285
- * 会话事件流(async iterable;单消费者)。跨轮连续,close() 后以
16286
- * session.ended 收尾并正常终结(for-await 自然退出)。
16388
+ * 会话事件流(async iterable;**多消费者广播**,2026-09-02 起)。每次 for-await 即一个
16389
+ * 独立订阅者:SessionView 泵、Narrator、宿主自建循环可同时挂,各得全量事件、互不争抢;
16390
+ * 首订阅者收到会话创建以来的积压,晚订阅者自订阅点起。跨轮连续,close() 后以
16391
+ * session.ended 收尾并正常终结(各订阅者排空后 for-await 自然退出)。
16287
16392
  */
16288
16393
  get events(): AsyncIterable<KernelEvent>;
16289
16394
  /** 当前模型档快照 */
@@ -16625,8 +16730,9 @@ declare function viewStateFromHistory(messages: readonly IRMessage[], options?:
16625
16730
  * - AsyncIterable<KernelEvent>:直接消费;
16626
16731
  * - { events: AsyncIterable<KernelEvent> }(AgentSession 形):消费 .events。
16627
16732
  *
16628
- * 注意:AgentSession 事件流是单消费者队列——同一会话上同时挂 SessionView
16629
- * 与 Narrator(或宿主自身的 for-await)需要调用方自行扇出事件。
16733
+ * 2026-09-02 起 AgentSession.events 系多消费者广播(每次 for-await 一个独立订阅者):
16734
+ * 同一会话上同时挂 SessionView 与 Narrator(或宿主自身的 for-await)恒不再需要扇出;
16735
+ * 本泵直接消费 session.events 即可(旧 fanout 写法仍兼容——多一层无害)。
16630
16736
  *
16631
16737
  * dispose 停泵:置标志 + best-effort 调用迭代器 return()(async generator
16632
16738
  * 的 finally 释放上游);已挂起的 next() 由 return 排队语义收口。
@@ -16956,5 +17062,5 @@ declare function attachSdkTaskTool(toolset: SdkToolsetRef, config: AttachSdkTask
16956
17062
  */
16957
17063
  declare function subagentModelResolverOf(registry: ProviderRegistry | null): SubagentModelResolver | undefined;
16958
17064
 
16959
- export { APP_SDK_CONTRACT_VERSION, APP_TOKEN_PLACEHOLDER_ENV, AgentSession, AppCapabilitiesSchema, AppTokenRequestSchema, AppTokenResponseSchema, DEFAULT_APP_CAPABILITIES, DEFAULT_MAX_TOKENS, DEFAULT_MAX_TURNS, EndUserIdSchema, HEADER_APP_TOKEN, IMAGEGEN_TOOL_MAX_N, IMAGEGEN_TOOL_TIMEOUT_MS, ImageGenArgsSchema, McpHost, OUTPUT_TAIL_MAX_CHARS, PLATFORM_SEARCH_PROVIDER_NAME, QueueChannel, SequentialToolExecutor, TANSR_PROVIDER_ID, TOOL_GUIDE_LABEL, TansrSdkError, UnavailableChannel, VIDEOGEN_TOOL_MAX_DURATION, VIDEOGEN_TOOL_TIMEOUT_MS, VideoGenArgsSchema, accumulateUsage, appBundleRegistryConfig, appendUserMessage, assembleManagedModel, assemblePlatformModel, assembleSdkSkills, assembleTooling, attachSdkMcp, attachSdkTaskTool, buildClientFromRegistry, buildSdkToolSet, buildToolGuideSegment, createAppTokenFetch, createFileSessionStore, createImageGenTool, createMcpHost, createNarrator, createPlatformSearchProvider, createSdkPermissionGate, createSession, createSessionView, createVideoGenTool, defineSkill, defineTool, initialSessionViewState, markSourceFailure, parseAppBundle, providerSwitchedBody, query, reduceSessionView, resolveBuiltinSelection, resolveInitialMessages, resolvePlatformSelection, runAgent, setSessionViewDelivery, stripThinkingParts, subagentModelResolverOf, toToolDef, viewStateFromHistory };
16960
- export type { ActiveToolStatus, Answer, AppBundle, AppBundleImageModel, AppBundleMediaModel, AppBundleModel, AppBundlePlatformModels, AppBundleVideoModel, AppCapabilities, AppTokenRequest, AppTokenResponse, AskUserCallback, AssembleManagedModelOptions, AssemblePlatformModelOptions, AssembleToolingOptions, AssembledManagedModel, AssembledPlatformModel, AssembledSkills, AssembledTooling, AttachSdkTaskToolConfig, BuildSdkToolSetOptions, BuiltinToolName, Capability, CompactNowOptions, CompactNowResult, ConfigDiagnostic, CreateFileSessionStoreOptions, CreateImageGenToolOptions, CreatePlatformSearchProviderOptions, CreateSdkPermissionGateOptions, CreateSessionOptions, CreateVideoGenToolOptions, DecisionSource, DefineSkillOptions, DefineToolOptions, DefinedSkill, DefinedTool, DeliveryConfig, ErrorView, EventBody, EventEnvelope, GateDecision, HistoryCommitMeta, HookOutcomeStatus, IRBlock, IRErrorKind, IRMessage, IRRequest, IRRole, IRStreamEvent, IRSystemSegment, IRToolContent, IRToolDef, IRToolResultBlock, IRUsage, ImageGenArgs, ImageGenData, ImageModelConstraints, Integrity, JournalKind, JournalRecord, KernelEvent, KernelState, LoadConfigOptions, LoadedConfig, ManagedQueryOptions, McpClientEvent, McpConnectFactory, McpConnection, McpEventObserver, McpHostOptions, McpServerConfig, McpSessionOption, ModelCallOptions, ModelClient, Narrator, NarratorOptions, NarratorVerbosity, PermissionDecision, PermissionGate, PermissionMode, PermissionOptions, PermissionRules, PlatformCapabilityName, PlatformToolContext, PlatformWarning, Pricing, PromptCachingMode, PromptChannel, ProposedToolCall, ProtocolKind, ProviderProfile, QueryCompactionOptions, QueryCounters, QueryHandle, QueryOptions, QueryResult, Question, QuestionOption, ResolvedModel, RunAgentOptions, SdkErrorCode, SdkSkillsOptions, SdkToolSet, SdkToolsOptions, SdkToolsetRef, SequentialToolHandler, SequentialToolResult, SessionEventSource, SessionRecord, SessionRecordMeta, SessionStore, SessionStoreCommitMeta, SessionStoreCreateInit, SessionView, SessionViewDeliveryOptions, SessionViewOptions, SessionViewReducerState, SessionViewSource, SessionViewState, SessionViewStatus, SetModelBinding, SkillsFileSystem, TansrConfig, TerminalReason, TextDeliveryMode, ThinkingDeliveryMode, TodoView, Tool, ToolCallPartStatus, ToolCallView, ToolContext, ToolErrorType, ToolExecutionContext, ToolExecutionOutcome, ToolExecutor, ToolExecutorYield, ToolParameterSpec, ToolResult, ToolResultContent, UIMessage, UIMessagePart, UITextPart, UIThinkingPart, UIToolCallPart, UsageView, VideoGenArgs, VideoGenData, VideoModelConstraints, Visibility };
17065
+ export { APP_SDK_CONTRACT_VERSION, APP_TOKEN_PLACEHOLDER_ENV, AgentSession, AppCapabilitiesSchema, AppTokenRequestSchema, AppTokenResponseSchema, DEFAULT_APP_CAPABILITIES, DEFAULT_MAX_TOKENS, DEFAULT_MAX_TURNS, EndUserIdSchema, HEADER_APP_TOKEN, IMAGEGEN_TOOL_MAX_N, IMAGEGEN_TOOL_TIMEOUT_MS, ImageGenArgsSchema, McpHost, OUTPUT_TAIL_MAX_CHARS, PLATFORM_SEARCH_PROVIDER_NAME, QueueChannel, SequentialToolExecutor, TANSR_PROVIDER_ID, TOOL_GUIDE_LABEL, TansrSdkError, UnavailableChannel, VIDEOGEN_TOOL_MAX_DURATION, VIDEOGEN_TOOL_TIMEOUT_MS, VideoGenArgsSchema, accumulateUsage, appBundlePricingUpdates, appBundleRegistryConfig, appendUserMessage, assembleManagedModel, assemblePlatformModel, assembleSdkSkills, assembleTooling, attachSdkMcp, attachSdkTaskTool, buildClientFromRegistry, buildSdkToolSet, buildToolGuideSegment, createAppTokenFetch, createFileSessionStore, createImageGenTool, createMcpHost, createNarrator, createPlatformSearchProvider, createSdkPermissionGate, createSession, createSessionView, createVideoGenTool, defineSkill, defineTool, initialSessionViewState, markSourceFailure, parseAppBundle, providerSwitchedBody, query, reduceSessionView, resolveBuiltinSelection, resolveInitialMessages, resolvePlatformSelection, runAgent, setSessionViewDelivery, stripThinkingParts, subagentModelResolverOf, toToolDef, viewStateFromHistory };
17066
+ export type { ActiveToolStatus, Answer, AppBundle, AppBundleImageModel, AppBundleMediaModel, AppBundleModel, AppBundleModelPricing, AppBundlePlatformModels, AppBundleVideoModel, AppCapabilities, AppTokenRequest, AppTokenResponse, AskUserCallback, AssembleManagedModelOptions, AssemblePlatformModelOptions, AssembleToolingOptions, AssembledManagedModel, AssembledPlatformModel, AssembledSkills, AssembledTooling, AttachSdkTaskToolConfig, BuildSdkToolSetOptions, BuiltinToolName, Capability, CompactNowOptions, CompactNowResult, ConfigDiagnostic, CreateFileSessionStoreOptions, CreateImageGenToolOptions, CreatePlatformSearchProviderOptions, CreateSdkPermissionGateOptions, CreateSessionOptions, CreateVideoGenToolOptions, DecisionSource, DefineSkillOptions, DefineToolOptions, DefinedSkill, DefinedTool, DeliveryConfig, ErrorView, EventBody, EventEnvelope, GateDecision, HistoryCommitMeta, HookOutcomeStatus, IRBlock, IRErrorKind, IRMessage, IRRequest, IRRole, IRStreamEvent, IRSystemSegment, IRToolContent, IRToolDef, IRToolResultBlock, IRUsage, ImageGenArgs, ImageGenData, ImageModelConstraints, Integrity, JournalKind, JournalRecord, KernelEvent, KernelState, LoadConfigOptions, LoadedConfig, ManagedQueryOptions, McpClientEvent, McpConnectFactory, McpConnection, McpEventObserver, McpHostOptions, McpServerConfig, McpSessionOption, ModelCallOptions, ModelClient, Narrator, NarratorOptions, NarratorVerbosity, PermissionDecision, PermissionGate, PermissionMode, PermissionOptions, PermissionRules, PlatformCapabilityName, PlatformToolContext, PlatformWarning, Pricing, PromptCachingMode, PromptChannel, ProposedToolCall, ProtocolKind, ProviderProfile, QueryCompactionOptions, QueryCounters, QueryHandle, QueryOptions, QueryResult, Question, QuestionOption, ResolvedModel, RunAgentOptions, SdkErrorCode, SdkSkillsOptions, SdkToolSet, SdkToolsOptions, SdkToolsetRef, SequentialToolHandler, SequentialToolResult, SessionEventSource, SessionRecord, SessionRecordMeta, SessionStore, SessionStoreCommitMeta, SessionStoreCreateInit, SessionView, SessionViewDeliveryOptions, SessionViewOptions, SessionViewReducerState, SessionViewSource, SessionViewState, SessionViewStatus, SetModelBinding, SkillsFileSystem, TansrConfig, TerminalReason, TextDeliveryMode, ThinkingDeliveryMode, TodoView, Tool, ToolCallPartStatus, ToolCallView, ToolContext, ToolErrorType, ToolExecutionContext, ToolExecutionOutcome, ToolExecutor, ToolExecutorYield, ToolParameterSpec, ToolResult, ToolResultContent, UIMessage, UIMessagePart, UITextPart, UIThinkingPart, UIToolCallPart, UsageView, VideoGenArgs, VideoGenData, VideoModelConstraints, Visibility };
package/dist/index.js CHANGED
@@ -4926,6 +4926,16 @@ var DEFAULT_MICROCOMPACT_MARGIN = 4e4;
4926
4926
  var MICROCOMPACT_RECOVERY_FLOOR_MIN = 2e4;
4927
4927
  var MICROCOMPACT_RECOVERY_FLOOR_RATIO = 0.1;
4928
4928
  var MICROCOMPACT_RECOVERY_FLOOR_MAX_FRACTION = 0.5;
4929
+ var MICROCOMPACT_RECOVERY_FLOOR_RATIO_TIERS = [
4930
+ { minContextWindow: 5e5, ratio: 0.15 },
4931
+ { minContextWindow: 0, ratio: MICROCOMPACT_RECOVERY_FLOOR_RATIO }
4932
+ ];
4933
+ function microcompactRecoveryFloorRatio(contextWindow) {
4934
+ for (const tier of MICROCOMPACT_RECOVERY_FLOOR_RATIO_TIERS) {
4935
+ if (contextWindow >= tier.minContextWindow) return tier.ratio;
4936
+ }
4937
+ return MICROCOMPACT_RECOVERY_FLOOR_RATIO;
4938
+ }
4929
4939
  var DEFAULT_AUTO_COMPACT_RATIO = 0.93;
4930
4940
  var MIN_CONTEXT_WINDOW = 1024;
4931
4941
  var ADAPTIVE_MAX_DEPTH_FRACTION = 0.75;
@@ -4958,9 +4968,12 @@ function linesHealthy(lines, contextWindow) {
4958
4968
  function clampLine(value, lo, hi) {
4959
4969
  return Math.min(hi, Math.max(lo, value));
4960
4970
  }
4961
- function deriveMicrocompactStopAt(microcompactAt, floorKnob) {
4971
+ function deriveMicrocompactStopAt(microcompactAt, floorKnob, contextWindow) {
4962
4972
  const floor = floorKnob ?? Math.min(
4963
- Math.max(MICROCOMPACT_RECOVERY_FLOOR_MIN, Math.floor(microcompactAt * MICROCOMPACT_RECOVERY_FLOOR_RATIO)),
4973
+ Math.max(
4974
+ MICROCOMPACT_RECOVERY_FLOOR_MIN,
4975
+ Math.floor(microcompactAt * microcompactRecoveryFloorRatio(contextWindow))
4976
+ ),
4964
4977
  Math.floor(microcompactAt * MICROCOMPACT_RECOVERY_FLOOR_MAX_FRACTION)
4965
4978
  );
4966
4979
  return Math.max(0, microcompactAt - Math.floor(floor));
@@ -5030,7 +5043,11 @@ function resolveThresholds(config) {
5030
5043
  warningAt: legacy.warningAt,
5031
5044
  blockingAt: legacy.blockingAt,
5032
5045
  microcompactAt: legacy.microcompactAt,
5033
- microcompactStopAt: deriveMicrocompactStopAt(legacy.microcompactAt, recoveryFloorKnob),
5046
+ microcompactStopAt: deriveMicrocompactStopAt(
5047
+ legacy.microcompactAt,
5048
+ recoveryFloorKnob,
5049
+ config.contextWindow
5050
+ ),
5034
5051
  compactOutputBudget
5035
5052
  };
5036
5053
  }
@@ -5063,7 +5080,7 @@ function resolveThresholds(config) {
5063
5080
  microcompactAt,
5064
5081
  // B1 停止线自最终触发线派生(自适应/钳制后的 microcompactAt;比例项使
5065
5082
  // 病态小窗口的下探幅度与触发线同尺度,恒不清穿)
5066
- microcompactStopAt: deriveMicrocompactStopAt(microcompactAt, recoveryFloorKnob),
5083
+ microcompactStopAt: deriveMicrocompactStopAt(microcompactAt, recoveryFloorKnob, config.contextWindow),
5067
5084
  // 预留区被降级时压缩输出预算同步收窄(摘要必须装得进降级后的预留区;
5068
5085
  // 未降级时原样保留)
5069
5086
  compactOutputBudget: scale < 1 ? Math.min(compactOutputBudget, Math.max(1, scaledReserve)) : compactOutputBudget,
@@ -8505,8 +8522,11 @@ ${decision.referenceText}
8505
8522
  // 不可得(上方两径均未测量)或 <1 时省略,零漂移
8506
8523
  ...promptTokensEstimate !== void 0 && Math.ceil(promptTokensEstimate) >= 1 ? { promptTokensEstimate: Math.ceil(promptTokensEstimate) } : {},
8507
8524
  // TM-8:一次性辅助查询(记忆提取 fork 等)抑制消息尾缓存断点
8508
- // (RFC-OPT14-1 同族;缺省不落键,主查询请求形状零漂移)
8509
- ...options.skipCacheWrite === true ? { skipCacheWrite: true } : {}
8525
+ // (RFC-OPT14-1 同族;缺省不落键,主查询请求形状零漂移)
8526
+ // doc/110 A3:收尾轮(closingTurnArmed)为可知末轮,调用方经
8527
+ // closingTurn.skipCacheWrite 声明历史不复读时同跳(仅收尾请求;
8528
+ // 非末轮恒不跳)。
8529
+ ...options.skipCacheWrite === true || closingTurnArmed && options.closingTurn?.skipCacheWrite === true ? { skipCacheWrite: true } : {}
8510
8530
  };
8511
8531
  if (options.onModelRequest !== void 0) {
8512
8532
  try {
@@ -13848,6 +13868,26 @@ function lockFilePath(sessionDir) {
13848
13868
  return path5.join(sessionDir, "lock");
13849
13869
  }
13850
13870
  var durableTmpSeq = 0;
13871
+ var RENAME_TRANSIENT_CODES = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
13872
+ var RENAME_RETRY_DELAYS_MS = [5, 10, 20, 40, 80, 160, 320];
13873
+ var defaultRenameDeps = {
13874
+ rename,
13875
+ sleep: (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)),
13876
+ platform: process.platform
13877
+ };
13878
+ async function renameWithRetry(from, to, deps = defaultRenameDeps) {
13879
+ for (let attempt = 0; ; attempt++) {
13880
+ try {
13881
+ await deps.rename(from, to);
13882
+ return;
13883
+ } catch (err) {
13884
+ const delay = RENAME_RETRY_DELAYS_MS[attempt];
13885
+ const transient = deps.platform === "win32" && isErrnoException(err) && err.code !== void 0 && RENAME_TRANSIENT_CODES.has(err.code);
13886
+ if (!transient || delay === void 0) throw err;
13887
+ await deps.sleep(delay);
13888
+ }
13889
+ }
13890
+ }
13851
13891
  async function writeFileDurable(filePath, content) {
13852
13892
  durableTmpSeq += 1;
13853
13893
  const tempPath = `${filePath}.tmp-${process.pid}-${durableTmpSeq.toString(36)}-${Date.now()}`;
@@ -13863,7 +13903,7 @@ async function writeFileDurable(filePath, content) {
13863
13903
  await handle.close();
13864
13904
  }
13865
13905
  try {
13866
- await rename(tempPath, filePath);
13906
+ await renameWithRetry(tempPath, filePath);
13867
13907
  } catch (err) {
13868
13908
  await rm(tempPath, { force: true }).catch(() => void 0);
13869
13909
  throw err;
@@ -19303,8 +19343,10 @@ async function runSubagent(options) {
19303
19343
  initialMessages: [{ role: "user", blocks: [{ t: "text", text: options.prompt }] }],
19304
19344
  maxTurns,
19305
19345
  // max_turns 优雅化:预算触顶且仍在干活时追加恰一次强制收束调用
19306
- // (有效轮数 = maxTurns + 1;语义见模块头注释与 RunQueryOptions.closingTurn)
19307
- closingTurn: { instruction: SUBAGENT_CLOSING_TURN_INSTRUCTION },
19346
+ // (有效轮数 = maxTurns + 1;语义见模块头注释与 RunQueryOptions.closingTurn)
19347
+ // doc/110 A3:收尾轮是可知末轮且子代理历史随终局丢弃(只回传摘要),
19348
+ // 尾断点写纯付费 → 收尾请求跳写;非末轮恒不跳(逐轮尾写/次轮读是正常增量)
19349
+ closingTurn: { instruction: SUBAGENT_CLOSING_TURN_INSTRUCTION, skipCacheWrite: true },
19308
19350
  // TC-T1:阈值预警注入(剩 3 轮减速带 / 剩 1 轮最后工作轮;各恰一次,
19309
19351
  // 与收尾轮构成三级带)——恒注入,与 closingTurn 同一零配置纪律
19310
19352
  reminders: createTurnBudgetReminderProvider(maxTurns),
@@ -24755,6 +24797,9 @@ async function loadConfig(options = {}) {
24755
24797
  // ../kernel/src/cost/money.ts
24756
24798
  var MAX_SAFE_NANO = Number.MAX_SAFE_INTEGER;
24757
24799
 
24800
+ // ../kernel/src/cost/pricing-table.ts
24801
+ var PRICING_CURRENCIES = ["USD", "CNY"];
24802
+
24758
24803
  // ../kernel/src/skills/frontmatter.ts
24759
24804
  function stripBom2(text) {
24760
24805
  return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
@@ -31078,6 +31123,9 @@ function imageModelNote(m) {
31078
31123
  if (!c.seed) notes.push("no seed");
31079
31124
  if (!c.negativePrompt) notes.push("no negativePrompt");
31080
31125
  if (c.maxImages === 1) notes.push("single image per call (n=1)");
31126
+ if (m.outputHosting === "overseas") {
31127
+ notes.push("output hosted OVERSEAS — image URLs may be unreachable from mainland China networks");
31128
+ }
31081
31129
  return notes.length > 0 ? `${label} [${notes.join("; ")}]` : label;
31082
31130
  }
31083
31131
  function authorizedModelsNote(models) {
@@ -31305,6 +31353,9 @@ function videoModelNote(m) {
31305
31353
  else if (c.ratio !== void 0) notes.push(`ratio ${c.ratio.join("|")}`);
31306
31354
  if (!c.seed) notes.push("no seed");
31307
31355
  if (!c.negativePrompt) notes.push("no negativePrompt");
31356
+ if (m.outputHosting === "overseas") {
31357
+ notes.push("output hosted OVERSEAS — the video URL may be unreachable from mainland China networks");
31358
+ }
31308
31359
  return `${label} [${notes.join("; ")}]`;
31309
31360
  }
31310
31361
  function authorizedModelsNote2(models) {
@@ -31876,6 +31927,19 @@ var APP_TOKEN_PLACEHOLDER_VALUE = "app-token-tier";
31876
31927
  function isRecord8(value) {
31877
31928
  return typeof value === "object" && value !== null && !Array.isArray(value);
31878
31929
  }
31930
+ function parsePricing(raw) {
31931
+ if (!isRecord8(raw)) return null;
31932
+ if (typeof raw.currency !== "string" || typeof raw.inPerMillion !== "string" || typeof raw.outPerMillion !== "string") {
31933
+ return null;
31934
+ }
31935
+ return {
31936
+ currency: raw.currency,
31937
+ inPerMillion: raw.inPerMillion,
31938
+ outPerMillion: raw.outPerMillion,
31939
+ cacheReadPerMillion: typeof raw.cacheReadPerMillion === "string" ? raw.cacheReadPerMillion : "0",
31940
+ cacheWritePerMillion: typeof raw.cacheWritePerMillion === "string" ? raw.cacheWritePerMillion : "0"
31941
+ };
31942
+ }
31879
31943
  function parseModel(raw) {
31880
31944
  if (!isRecord8(raw)) return null;
31881
31945
  if (typeof raw.handle !== "string" || raw.handle === "" || typeof raw.modelId !== "string" || raw.modelId === "" || typeof raw.protocol !== "string") {
@@ -31890,9 +31954,36 @@ function parseModel(raw) {
31890
31954
  family: typeof raw.family === "string" && raw.family !== "" ? raw.family : null,
31891
31955
  protocol: raw.protocol,
31892
31956
  capabilities: isRecord8(raw.capabilities) ? raw.capabilities : {},
31893
- contextWindow: typeof raw.contextWindow === "number" ? raw.contextWindow : null
31957
+ contextWindow: typeof raw.contextWindow === "number" ? raw.contextWindow : null,
31958
+ pricing: parsePricing(raw.pricing)
31894
31959
  };
31895
31960
  }
31961
+ function appBundlePricingUpdates(bundle) {
31962
+ const updates = [];
31963
+ for (const model of bundle.models) {
31964
+ const pricing = model.pricing;
31965
+ if (pricing === null) continue;
31966
+ if (!PRICING_CURRENCIES.includes(pricing.currency)) continue;
31967
+ const input = Number(pricing.inPerMillion);
31968
+ const output = Number(pricing.outPerMillion);
31969
+ if (!Number.isFinite(input) || !Number.isFinite(output)) continue;
31970
+ const cached = Number(pricing.cacheReadPerMillion);
31971
+ const cacheWrite = Number(pricing.cacheWritePerMillion);
31972
+ updates.push({
31973
+ providerId: TANSR_PROVIDER_ID,
31974
+ modelName: model.handle,
31975
+ currency: pricing.currency,
31976
+ pricing: {
31977
+ inputPerMillion: input,
31978
+ outputPerMillion: output,
31979
+ ...Number.isFinite(cached) && cached > 0 ? { cachedInputPerMillion: cached } : {},
31980
+ ...Number.isFinite(cacheWrite) && cacheWrite > 0 ? { cacheWriteInputPerMillion: cacheWrite } : {}
31981
+ },
31982
+ note: "app bundle"
31983
+ });
31984
+ }
31985
+ return updates;
31986
+ }
31896
31987
  function parseMediaImageInput(raw, flagKey) {
31897
31988
  if (raw === null) return null;
31898
31989
  if (!isRecord8(raw)) return false;
@@ -31955,10 +32046,12 @@ function parseMediaModels(raw, parseConstraints) {
31955
32046
  for (const item of raw) {
31956
32047
  if (!isRecord8(item) || typeof item.model !== "string" || item.model === "") continue;
31957
32048
  const constraints = item.constraints === void 0 ? void 0 : parseConstraints(item.constraints);
32049
+ const hosting = item.outputHosting === "domestic" || item.outputHosting === "overseas" || item.outputHosting === "inline" ? item.outputHosting : void 0;
31958
32050
  out.push({
31959
32051
  model: item.model,
31960
32052
  displayName: typeof item.displayName === "string" && item.displayName !== "" ? item.displayName : item.model,
31961
- ...constraints !== void 0 ? { constraints } : {}
32053
+ ...constraints !== void 0 ? { constraints } : {},
32054
+ ...hosting !== void 0 ? { outputHosting: hosting } : {}
31962
32055
  });
31963
32056
  }
31964
32057
  return out;
@@ -32163,7 +32256,13 @@ async function assemblePlatformModel(options) {
32163
32256
  }
32164
32257
  });
32165
32258
  const built = buildClientFromRegistry(registry, options.model ?? "main", options.onProviderSelected);
32166
- return { ...built, registry, capabilities: bundle.capabilities, platformModels: bundle.platformModels };
32259
+ return {
32260
+ ...built,
32261
+ registry,
32262
+ capabilities: bundle.capabilities,
32263
+ platformModels: bundle.platformModels,
32264
+ pricingUpdates: appBundlePricingUpdates(bundle)
32265
+ };
32167
32266
  }
32168
32267
 
32169
32268
  // src/task.ts
@@ -32408,39 +32507,64 @@ function repairHistoryPairing2(messages) {
32408
32507
 
32409
32508
  // src/session.ts
32410
32509
  function createEventQueue() {
32411
- const buffered = [];
32510
+ const log = [];
32511
+ let head = 0;
32412
32512
  let ended = false;
32413
- let wake = null;
32414
- const notify = () => {
32415
- if (wake !== null) {
32416
- const w = wake;
32417
- wake = null;
32418
- w();
32513
+ let liveStarted = false;
32514
+ const subscribers = /* @__PURE__ */ new Set();
32515
+ const wakeAll = () => {
32516
+ for (const s of subscribers) {
32517
+ if (s.wake !== null) {
32518
+ const w = s.wake;
32519
+ s.wake = null;
32520
+ w();
32521
+ }
32522
+ }
32523
+ };
32524
+ const trim = () => {
32525
+ if (!liveStarted || subscribers.size === 0) return;
32526
+ let min = Number.POSITIVE_INFINITY;
32527
+ for (const s of subscribers) min = Math.min(min, s.cursor);
32528
+ const drop = min - head;
32529
+ if (drop > 0) {
32530
+ log.splice(0, drop);
32531
+ head = min;
32419
32532
  }
32420
32533
  };
32421
32534
  return {
32422
32535
  push(item) {
32423
32536
  if (ended) return;
32424
- buffered.push(item);
32425
- notify();
32537
+ if (subscribers.size > 0) liveStarted = true;
32538
+ log.push(item);
32539
+ wakeAll();
32426
32540
  },
32427
32541
  end() {
32428
32542
  ended = true;
32429
- notify();
32543
+ wakeAll();
32430
32544
  },
32431
32545
  get ended() {
32432
32546
  return ended;
32433
32547
  },
32434
32548
  iterable: {
32435
32549
  async *[Symbol.asyncIterator]() {
32436
- for (; ; ) {
32437
- while (buffered.length > 0) {
32438
- yield buffered.shift();
32550
+ const me = { cursor: liveStarted ? head + log.length : head, wake: null };
32551
+ subscribers.add(me);
32552
+ try {
32553
+ for (; ; ) {
32554
+ while (me.cursor < head + log.length) {
32555
+ const item = log[me.cursor - head];
32556
+ me.cursor += 1;
32557
+ trim();
32558
+ yield item;
32559
+ }
32560
+ if (ended) return;
32561
+ await new Promise((resolve2) => {
32562
+ me.wake = resolve2;
32563
+ });
32439
32564
  }
32440
- if (ended) return;
32441
- await new Promise((resolve2) => {
32442
- wake = resolve2;
32443
- });
32565
+ } finally {
32566
+ subscribers.delete(me);
32567
+ trim();
32444
32568
  }
32445
32569
  }
32446
32570
  }
@@ -32489,8 +32613,10 @@ var AgentSession = class {
32489
32613
  return this.#sessionId;
32490
32614
  }
32491
32615
  /**
32492
- * 会话事件流(async iterable;单消费者)。跨轮连续,close() 后以
32493
- * session.ended 收尾并正常终结(for-await 自然退出)。
32616
+ * 会话事件流(async iterable;**多消费者广播**,2026-09-02 起)。每次 for-await 即一个
32617
+ * 独立订阅者:SessionView 泵、Narrator、宿主自建循环可同时挂,各得全量事件、互不争抢;
32618
+ * 首订阅者收到会话创建以来的积压,晚订阅者自订阅点起。跨轮连续,close() 后以
32619
+ * session.ended 收尾并正常终结(各订阅者排空后 for-await 自然退出)。
32494
32620
  */
32495
32621
  get events() {
32496
32622
  return this.#queue.iterable;
@@ -32724,6 +32850,7 @@ async function createSession(options = {}) {
32724
32850
  }
32725
32851
  validateTokenTierOptions("createSession", options);
32726
32852
  let initialMessages = options.initialMessages ?? [];
32853
+ let storedPlatformSessionId;
32727
32854
  if (options.resume !== void 0) {
32728
32855
  const record = await options.resume.store.get(options.resume.sessionId);
32729
32856
  if (record === null) {
@@ -32733,8 +32860,9 @@ async function createSession(options = {}) {
32733
32860
  );
32734
32861
  }
32735
32862
  initialMessages = repairHistoryPairing2(record.messages).messages;
32863
+ storedPlatformSessionId = record.meta.platformSessionId;
32736
32864
  }
32737
- const platformSessionId = tokenTier ? ulid() : void 0;
32865
+ const platformSessionId = tokenTier ? storedPlatformSessionId ?? ulid() : void 0;
32738
32866
  let sessionRef = null;
32739
32867
  const emitBody = (body, source) => {
32740
32868
  sessionRef?.pushBody(body, source);
@@ -34159,6 +34287,7 @@ export {
34159
34287
  VIDEOGEN_TOOL_TIMEOUT_MS,
34160
34288
  VideoGenArgsSchema,
34161
34289
  accumulateUsage,
34290
+ appBundlePricingUpdates,
34162
34291
  appBundleRegistryConfig,
34163
34292
  appendUserMessage,
34164
34293
  assembleManagedModel,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tansr/sdk",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Tansr public TypeScript SDK: headless agent API (query / createSession / runAgent) + pure protocol type re-exports (public, MIT).",
5
5
  "license": "MIT",
6
6
  "type": "module",