@tansr/sdk 0.9.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 加法键,
@@ -15634,6 +15709,15 @@ declare const TANSR_PROVIDER_ID = "tansr";
15634
15709
  * 真实鉴权头由 createAppTokenFetch 包装覆写,令牌恒不进 registry env)。
15635
15710
  */
15636
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[];
15637
15721
  /**
15638
15722
  * bundle 载荷 → SDK 消费子集。顶层形状非法返回 null(调用方结构化报错);
15639
15723
  * 条目级损坏逐条跳过。capabilities 段严格校验,失败回落平台缺省档
@@ -15935,6 +16019,13 @@ interface AssembledPlatformModel {
15935
16019
  * 集成方零手配)。旧 api 无段 = 双空集如实。
15936
16020
  */
15937
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[];
15938
16029
  }
15939
16030
  /**
15940
16031
  * 令牌头注入 fetch 包装:剥 AK/SK 双头与签名三头(值只是占位哑值,但
@@ -16066,6 +16157,8 @@ interface SessionRecordMeta {
16066
16157
  * 平台会话 id(ULID 26 位 Crockford;doc/91 拍板⑤):令牌档 createSession
16067
16158
  * per-AgentSession 铸造并经 twp meta.sessionId 出线,ULID↔内核 UUID 映射
16068
16159
  * 落在此键——平台侧会话行(归因/续租/亲和)与本地记录互认的桥。
16160
+ * doc/110 B2(2026-09-02 翻案拍板⑤实施语义):resume 径**沿用**此键——
16161
+ * 缓存键/粘性/归因跨 resume 延续;旧记录无键时 resume 铸新并补录。
16069
16162
  */
16070
16163
  platformSessionId?: string;
16071
16164
  /** 开发者自留元数据域(SDK 恒不消费其内容) */
@@ -16075,7 +16168,10 @@ interface SessionRecordMeta {
16075
16168
  interface SessionStoreCreateInit {
16076
16169
  sessionId?: string;
16077
16170
  title?: string;
16078
- /** 平台会话 ULID(令牌档装配注入;重复登记时以新值对账更新) */
16171
+ /**
16172
+ * 平台会话 ULID(令牌档装配注入;重复登记时以新值对账更新——doc/110 B2
16173
+ * 起 resume 恒沿用已存值,故在场值只会是同值或旧记录无键的首次补录)
16174
+ */
16079
16175
  platformSessionId?: string;
16080
16176
  meta?: Record<string, unknown>;
16081
16177
  }
@@ -16100,7 +16196,8 @@ interface SessionRecord {
16100
16196
  * 验收:改坏存储文件须报错不静默);
16101
16197
  * - list 恒不携消息内容(枚举是元数据面);
16102
16198
  * - create 幂等(同 sessionId 重复登记返回既有记录,platformSessionId
16103
- * 以新值对账更新——resume 后的新 AgentSession 铸新平台 ULID 经此落位)。
16199
+ * 以新值对账更新——doc/110 B2:resume 后的 AgentSession **沿用**记录已存
16200
+ * 平台 ULID,本对账写只在旧记录无键(2026-09-02 前落盘)时补录新铸值)。
16104
16201
  */
