@tansr/sdk 0.1.0 → 0.2.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
@@ -15503,9 +15503,8 @@ interface SdkToolsOptions {
15503
15503
  builtin?: readonly string[];
15504
15504
  /**
15505
15505
  * 环3 平台能力选择(词表:imageGen/videoGen/webSearch)。位关恒 fail-fast;
15506
- * S-E1/S-F 起 imageGen/videoGen 位开即装配平台工具客户端(ImageGen/VideoGen,
15507
- * 材料 = 令牌档 platformContext,托管/注入档选择即可读错);webSearch 仍只
15508
- * 校验位(客户端候后续卡,位开静默不装)。
15506
+ * 位开即装配平台工具客户端(ImageGen/VideoGen/PlatformWebSearch,材料 =
15507
+ * 令牌档 platformContext,托管/注入档选择即可读错)
15509
15508
  */
15510
15509
  platform?: readonly string[];
15511
15510
  /** 环1 自定义工具(defineTool 产物;kernel Tool 形态直给亦可) */
@@ -15550,8 +15549,7 @@ declare function resolveBuiltinSelection(selection: readonly string[] | undefine
15550
15549
  /**
15551
15550
  * platform 选择集解出(校验 + 装配序):未知名/位关恒 fail-fast 可读错;
15552
15551
  * 返回按 PLATFORM_NAMES 固定序去重的选择集(prompt 前缀稳定,builtin 同律)。
15553
- * S-E1/S-F 起 imageGen/videoGen 进装配径(工具客户端);webSearch 位开静默
15554
- * 不装(客户端候后续卡,语义与旧 validate-only 一致)。
15552
+ * 三位(imageGen/videoGen/webSearch)全进装配径(工具客户端)
15555
15553
  */
15556
15554
  declare function resolvePlatformSelection(selection: readonly string[] | undefined, capabilities: AppCapabilities): PlatformCapabilityName[];
15557
15555
  /** guide 段的语义标签(IRSystemSegment.label;skills 索引段同款纪律) */
@@ -16397,6 +16395,74 @@ interface CreateVideoGenToolOptions {
16397
16395
  */
16398
16396
  declare function createVideoGenTool(options: CreateVideoGenToolOptions): Tool<VideoGenArgs>;
16399
16397
 
16398
+ /**
16399
+ * S-WS — WebSearch 环3 平台工具客户端(imagegen/videogen-tool.ts 同构镜像;
16400
+ * doc/84 §4.2 平台托管能力;用户拍板 2026-08-30「webSearch 补打通」)。
16401
+ *
16402
+ * 环3 语义:执行不在终端本地——工具 execute 经令牌档 fetch 打平台网关
16403
+ * POST {baseUrl}/t1/websearch(鉴权头 x-tansr-app-token),平台代调搜索
16404
+ * 供应商池(加权选池 + 一次故障转移),**按次计量计费归 App**(pricePerCall;
16405
+ * 开发者对终端如何转售自主,计量计费分离)。
16406
+ *
16407
+ * wire 契约(api 仓 TwpWebsearchRequest/Response,doc/36 §3.2):请求
16408
+ * {query, max_results?} 为 snake_case——与 CLI 内核 HTTP 搜索后端字节同构的
16409
+ * 既有特例(imagegen/videogen 的 camelCase 系 twp 核心纪律,本面迁就既有
16410
+ * 字节);响应 {results:[{title,url,snippet}]}(供应商方言已在网关归一)。
16411
+ *
16412
+ * 命名注记:kernel 环2 内置搜索工具已占名 'WebSearch'(终端本地 HTTP 后端,
16413
+ * tools.webSearch 位),本工具名取 'PlatformWebSearch' 与位名 platform.webSearch
16414
+ * 对齐——双位同开双选时两环并存,恒不注册表撞名。
16415
+ *
16416
+ * 装配面:tools.platform: ['webSearch'] 且 bundle 能力位 platform.webSearch=true
16417
+ * 时由 buildSdkToolSet 装配(位关 fail-fast 可读错);材料(baseUrl/token)
16418
+ * 来自会话令牌档——托管/注入档选择本工具恒 fail-fast 指引改用令牌档。
16419
+ *
16420
+ * 错误纪律(imagegen 同款):恒不 throw——网关错误信封归一为 isError 结构化
16421
+ * 结果(携错误码与修复指引),智能体可自纠不炸查询环;令牌本体只活在闭包
16422
+ * (INV-10 密钥纪律)。数据主权注记:查询文本平台侧恒不落日志不落库(网关
16423
+ * 红线),SDK 侧同样恒不打印。
16424
+ */
16425
+
16426
+ /** 结果数 wire 帽(与网关 TwpWebsearchRequestSchema 同值;供应商侧上限再截)。 */
16427
+ declare const WEBSEARCH_TOOL_MAX_RESULTS = 20;
16428
+ declare const WebSearchArgsSchema: z.ZodObject<{
16429
+ query: z.ZodEffects<z.ZodString, string, string>;
16430
+ max_results: z.ZodOptional<z.ZodNumber>;
16431
+ }, "strip", z.ZodTypeAny, {
16432
+ query: string;
16433
+ max_results?: number | undefined;
16434
+ }, {
16435
+ query: string;
16436
+ max_results?: number | undefined;
16437
+ }>;
16438
+ type WebSearchArgs = z.infer<typeof WebSearchArgsSchema>;
16439
+ /** 表面层渲染用结构化数据(ToolResult.data;错误时携错误码)。 */
16440
+ interface WebSearchData {
16441
+ query: string;
16442
+ results: Array<{
16443
+ title: string;
16444
+ url: string;
16445
+ snippet: string;
16446
+ }>;
16447
+ resultCount: number;
16448
+ /** 网关错误码(如 forbidden/websearch_not_configured/websearch_quota_exceeded;成功缺席)。 */
16449
+ errorCode?: string;
16450
+ }
16451
+ interface CreateWebSearchToolOptions {
16452
+ /** 平台 API 基址(令牌档会话档;/t1 前缀由本工具追加)。 */
16453
+ baseUrl: string;
16454
+ /** app_user 短期令牌(只活在本闭包,恒不进工具定义/日志)。 */
16455
+ token: string;
16456
+ /** fetch 注入缝(测试桩网关;缺省全局 fetch)。 */
16457
+ fetchImpl?: typeof fetch;
16458
+ }
16459
+ /**
16460
+ * 环3 平台联网搜索工具(kernel Tool 形态;name 'PlatformWebSearch',命名注记
16461
+ * 见文件头)。计费副作用真实存在(按次扣 App 余额)——恒不声明只读/并发安全
16462
+ * (ImageGen/VideoGen 同律保守档;权限规则可按名 gate)。
16463
+ */
16464
+ declare function createWebSearchTool(options: CreateWebSearchToolOptions): Tool<WebSearchArgs>;
16465
+
16400
16466
  /** bundle 内单模型条目(SDK 消费子集) */
16401
16467
  interface AppBundleModel {
16402
16468
  handle: string;
@@ -16461,5 +16527,5 @@ declare function attachSdkTaskTool(toolset: SdkToolsetRef, config: AttachSdkTask
16461
16527
  */
16462
16528
  declare function subagentModelResolverOf(registry: ProviderRegistry | null): SubagentModelResolver | undefined;
16463
16529
 
16464
- 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, ImageGenArgsSchema, McpHost, OUTPUT_TAIL_MAX_CHARS, QueueChannel, SequentialToolExecutor, TANSR_PROVIDER_ID, TOOL_GUIDE_LABEL, TansrSdkError, UnavailableChannel, VIDEOGEN_TOOL_MAX_DURATION, VideoGenArgsSchema, accumulateUsage, appBundleRegistryConfig, appendUserMessage, assembleManagedModel, assemblePlatformModel, assembleSdkSkills, assembleTooling, attachSdkMcp, attachSdkTaskTool, buildClientFromRegistry, buildSdkToolSet, buildToolGuideSegment, createAppTokenFetch, createImageGenTool, createMcpHost, createNarrator, createSdkPermissionGate, createSession, createSessionView, createVideoGenTool, defineSkill, defineTool, initialSessionViewState, markSourceFailure, parseAppBundle, providerSwitchedBody, query, reduceSessionView, resolveBuiltinSelection, resolveInitialMessages, resolvePlatformSelection, runAgent, subagentModelResolverOf, toToolDef };
16465
- export type { ActiveToolStatus, Answer, AppBundle, AppBundleModel, AppCapabilities, AppTokenRequest, AppTokenResponse, AskUserCallback, AssembleManagedModelOptions, AssemblePlatformModelOptions, AssembleToolingOptions, AssembledManagedModel, AssembledPlatformModel, AssembledSkills, AssembledTooling, AttachSdkTaskToolConfig, BuildSdkToolSetOptions, BuiltinToolName, Capability, CompactNowOptions, CompactNowResult, ConfigDiagnostic, CreateImageGenToolOptions, CreateSdkPermissionGateOptions, CreateSessionOptions, CreateVideoGenToolOptions, DecisionSource, DefineSkillOptions, DefineToolOptions, DefinedSkill, DefinedTool, ErrorView, EventBody, EventEnvelope, GateDecision, HookOutcomeStatus, IRBlock, IRErrorKind, IRMessage, IRRequest, IRRole, IRStreamEvent, IRSystemSegment, IRToolContent, IRToolDef, IRToolResultBlock, IRUsage, ImageGenArgs, ImageGenData, 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, Pricing, PromptCachingMode, PromptChannel, ProposedToolCall, ProtocolKind, ProviderProfile, QueryCompactionOptions, QueryCounters, QueryHandle, QueryOptions, QueryResult, Question, QuestionOption, ResolvedModel, RunAgentOptions, SdkErrorCode, SdkSkillsOptions, SdkToolSet, SdkToolsOptions, SdkToolsetRef, SequentialToolHandler, SequentialToolResult, SessionEventSource, SessionView, SessionViewReducerState, SessionViewSource, SessionViewState, SessionViewStatus, SetModelBinding, SkillsFileSystem, TansrConfig, TerminalReason, TodoView, Tool, ToolCallPartStatus, ToolCallView, ToolContext, ToolErrorType, ToolExecutionContext, ToolExecutionOutcome, ToolExecutor, ToolExecutorYield, ToolParameterSpec, ToolResult, ToolResultContent, UIMessage, UIMessagePart, UITextPart, UIThinkingPart, UIToolCallPart, UsageView, VideoGenArgs, VideoGenData, Visibility };
16530
+ 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, ImageGenArgsSchema, McpHost, OUTPUT_TAIL_MAX_CHARS, QueueChannel, SequentialToolExecutor, TANSR_PROVIDER_ID, TOOL_GUIDE_LABEL, TansrSdkError, UnavailableChannel, VIDEOGEN_TOOL_MAX_DURATION, VideoGenArgsSchema, WEBSEARCH_TOOL_MAX_RESULTS, WebSearchArgsSchema, accumulateUsage, appBundleRegistryConfig, appendUserMessage, assembleManagedModel, assemblePlatformModel, assembleSdkSkills, assembleTooling, attachSdkMcp, attachSdkTaskTool, buildClientFromRegistry, buildSdkToolSet, buildToolGuideSegment, createAppTokenFetch, createImageGenTool, createMcpHost, createNarrator, createSdkPermissionGate, createSession, createSessionView, createVideoGenTool, createWebSearchTool, defineSkill, defineTool, initialSessionViewState, markSourceFailure, parseAppBundle, providerSwitchedBody, query, reduceSessionView, resolveBuiltinSelection, resolveInitialMessages, resolvePlatformSelection, runAgent, subagentModelResolverOf, toToolDef };
16531
+ export type { ActiveToolStatus, Answer, AppBundle, AppBundleModel, AppCapabilities, AppTokenRequest, AppTokenResponse, AskUserCallback, AssembleManagedModelOptions, AssemblePlatformModelOptions, AssembleToolingOptions, AssembledManagedModel, AssembledPlatformModel, AssembledSkills, AssembledTooling, AttachSdkTaskToolConfig, BuildSdkToolSetOptions, BuiltinToolName, Capability, CompactNowOptions, CompactNowResult, ConfigDiagnostic, CreateImageGenToolOptions, CreateSdkPermissionGateOptions, CreateSessionOptions, CreateVideoGenToolOptions, CreateWebSearchToolOptions, DecisionSource, DefineSkillOptions, DefineToolOptions, DefinedSkill, DefinedTool, ErrorView, EventBody, EventEnvelope, GateDecision, HookOutcomeStatus, IRBlock, IRErrorKind, IRMessage, IRRequest, IRRole, IRStreamEvent, IRSystemSegment, IRToolContent, IRToolDef, IRToolResultBlock, IRUsage, ImageGenArgs, ImageGenData, 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, Pricing, PromptCachingMode, PromptChannel, ProposedToolCall, ProtocolKind, ProviderProfile, QueryCompactionOptions, QueryCounters, QueryHandle, QueryOptions, QueryResult, Question, QuestionOption, ResolvedModel, RunAgentOptions, SdkErrorCode, SdkSkillsOptions, SdkToolSet, SdkToolsOptions, SdkToolsetRef, SequentialToolHandler, SequentialToolResult, SessionEventSource, SessionView, SessionViewReducerState, SessionViewSource, SessionViewState, SessionViewStatus, SetModelBinding, SkillsFileSystem, TansrConfig, TerminalReason, TodoView, Tool, ToolCallPartStatus, ToolCallView, ToolContext, ToolErrorType, ToolExecutionContext, ToolExecutionOutcome, ToolExecutor, ToolExecutorYield, ToolParameterSpec, ToolResult, ToolResultContent, UIMessage, UIMessagePart, UITextPart, UIThinkingPart, UIToolCallPart, UsageView, VideoGenArgs, VideoGenData, Visibility, WebSearchArgs, WebSearchData };
package/dist/index.js CHANGED
@@ -30550,6 +30550,123 @@ function createVideoGenTool(options) {
30550
30550
  };
30551
30551
  }
30552
30552
 
30553
+ // src/platform/websearch-tool.ts
30554
+ import { z as z44 } from "zod";
30555
+ var WEBSEARCH_TOOL_MAX_RESULTS = 20;
30556
+ var WebSearchArgsSchema2 = z44.object({
30557
+ query: z44.string().max(1024).refine((s) => s.trim().length > 0, { message: "query must be a non-empty string" }).describe("Search query text (the platform never logs or stores it)."),
30558
+ max_results: z44.number().int().min(1).max(WEBSEARCH_TOOL_MAX_RESULTS).optional().describe(
30559
+ `Desired number of results (default 8, max ${WEBSEARCH_TOOL_MAX_RESULTS}; the provider may cap it lower). Billing is per call, not per result.`
30560
+ )
30561
+ });
30562
+ function errorResult15(text, query2, errorCode2) {
30563
+ const data = {
30564
+ query: query2,
30565
+ results: [],
30566
+ resultCount: 0,
30567
+ ...errorCode2 !== void 0 ? { errorCode: errorCode2 } : {}
30568
+ };
30569
+ return { content: [{ t: "text", text }], isError: true, data };
30570
+ }
30571
+ function hintOf3(code) {
30572
+ if (code === "forbidden") {
30573
+ return " The app platform capability webSearch is disabled; the app developer can enable it in console → app → capabilities.";
30574
+ }
30575
+ if (code === "websearch_not_configured") {
30576
+ return " Web search is not configured on this platform yet (no active search provider); tell the user instead of retrying.";
30577
+ }
30578
+ if (code === "websearch_quota_exceeded") {
30579
+ return " The daily web-search quota for this account is exhausted; retry after the daily reset (UTC+8).";
30580
+ }
30581
+ if (code === "rate_limited") {
30582
+ return " Too many requests right now; wait briefly before retrying.";
30583
+ }
30584
+ if (code === "insufficient_balance") {
30585
+ return " The app account balance is insufficient; the app developer needs to top up.";
30586
+ }
30587
+ if (code === "upstream_error") {
30588
+ return " All search providers failed for this request (nothing was billed); a later retry may succeed.";
30589
+ }
30590
+ return "";
30591
+ }
30592
+ function createWebSearchTool2(options) {
30593
+ const base = options.baseUrl.replace(/\/+$/, "");
30594
+ const fetchImpl = options.fetchImpl ?? fetch;
30595
+ const token = options.token;
30596
+ return {
30597
+ name: "PlatformWebSearch",
30598
+ description: "Searches the web via the tansr platform (ring-3 hosted capability; the platform calls a managed search provider pool and bills the app per call). Returns a numbered list of results with title, URL and snippet. Requires the app to have the webSearch platform capability enabled.",
30599
+ shortDescription: "Search the web via the tansr platform (billed per call). Args: query, max_results?.",
30600
+ inputSchema: WebSearchArgsSchema2,
30601
+ isReadOnly: false,
30602
+ isConcurrencySafe: false,
30603
+ async execute(args, ctx) {
30604
+ if (ctx.signal.aborted) {
30605
+ return errorResult15("Tool execution was aborted.", args.query);
30606
+ }
30607
+ const payload = {
30608
+ query: args.query,
30609
+ ...args.max_results !== void 0 ? { max_results: args.max_results } : {}
30610
+ };
30611
+ let response;
30612
+ try {
30613
+ response = await fetchImpl(`${base}/t1/websearch`, {
30614
+ method: "POST",
30615
+ headers: {
30616
+ "content-type": "application/json",
30617
+ accept: "application/json",
30618
+ [HEADER_APP_TOKEN]: token
30619
+ },
30620
+ body: JSON.stringify(payload),
30621
+ signal: ctx.signal
30622
+ });
30623
+ } catch (err) {
30624
+ if (ctx.signal.aborted) return errorResult15("Tool execution was aborted.", args.query);
30625
+ const message = err instanceof Error ? err.message : String(err);
30626
+ return errorResult15(`Web search request failed to reach the platform: ${message}`, args.query);
30627
+ }
30628
+ let raw = null;
30629
+ try {
30630
+ raw = await response.json();
30631
+ } catch {
30632
+ raw = null;
30633
+ }
30634
+ if (!response.ok) {
30635
+ const envelope = raw ?? {};
30636
+ const code = typeof envelope.error?.code === "string" ? envelope.error.code : `http_${response.status}`;
30637
+ const message = typeof envelope.error?.message === "string" ? envelope.error.message : "request rejected";
30638
+ return errorResult15(`Web search failed (${code}): ${message}.${hintOf3(code)}`, args.query, code);
30639
+ }
30640
+ const body = raw ?? {};
30641
+ if (!Array.isArray(body.results)) {
30642
+ return errorResult15("Web search returned an unexpected platform response (no results array).", args.query);
30643
+ }
30644
+ const results = body.results.map((item) => {
30645
+ const row = item ?? {};
30646
+ if (typeof row.title !== "string" || typeof row.url !== "string") return null;
30647
+ return {
30648
+ title: row.title,
30649
+ url: row.url,
30650
+ snippet: typeof row.snippet === "string" ? row.snippet : ""
30651
+ };
30652
+ }).filter((item) => item !== null);
30653
+ const data = { query: args.query, results, resultCount: results.length };
30654
+ if (results.length === 0) {
30655
+ return { content: [{ t: "text", text: "Web search returned no results for this query (the call was still billed)." }], data };
30656
+ }
30657
+ const lines = [
30658
+ `Web search returned ${results.length} result(s) (billed per call):`,
30659
+ ...results.map((item, i) => {
30660
+ const block = [`${i + 1}. ${item.title}`, ` ${item.url}`];
30661
+ if (item.snippet !== "") block.push(` ${item.snippet}`);
30662
+ return block.join("\n");
30663
+ })
30664
+ ];
30665
+ return { content: [{ t: "text", text: lines.join("\n") }], data };
30666
+ }
30667
+ };
30668
+ }
30669
+
30553
30670
  // src/toolset.ts
30554
30671
  var BUILTIN_ORDER = [
30555
30672
  "read",
@@ -30681,7 +30798,6 @@ function buildSdkToolSet(options = {}) {
30681
30798
  validateCustomSelection(selection.custom, capabilities);
30682
30799
  const platformTools = [];
30683
30800
  for (const name of platformNames) {
30684
- if (name !== "imageGen" && name !== "videoGen") continue;
30685
30801
  const pc = options.platformContext;
30686
30802
  if (pc === void 0) {
30687
30803
  throw new TansrSdkError(
@@ -30694,7 +30810,9 @@ function buildSdkToolSet(options = {}) {
30694
30810
  token: pc.token,
30695
30811
  ...pc.fetchImpl !== void 0 ? { fetchImpl: pc.fetchImpl } : {}
30696
30812
  };
30697
- platformTools.push(name === "imageGen" ? createImageGenTool(materials) : createVideoGenTool(materials));
30813
+ platformTools.push(
30814
+ name === "imageGen" ? createImageGenTool(materials) : name === "videoGen" ? createVideoGenTool(materials) : createWebSearchTool2(materials)
30815
+ );
30698
30816
  }
30699
30817
  const store = options.store ?? new TodoStore();
30700
30818
  const channel = options.promptChannel ?? new UnavailableChannel();
@@ -32490,6 +32608,8 @@ export {
32490
32608
  UnavailableChannel,
32491
32609
  VIDEOGEN_TOOL_MAX_DURATION,
32492
32610
  VideoGenArgsSchema,
32611
+ WEBSEARCH_TOOL_MAX_RESULTS,
32612
+ WebSearchArgsSchema2 as WebSearchArgsSchema,
32493
32613
  accumulateUsage,
32494
32614
  appBundleRegistryConfig,
32495
32615
  appendUserMessage,
@@ -32510,6 +32630,7 @@ export {
32510
32630
  createSession,
32511
32631
  createSessionView,
32512
32632
  createVideoGenTool,
32633
+ createWebSearchTool2 as createWebSearchTool,
32513
32634
  defineSkill,
32514
32635
  defineTool,
32515
32636
  initialSessionViewState,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tansr/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.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",