16105
16202
  interface SessionStore {
16106
16203
  /** 建会话(登记 meta;id 由 store 铸造或调用方供给;幂等) */
@@ -16288,8 +16385,10 @@ declare class AgentSession {
16288
16385
  constructor(init: AgentSessionInit);
16289
16386
  get sessionId(): string;
16290
16387
  /**
16291
- * 会话事件流(async iterable;单消费者)。跨轮连续,close() 后以
16292
- * session.ended 收尾并正常终结(for-await 自然退出)。
16388
+ * 会话事件流(async iterable;**多消费者广播**,2026-09-02 起)。每次 for-await 即一个
16389
+ * 独立订阅者:SessionView 泵、Narrator、宿主自建循环可同时挂,各得全量事件、互不争抢;
16390
+ * 首订阅者收到会话创建以来的积压,晚订阅者自订阅点起。跨轮连续,close() 后以
16391
+ * session.ended 收尾并正常终结(各订阅者排空后 for-await 自然退出)。
16293
16392
  */
16294
16393
  get events(): AsyncIterable<KernelEvent>;
16295
16394
  /** 当前模型档快照 */
@@ -16631,8 +16730,9 @@ declare function viewStateFromHistory(messages: readonly IRMessage[], options?:
16631
16730
  * - AsyncIterable<KernelEvent>:直接消费;
16632
16731
  * - { events: AsyncIterable<KernelEvent> }(AgentSession 形):消费 .events。
16633
16732
  *
16634
- * 注意:AgentSession 事件流是单消费者队列——同一会话上同时挂 SessionView
16635
- * 与 Narrator(或宿主自身的 for-await)需要调用方自行扇出事件。
16733
+ * 2026-09-02 起 AgentSession.events 系多消费者广播(每次 for-await 一个独立订阅者):
16734
+ * 同一会话上同时挂 SessionView 与 Narrator(或宿主自身的 for-await)恒不再需要扇出;
16735
+ * 本泵直接消费 session.events 即可(旧 fanout 写法仍兼容——多一层无害)。
16636
16736
  *
16637
16737
  * dispose 停泵:置标志 + best-effort 调用迭代器 return()(async generator
16638
16738
  * 的 finally 释放上游);已挂起的 next() 由 return 排队语义收口。
@@ -16962,5 +17062,5 @@ declare function attachSdkTaskTool(toolset: SdkToolsetRef, config: AttachSdkTask
16962
17062
  */
16963
17063
  declare function subagentModelResolverOf(registry: ProviderRegistry | null): SubagentModelResolver | undefined;
16964
17064
 
16965
- 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 };
16966
- 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;
@@ -31882,6 +31927,19 @@ var APP_TOKEN_PLACEHOLDER_VALUE = "app-token-tier";
31882
31927
  function isRecord8(value) {
31883
31928
  return typeof value === "object" && value !== null && !Array.isArray(value);
31884
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
+ }
31885
31943
  function parseModel(raw) {
31886
31944
  if (!isRecord8(raw)) return null;
31887
31945
  if (typeof raw.handle !== "string" || raw.handle === "" || typeof raw.modelId !== "string" || raw.modelId === "" || typeof raw.protocol !== "string") {
@@ -31896,9 +31954,36 @@ function parseModel(raw) {
31896
31954
  family: typeof raw.family === "string" && raw.family !== "" ? raw.family : null,
31897
31955
  protocol: raw.protocol,
31898
31956
  capabilities: isRecord8(raw.capabilities) ? raw.capabilities : {},
31899
- contextWindow: typeof raw.contextWindow === "number" ? raw.contextWindow : null
31957
+ contextWindow: typeof raw.contextWindow === "number" ? raw.contextWindow : null,
31958
+ pricing: parsePricing(raw.pricing)
31900
31959
  };
31901
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
+ }
31902
31987
  function parseMediaImageInput(raw, flagKey) {
31903
31988
  if (raw === null) return null;
31904
31989
  if (!isRecord8(raw)) return false;
@@ -32171,7 +32256,13 @@ async function assemblePlatformModel(options) {
32171
32256
  }
32172
32257
  });
32173
32258
  const built = buildClientFromRegistry(registry, options.model ?? "main", options.onProviderSelected);
32174
- 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
+ };
32175
32266
  }
32176
32267
 
32177
32268
  // src/task.ts
@@ -32416,39 +32507,64 @@ function repairHistoryPairing2(messages) {
32416
32507
 
32417
32508
  // src/session.ts
32418
32509
  function createEventQueue() {
32419
- const buffered = [];
32510
+ const log = [];
32511
+ let head = 0;
32420
32512
  let ended = false;
32421
- let wake = null;
32422
- const notify = () => {
32423
- if (wake !== null) {
32424
- const w = wake;
32425
- wake = null;
32426
- 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;
32427
32532
  }
32428
32533
  };
32429
32534
  return {
32430
32535
  push(item) {
32431
32536
  if (ended) return;
32432
- buffered.push(item);
32433
- notify();
32537
+ if (subscribers.size > 0) liveStarted = true;
32538
+ log.push(item);
32539
+ wakeAll();
32434
32540
  },
32435
32541
  end() {
32436
32542
  ended = true;
32437
- notify();
32543
+ wakeAll();
32438
32544
  },
32439
32545
  get ended() {
32440
32546
  return ended;
32441
32547
  },
32442
32548
  iterable: {
32443
32549
  async *[Symbol.asyncIterator]() {
32444
- for (; ; ) {
32445
- while (buffered.length > 0) {
32446
- 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
+ });
32447
32564
  }
32448
- if (ended) return;
32449
- await new Promise((resolve2) => {
32450
- wake = resolve2;
32451
- });
32565
+ } finally {
32566
+ subscribers.delete(me);
32567
+ trim();
32452
32568
  }
32453
32569
  }
32454
32570
  }
@@ -32497,8 +32613,10 @@ var AgentSession = class {
32497
32613
  return this.#sessionId;
32498
32614
  }
32499
32615
  /**
32500
- * 会话事件流(async iterable;单消费者)。跨轮连续,close() 后以
32501
- * session.ended 收尾并正常终结(for-await 自然退出)。
32616
+ * 会话事件流(async iterable;**多消费者广播**,2026-09-02 起)。每次 for-await 即一个
32617
+ * 独立订阅者:SessionView 泵、Narrator、宿主自建循环可同时挂,各得全量事件、互不争抢;
32618
+ * 首订阅者收到会话创建以来的积压,晚订阅者自订阅点起。跨轮连续,close() 后以
32619
+ * session.ended 收尾并正常终结(各订阅者排空后 for-await 自然退出)。
32502
32620
  */
32503
32621
  get events() {
32504
32622
  return this.#queue.iterable;
@@ -32732,6 +32850,7 @@ async function createSession(options = {}) {
32732
32850
  }
32733
32851
  validateTokenTierOptions("createSession", options);
32734
32852
  let initialMessages = options.initialMessages ?? [];
32853
+ let storedPlatformSessionId;
32735
32854
  if (options.resume !== void 0) {
32736
32855
  const record = await options.resume.store.get(options.resume.sessionId);
32737
32856
  if (record === null) {
@@ -32741,8 +32860,9 @@ async function createSession(options = {}) {
32741
32860
  );
32742
32861
  }
32743
32862
  initialMessages = repairHistoryPairing2(record.messages).messages;
32863
+ storedPlatformSessionId = record.meta.platformSessionId;
32744
32864
  }
32745
- const platformSessionId = tokenTier ? ulid() : void 0;
32865
+ const platformSessionId = tokenTier ? storedPlatformSessionId ?? ulid() : void 0;
32746
32866
  let sessionRef = null;
32747
32867
  const emitBody = (body, source) => {
32748
32868
  sessionRef?.pushBody(body, source);
@@ -34167,6 +34287,7 @@ export {
34167
34287
  VIDEOGEN_TOOL_TIMEOUT_MS,
34168
34288
  VideoGenArgsSchema,
34169
34289
  accumulateUsage,
34290
+ appBundlePricingUpdates,
34170
34291
  appBundleRegistryConfig,
34171
34292
  appendUserMessage,
34172
34293
  assembleManagedModel,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tansr/sdk",
3
- "version": "0.9.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",