@blade-hq/agent-client 2612.0.0-beta.85 → 2612.0.0-beta.87

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
@@ -1,5 +1,7 @@
1
1
  export { BladeApplicationClient } from "./application-client";
2
2
  export { BladeClient } from "./blade-client";
3
+ export { BROWSER_DISABLED_CODE, BrowserDisabledError, getBrowserCapability, isBrowserDisabledError } from "./browser-capability";
4
+ export type { BrowserCapability } from "./browser-capability";
3
5
  export { ConnectorsResource } from "./resources/connectors";
4
6
  export * from "./resources/feishu-bots";
5
7
  export type { ConnectorRuleValue, ConnectorRuleGroup, ConnectorRules, ConnectorPushSettingsResult, ConnectorPushSettings, ConnectorPushSetting, ConnectorArtifact, ConnectorApprovalStatus, ConnectorDomain, ConnectorAuthorization, ConnectorAuthorizationAction, ConnectorAuthorizationOptions, ConnectorAuthorizationPlan, ConnectorCapability, ConnectorPermission, ConnectorAuthorizationFailure, ConnectorAuthorizationStep, ConnectorDiagnostics, ConnectorRuntimeDiagnostics, ConnectorAuditEvent, AccountConnector, ConnectorDraft, ConnectorConnection, ConnectorConnectionView } from "./resources/connectors";
@@ -8,7 +10,7 @@ export { BladeApiError } from "./rest";
8
10
  export type { LoginOptions, LoginResult, TokenStorageMode } from "./auth-login";
9
11
  export { SDK_NAME, SDK_VERSION } from "./version";
10
12
  export { AgentSession } from "./session/agent-session";
11
- export type { AttachAppOptions, SendOptions, PreparedSend, PreparedSendOptions, DeliveryReceipt } from "./session/agent-session";
13
+ export type { AttachAppOptions, InputKind, SendOptions, DeliveryReceipt } from "./session/agent-session";
12
14
  export { AgentSessionError } from "./session/errors";
13
15
  export type { AgentSessionEvents, AgentSessionEventName } from "./session/events";
14
16
  export type { WorkflowRunEntry, WorkflowRunState } from "./session/workflow";
@@ -42,7 +44,7 @@ export type { PluginRef, SkillRef, MessageRef } from "./schemas/plugin-refs";
42
44
  export type { ToolEvidence } from "./schemas/projection";
43
45
  export { ToolProvider } from "./tool-provider";
44
46
  export type { ToolProviderOptions, ProviderTool, ProviderToolResult } from "./tool-provider";
45
- export type { ContextAttachment } from "./schemas/context-attachments";
47
+ export type { ContextAttachment, ContextSource } from "./schemas/context-attachments";
46
48
  export { SandboxResource, type SandboxScriptRequest, type SandboxScriptResult } from "./resources/sandbox";
47
49
  export type { LlmResource, ChatCompletionRequest, ChatCompletion } from "./resources/llm";
48
50
  export type { FileOpenerInstance } from "./resources/sessions";
@@ -54,3 +56,4 @@ export { attachPackPageBridge } from "./pack-page-bridge";
54
56
  export type { PackProfile, ProfileComponent, PackManifest, PackLayoutOperation, InstalledPack } from "./resources/profile";
55
57
  export { CapabilitiesResource } from "./resources/capabilities";
56
58
  export type { CapabilitySnapshot } from "./resources/capabilities";
59
+ export type { CompactionPreference } from "./resources/sessions";
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  AgentSession,
3
3
  AgentSessionError,
4
+ BROWSER_DISABLED_CODE,
4
5
  BladeApiError,
5
6
  BladeApplicationClient,
6
7
  BladeClient,
8
+ BrowserDisabledError,
7
9
  CapabilitiesResource,
8
10
  ConnectorsResource,
9
11
  DEFAULT_REPLAY_SPEED,
@@ -22,23 +24,27 @@ import {
22
24
  chatErrorForDisplay,
23
25
  contentPreview,
24
26
  formatAskUserAnswer,
27
+ getBrowserCapability,
25
28
  getFileParts,
26
29
  getImageParts,
27
30
  getTextContent,
28
31
  groupMessagesByLoop,
32
+ isBrowserDisabledError,
29
33
  normalizeMessageRefs,
30
34
  normalizePluginRefs,
31
35
  normalizeTopicAssetRefs,
32
36
  parseAskUserQuestion,
33
37
  transformSlashCommand,
34
38
  userFacingErrorText
35
- } from "./chunk-AKYL4RUF.js";
39
+ } from "./chunk-WXZ5AWAT.js";
36
40
  export {
37
41
  AgentSession,
38
42
  AgentSessionError,
43
+ BROWSER_DISABLED_CODE,
39
44
  BladeApiError,
40
45
  BladeApplicationClient,
41
46
  BladeClient,
47
+ BrowserDisabledError,
42
48
  CapabilitiesResource,
43
49
  ConnectorsResource,
44
50
  DEFAULT_REPLAY_SPEED,
@@ -57,10 +63,12 @@ export {
57
63
  chatErrorForDisplay,
58
64
  contentPreview,
59
65
  formatAskUserAnswer,
66
+ getBrowserCapability,
60
67
  getFileParts,
61
68
  getImageParts,
62
69
  getTextContent,
63
70
  groupMessagesByLoop,
71
+ isBrowserDisabledError,
64
72
  normalizeMessageRefs,
65
73
  normalizePluginRefs,
66
74
  normalizeTopicAssetRefs,
@@ -5,7 +5,7 @@ export { EMPTY_PLATFORM_ENDPOINTS, loadPlatformEndpoints, resolveServiceUrl, } f
5
5
  export type { LoadPlatformEndpointsOptions, PlatformEndpoints, PlatformServiceName, } from "./platform-endpoints";
6
6
  export { SessionHub } from "./session/hub";
7
7
  export type { SessionConnectOptions, SessionHubEvents, SessionHubOptions } from "./session/hub";
8
- export { sessionStatusFromChatEnd } from "./session/agent-session";
8
+ export { captureClientInputTime, sessionStatusFromChatEnd } from "./session/agent-session";
9
9
  export type { ChatEndPayload, SessionDetailSnapshot } from "./session/agent-session";
10
10
  export { isWorkflowRunToolName, workflowEntriesFromOutput, workflowNameFromArguments, } from "./session/workflow";
11
11
  export { isMcpAppData } from "./schemas/mcp-app";
package/dist/internal.js CHANGED
@@ -2,9 +2,11 @@ import {
2
2
  AgentSession,
3
3
  AgentSessionError,
4
4
  AuthBusyReconnect,
5
+ BROWSER_DISABLED_CODE,
5
6
  BladeApiError,
6
7
  BladeApplicationClient,
7
8
  BladeClient,
9
+ BrowserDisabledError,
8
10
  CapabilitiesResource,
9
11
  ChatGroupsResource,
10
12
  ClientProjectionBuilder,
@@ -37,6 +39,7 @@ import {
37
39
  canCancelQueuedMessage,
38
40
  canDeliverQueuedMessage,
39
41
  canEditQueuedMessage,
42
+ captureClientInputTime,
40
43
  chatErrorForDisplay,
41
44
  collectInlineToolUiCards,
42
45
  collectPreviewToolUiCards,
@@ -50,6 +53,7 @@ import {
50
53
  createSocket,
51
54
  extractTextAttachments,
52
55
  formatAskUserAnswer,
56
+ getBrowserCapability,
53
57
  getContextDisplayState,
54
58
  getContextGroupDisplayState,
55
59
  getFileParts,
@@ -62,6 +66,7 @@ import {
62
66
  inferToolStatus,
63
67
  isAppDevToolUiCard,
64
68
  isBackgroundWakeMessage,
69
+ isBrowserDisabledError,
65
70
  isEntryGoneError,
66
71
  isHiddenInternalMessage,
67
72
  isInternalStatusToolUiCard,
@@ -102,7 +107,7 @@ import {
102
107
  withTurns,
103
108
  workflowEntriesFromOutput,
104
109
  workflowNameFromArguments
105
- } from "./chunk-AKYL4RUF.js";
110
+ } from "./chunk-WXZ5AWAT.js";
106
111
 
107
112
  // src/polling-backoff.ts
108
113
  var MAX_BACKOFF_MS = 6e4;
@@ -271,9 +276,11 @@ export {
271
276
  AgentSession,
272
277
  AgentSessionError,
273
278
  AuthBusyReconnect,
279
+ BROWSER_DISABLED_CODE,
274
280
  BladeApiError,
275
281
  BladeApplicationClient,
276
282
  BladeClient,
283
+ BrowserDisabledError,
277
284
  CapabilitiesResource,
278
285
  ChatGroupsResource,
279
286
  ClientProjectionBuilder,
@@ -311,6 +318,7 @@ export {
311
318
  canCancelQueuedMessage,
312
319
  canDeliverQueuedMessage,
313
320
  canEditQueuedMessage,
321
+ captureClientInputTime,
314
322
  chatErrorForDisplay,
315
323
  collectInlineToolUiCards,
316
324
  collectPreviewToolUiCards,
@@ -324,6 +332,7 @@ export {
324
332
  createSocket,
325
333
  extractTextAttachments,
326
334
  formatAskUserAnswer,
335
+ getBrowserCapability,
327
336
  getContextDisplayState,
328
337
  getContextGroupDisplayState,
329
338
  getFileParts,
@@ -336,6 +345,7 @@ export {
336
345
  inferToolStatus,
337
346
  isAppDevToolUiCard,
338
347
  isBackgroundWakeMessage,
348
+ isBrowserDisabledError,
339
349
  isCommandEnvelope,
340
350
  isEntryGoneError,
341
351
  isHiddenInternalMessage,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/polling-backoff.ts","../src/platform-endpoints.ts","../src/commands/protocol.ts","../src/schemas/projection-utils.ts","../src/schemas/solution.ts","../src/schemas/task.ts"],"sourcesContent":["import { BladeApiError } from \"./rest\"\n\nconst MAX_BACKOFF_MS = 60_000\nconst MAX_TIMER_MS = 2_147_483_647\n\n/** Scheduling policy for read-only polling; never sends or replays a request. */\nexport class PollingBackoff {\n private failures = 0\n private nextAt: number | false = 0\n\n constructor(private readonly intervalMs: number) {\n if (!Number.isFinite(intervalMs) || intervalMs <= 0 || intervalMs > MAX_BACKOFF_MS) {\n throw new RangeError(\"Polling interval must be between 0 and 60000 ms\")\n }\n }\n\n reset(): void {\n this.failures = 0\n this.nextAt = 0\n }\n\n failed(error: unknown): void {\n if (\n (error instanceof Error && error.name === \"AbortError\") ||\n (error instanceof BladeApiError && error.status < 500 &&\n error.status !== 408 && error.status !== 429)\n ) {\n this.nextAt = false\n return\n }\n this.failures = Math.min(this.failures + 1, 10)\n const ceiling = Math.min(MAX_BACKOFF_MS, this.intervalMs * 2 ** this.failures)\n const backoff = Math.max(this.intervalMs, ceiling * (0.5 + Math.random() * 0.5))\n const header = error instanceof BladeApiError\n ? error.response.headers.get(\"Retry-After\")?.trim()\n : undefined\n const retryAfter = header\n ? /^\\d+$/.test(header) ? Number(header) * 1000 : Date.parse(header) - Date.now()\n : 0\n const delay = Math.max(backoff, Number.isNaN(retryAfter) ? 0 : retryAfter)\n // Oversized server delays must not overflow browser timers into a hot loop.\n this.nextAt = delay > MAX_TIMER_MS ? false : Date.now() + delay\n }\n\n /** Zero means ready, false means stop, otherwise wait at least this many ms. */\n waitMs(): number | false {\n return this.nextAt === false ? false : Math.max(0, this.nextAt - Date.now())\n }\n}\n","import { isRecord } from \"./shared/type-guards\"\n\nexport const PLATFORM_SERVICE_NAMES = [\n \"os\",\n \"hub\",\n \"agent\",\n \"oauth\",\n \"llmGateway\",\n \"gitea\",\n \"tile\",\n] as const\n\nexport type PlatformServiceName = (typeof PLATFORM_SERVICE_NAMES)[number]\n\nexport interface PlatformEndpoints {\n services: Partial<Record<PlatformServiceName, string>>\n}\n\nexport const EMPTY_PLATFORM_ENDPOINTS: PlatformEndpoints = Object.freeze({\n services: Object.freeze({}),\n})\n\nexport interface LoadPlatformEndpointsOptions {\n baseUrl?: string\n fetchImpl?: typeof fetch\n timeoutMs?: number\n}\n\nfunction defaultDocumentBaseUrl(): string | undefined {\n if (typeof document === \"undefined\") return undefined\n if (document.querySelector(\"base[href]\")) return document.baseURI\n if (typeof location !== \"undefined\" && location.origin) return `${location.origin}/`\n return document.baseURI\n}\n\nfunction normalizeServiceUrl(value: unknown): string | null {\n if (typeof value !== \"string\" || !value.trim()) return null\n if (value.includes(\"?\") || value.includes(\"#\")) return null\n try {\n const url = new URL(value.trim())\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return null\n if (url.username || url.password || url.search || url.hash) return null\n return url.toString().replace(/\\/$/, \"\")\n } catch {\n return null\n }\n}\n\nexport function parsePlatformEndpoints(value: unknown): PlatformEndpoints | null {\n if (!isRecord(value) || !isRecord(value.services)) return null\n\n const services: Partial<Record<PlatformServiceName, string>> = {}\n for (const name of PLATFORM_SERVICE_NAMES) {\n if (!(name in value.services)) continue\n const url = normalizeServiceUrl(value.services[name])\n if (!url) return null\n if (name === \"agent\" && new URL(url).pathname !== \"/\") return null\n services[name] = url\n }\n\n return { services }\n}\n\nexport async function loadPlatformEndpoints(\n options: LoadPlatformEndpointsOptions = {},\n): Promise<PlatformEndpoints> {\n const fetchImpl = options.fetchImpl ?? globalThis.fetch\n const baseUrl = options.baseUrl ?? defaultDocumentBaseUrl()\n if (!fetchImpl || !baseUrl) return EMPTY_PLATFORM_ENDPOINTS\n\n const controller = new AbortController()\n const timeout = globalThis.setTimeout(() => controller.abort(), options.timeoutMs ?? 3_000)\n try {\n const response = await fetchImpl(new URL(\"config.json\", baseUrl), {\n cache: \"no-store\",\n credentials: \"same-origin\",\n headers: { Accept: \"application/json\" },\n signal: controller.signal,\n })\n if (!response.ok) return EMPTY_PLATFORM_ENDPOINTS\n return parsePlatformEndpoints(await response.json()) ?? EMPTY_PLATFORM_ENDPOINTS\n } catch {\n return EMPTY_PLATFORM_ENDPOINTS\n } finally {\n globalThis.clearTimeout(timeout)\n }\n}\n\nexport function resolveServiceUrl(\n endpoints: PlatformEndpoints,\n name: PlatformServiceName,\n path = \"\",\n): string | null {\n const baseUrl = endpoints.services[name]\n if (!baseUrl) return null\n if (!path) return baseUrl\n const pathReference = path.trimStart()\n if (\n path.includes(\"\\\\\") ||\n pathReference.startsWith(\"//\") ||\n /^[a-z][a-z0-9+.-]*:/i.test(pathReference)\n ) {\n return null\n }\n const base = new URL(`${baseUrl}/`)\n const target = new URL(path.replace(/^\\/+/, \"\"), base)\n if (target.origin !== base.origin || !target.pathname.startsWith(base.pathname)) {\n return null\n }\n return target.toString()\n}\n","/**\n * 页面协作协议(对应后端 `_meta.bridge` 通道,见 docs/specs/260417-embed-bridge)。\n *\n * ## action 从哪里来\n *\n * 智能体 → 宿主方向的每一条指令,都源自**技能作者写的工具代码**:工具返回值\n * JSON 里带 `_meta.bridge: { action, payload }`,后端在持久化前把它剥离成独立\n * 事件送达前端(LLM 的对话历史里读不到它)。因此:\n *\n * - action 字符串(如 \"map.highlight\")是**技能作者与宿主页面开发者之间的业务\n * 契约**,LLM 不参与协议、SDK 不做枚举校验;\n * - 宿主页面用 `session.onCommand(\"map.highlight\", fn)` 消费;\n * - 未注册 handler 的 action 会进入有限缓冲等待注册,超限后丢弃并 console 告警。\n *\n * 宿主 → 智能体方向只有三个白名单动作:attach(附件入输入框)/ insertText\n * (追加输入文本)/ send(直接发消息),对应协议层的 addContext / appendInput /\n * sendMessage。\n */\n\nexport interface CommandEnvelope {\n __bladeBridge: true\n direction: \"agent-to-host\"\n action: string\n payload: unknown\n meta: {\n sessionId: string\n toolCallId?: string\n timestamp: number\n }\n}\n\nexport type InboundAction = \"addContext\" | \"appendInput\" | \"sendMessage\"\n\nexport interface InboundEnvelope {\n __bladeBridge: true\n direction: \"host-to-agent\"\n action: InboundAction\n payload: unknown\n}\n\nexport function isCommandEnvelope(value: unknown): value is CommandEnvelope {\n if (typeof value !== \"object\" || value === null) return false\n const record = value as Record<string, unknown>\n return (\n record.__bladeBridge === true &&\n record.direction === \"agent-to-host\" &&\n typeof record.action === \"string\"\n )\n}\n\nexport function isInboundEnvelope(value: unknown): value is InboundEnvelope {\n if (typeof value !== \"object\" || value === null) return false\n const record = value as Record<string, unknown>\n return (\n record.__bladeBridge === true &&\n record.direction === \"host-to-agent\" &&\n (record.action === \"addContext\" || record.action === \"appendInput\" || record.action === \"sendMessage\")\n )\n}\n","import type { PostChatFollowup, TurnProjection } from \"./projection\"\n\n/** 返回最新根会话轮次的小结;新用户消息到达后旧小结立即失效。 */\nexport function latestPostChatFollowup(turns: TurnProjection[]): PostChatFollowup | null {\n for (let index = turns.length - 1; index >= 0; index -= 1) {\n const turn = turns[index]\n if (\n turn.loop_id === \"root\" &&\n (turn.role === \"user\" || turn.role === \"assistant\") &&\n (turn.kind ?? \"message\") === \"message\" &&\n !turn.blocks.some((block) =>\n [\"mode_change\", \"plan_status\", \"ask_user_answer\"].includes(block.type),\n )\n ) {\n return turn.role === \"assistant\" ? (turn.post_chat_followup ?? null) : null\n }\n }\n return null\n}\n","export enum LayoutType {\n Default = \"default\",\n SkillEditor = \"skill-editor\",\n SolutionEditor = \"solution-editor\",\n SolutionApp = \"solution-app\",\n Custom = \"custom\",\n}\n\nexport interface Solution {\n id: string\n name: string\n version: string\n description?: string | null\n source?: \"builtin\" | \"personal\" | string | null\n layout_type: LayoutType | string\n initial_mode?: \"planning\" | \"executing\" | string | null\n initial_message?: string | null\n preview?: { url: string; title?: string | null } | null\n layout?: {\n available?: boolean\n source_dir?: string\n entry?: string\n export?: string\n } | null\n roles?: BizRole[] | null\n data?: Record<string, unknown> | null\n ui_config?: SolutionAppUiConfig | null\n}\n\nexport interface SolutionAppUiConfig {\n branding: {\n name: string\n subtitle?: string\n icon_text: string\n icon_gradient?: string\n }\n list: {\n title: string\n create_button: string\n card?: {\n subtitle?: string\n stats?: Array<{\n label: string\n value: string\n color?: string\n }>\n }\n }\n create: {\n title: string\n description?: string\n submit_button: string\n sections: Array<{\n id: string\n title: string\n description?: string\n fields: Array<SolutionAppField>\n }>\n }\n}\n\nexport type SolutionAppField =\n | {\n id: string\n kind: \"textarea\"\n label: string\n placeholder?: string\n }\n | {\n id: string\n kind: \"file-upload\"\n accept?: string[]\n categories?: Array<{\n label: string\n description: string\n color: string\n }>\n }\n\nexport interface SolutionAppState {\n pipeline: Array<{\n id: string\n label: string\n status: \"done\" | \"active\" | \"pending\" | \"error\"\n }>\n meta: Record<\n string,\n {\n label: string\n value: string\n color?: string\n }\n >\n}\n\nexport interface BizRole {\n id: string\n name: string\n description?: string | null\n preview?: { url: string; title?: string | null } | null\n}\n","import { type } from \"arktype\"\n\nexport const TaskStatus = type(\"'pending' | 'in_progress' | 'done' | 'failed' | 'skipped'\")\nexport type TaskStatus = typeof TaskStatus.infer\n\nexport const Task = type({\n id: \"string\",\n goal: \"string\",\n skills: \"string[]\",\n depends_on: \"string[]\",\n status: TaskStatus,\n result_summary: \"string\",\n number: \"string\",\n})\nexport type Task = typeof Task.infer\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAM,iBAAiB;AACvB,IAAM,eAAe;AAGd,IAAM,iBAAN,MAAqB;AAAA,EAI1B,YAA6B,YAAoB;AAApB;AAC3B,QAAI,CAAC,OAAO,SAAS,UAAU,KAAK,cAAc,KAAK,aAAa,gBAAgB;AAClF,YAAM,IAAI,WAAW,iDAAiD;AAAA,IACxE;AAAA,EACF;AAAA,EAJ6B;AAAA,EAHrB,WAAW;AAAA,EACX,SAAyB;AAAA,EAQjC,QAAc;AACZ,SAAK,WAAW;AAChB,SAAK,SAAS;AAAA,EAChB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,SAAS,GAAG;AACzD,UAAM,OAAO,MAAM,KAAK;AACxB,QACE,KAAK,YAAY,WAChB,KAAK,SAAS,UAAU,KAAK,SAAS,iBACtC,KAAK,QAAQ,eAAe,aAC7B,CAAC,KAAK,OAAO;AAAA,MAAK,CAAC,UACjB,CAAC,eAAe,eAAe,iBAAiB,EAAE,SAAS,MAAM,IAAI;AAAA,IACvE,GACA;AACA,aAAO,KAAK,SAAS,cAAe,KAAK,sBAAsB,OAAQ;AAAA,IACzE;AAAA,EACF;AACA,SAAO;AACT;;;AClBO,IAAK,aAAL,kBAAKA,gBAAL;AACL,EAAAA,YAAA,aAAU;AACV,EAAAA,YAAA,iBAAc;AACd,EAAAA,YAAA,oBAAiB;AACjB,EAAAA,YAAA,iBAAc;AACd,EAAAA,YAAA,YAAS;AALC,SAAAA;AAAA,GAAA;;;ACAZ,SAAS,YAAY;AAEd,IAAM,aAAa,KAAK,2DAA2D;AAGnF,IAAM,OAAO,KAAK;AAAA,EACvB,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,gBAAgB;AAAA,EAChB,QAAQ;AACV,CAAC;","names":["LayoutType"]}
1
+ {"version":3,"sources":["../src/polling-backoff.ts","../src/platform-endpoints.ts","../src/commands/protocol.ts","../src/schemas/projection-utils.ts","../src/schemas/solution.ts","../src/schemas/task.ts"],"sourcesContent":["import { BladeApiError } from \"./rest\"\n\nconst MAX_BACKOFF_MS = 60_000\nconst MAX_TIMER_MS = 2_147_483_647\n\n/** Scheduling policy for read-only polling; never sends or replays a request. */\nexport class PollingBackoff {\n private failures = 0\n private nextAt: number | false = 0\n\n constructor(private readonly intervalMs: number) {\n if (!Number.isFinite(intervalMs) || intervalMs <= 0 || intervalMs > MAX_BACKOFF_MS) {\n throw new RangeError(\"Polling interval must be between 0 and 60000 ms\")\n }\n }\n\n reset(): void {\n this.failures = 0\n this.nextAt = 0\n }\n\n failed(error: unknown): void {\n if (\n (error instanceof Error && error.name === \"AbortError\") ||\n (error instanceof BladeApiError && error.status < 500 &&\n error.status !== 408 && error.status !== 429)\n ) {\n this.nextAt = false\n return\n }\n this.failures = Math.min(this.failures + 1, 10)\n const ceiling = Math.min(MAX_BACKOFF_MS, this.intervalMs * 2 ** this.failures)\n const backoff = Math.max(this.intervalMs, ceiling * (0.5 + Math.random() * 0.5))\n const header = error instanceof BladeApiError\n ? error.response.headers.get(\"Retry-After\")?.trim()\n : undefined\n const retryAfter = header\n ? /^\\d+$/.test(header) ? Number(header) * 1000 : Date.parse(header) - Date.now()\n : 0\n const delay = Math.max(backoff, Number.isNaN(retryAfter) ? 0 : retryAfter)\n // Oversized server delays must not overflow browser timers into a hot loop.\n this.nextAt = delay > MAX_TIMER_MS ? false : Date.now() + delay\n }\n\n /** Zero means ready, false means stop, otherwise wait at least this many ms. */\n waitMs(): number | false {\n return this.nextAt === false ? false : Math.max(0, this.nextAt - Date.now())\n }\n}\n","import { isRecord } from \"./shared/type-guards\"\n\nexport const PLATFORM_SERVICE_NAMES = [\n \"os\",\n \"hub\",\n \"agent\",\n \"oauth\",\n \"llmGateway\",\n \"gitea\",\n \"tile\",\n] as const\n\nexport type PlatformServiceName = (typeof PLATFORM_SERVICE_NAMES)[number]\n\nexport interface PlatformEndpoints {\n services: Partial<Record<PlatformServiceName, string>>\n}\n\nexport const EMPTY_PLATFORM_ENDPOINTS: PlatformEndpoints = Object.freeze({\n services: Object.freeze({}),\n})\n\nexport interface LoadPlatformEndpointsOptions {\n baseUrl?: string\n fetchImpl?: typeof fetch\n timeoutMs?: number\n}\n\nfunction defaultDocumentBaseUrl(): string | undefined {\n if (typeof document === \"undefined\") return undefined\n if (document.querySelector(\"base[href]\")) return document.baseURI\n if (typeof location !== \"undefined\" && location.origin) return `${location.origin}/`\n return document.baseURI\n}\n\nfunction normalizeServiceUrl(value: unknown): string | null {\n if (typeof value !== \"string\" || !value.trim()) return null\n if (value.includes(\"?\") || value.includes(\"#\")) return null\n try {\n const url = new URL(value.trim())\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return null\n if (url.username || url.password || url.search || url.hash) return null\n return url.toString().replace(/\\/$/, \"\")\n } catch {\n return null\n }\n}\n\nexport function parsePlatformEndpoints(value: unknown): PlatformEndpoints | null {\n if (!isRecord(value) || !isRecord(value.services)) return null\n\n const services: Partial<Record<PlatformServiceName, string>> = {}\n for (const name of PLATFORM_SERVICE_NAMES) {\n if (!(name in value.services)) continue\n const url = normalizeServiceUrl(value.services[name])\n if (!url) return null\n if (name === \"agent\" && new URL(url).pathname !== \"/\") return null\n services[name] = url\n }\n\n return { services }\n}\n\nexport async function loadPlatformEndpoints(\n options: LoadPlatformEndpointsOptions = {},\n): Promise<PlatformEndpoints> {\n const fetchImpl = options.fetchImpl ?? globalThis.fetch\n const baseUrl = options.baseUrl ?? defaultDocumentBaseUrl()\n if (!fetchImpl || !baseUrl) return EMPTY_PLATFORM_ENDPOINTS\n\n const controller = new AbortController()\n const timeout = globalThis.setTimeout(() => controller.abort(), options.timeoutMs ?? 3_000)\n try {\n const response = await fetchImpl(new URL(\"config.json\", baseUrl), {\n cache: \"no-store\",\n credentials: \"same-origin\",\n headers: { Accept: \"application/json\" },\n signal: controller.signal,\n })\n if (!response.ok) return EMPTY_PLATFORM_ENDPOINTS\n return parsePlatformEndpoints(await response.json()) ?? EMPTY_PLATFORM_ENDPOINTS\n } catch {\n return EMPTY_PLATFORM_ENDPOINTS\n } finally {\n globalThis.clearTimeout(timeout)\n }\n}\n\nexport function resolveServiceUrl(\n endpoints: PlatformEndpoints,\n name: PlatformServiceName,\n path = \"\",\n): string | null {\n const baseUrl = endpoints.services[name]\n if (!baseUrl) return null\n if (!path) return baseUrl\n const pathReference = path.trimStart()\n if (\n path.includes(\"\\\\\") ||\n pathReference.startsWith(\"//\") ||\n /^[a-z][a-z0-9+.-]*:/i.test(pathReference)\n ) {\n return null\n }\n const base = new URL(`${baseUrl}/`)\n const target = new URL(path.replace(/^\\/+/, \"\"), base)\n if (target.origin !== base.origin || !target.pathname.startsWith(base.pathname)) {\n return null\n }\n return target.toString()\n}\n","/**\n * 页面协作协议(对应后端 `_meta.bridge` 通道,见 docs/specs/260417-embed-bridge)。\n *\n * ## action 从哪里来\n *\n * 智能体 → 宿主方向的每一条指令,都源自**技能作者写的工具代码**:工具返回值\n * JSON 里带 `_meta.bridge: { action, payload }`,后端在持久化前把它剥离成独立\n * 事件送达前端(LLM 的对话历史里读不到它)。因此:\n *\n * - action 字符串(如 \"map.highlight\")是**技能作者与宿主页面开发者之间的业务\n * 契约**,LLM 不参与协议、SDK 不做枚举校验;\n * - 宿主页面用 `session.onCommand(\"map.highlight\", fn)` 消费;\n * - 未注册 handler 的 action 会进入有限缓冲等待注册,超限后丢弃并 console 告警。\n *\n * 宿主 → 智能体方向只有三个白名单动作:attach(附件入输入框)/ insertText\n * (追加输入文本)/ send(直接发消息),对应协议层的 addContext / appendInput /\n * sendMessage。\n */\n\nexport interface CommandEnvelope {\n __bladeBridge: true\n direction: \"agent-to-host\"\n action: string\n payload: unknown\n meta: {\n sessionId: string\n toolCallId?: string\n timestamp: number\n }\n}\n\nexport type InboundAction = \"addContext\" | \"appendInput\" | \"sendMessage\"\n\nexport interface InboundEnvelope {\n __bladeBridge: true\n direction: \"host-to-agent\"\n action: InboundAction\n payload: unknown\n}\n\nexport function isCommandEnvelope(value: unknown): value is CommandEnvelope {\n if (typeof value !== \"object\" || value === null) return false\n const record = value as Record<string, unknown>\n return (\n record.__bladeBridge === true &&\n record.direction === \"agent-to-host\" &&\n typeof record.action === \"string\"\n )\n}\n\nexport function isInboundEnvelope(value: unknown): value is InboundEnvelope {\n if (typeof value !== \"object\" || value === null) return false\n const record = value as Record<string, unknown>\n return (\n record.__bladeBridge === true &&\n record.direction === \"host-to-agent\" &&\n (record.action === \"addContext\" || record.action === \"appendInput\" || record.action === \"sendMessage\")\n )\n}\n","import type { PostChatFollowup, TurnProjection } from \"./projection\"\n\n/** 返回最新根会话轮次的小结;新用户消息到达后旧小结立即失效。 */\nexport function latestPostChatFollowup(turns: TurnProjection[]): PostChatFollowup | null {\n for (let index = turns.length - 1; index >= 0; index -= 1) {\n const turn = turns[index]\n if (\n turn.loop_id === \"root\" &&\n (turn.role === \"user\" || turn.role === \"assistant\") &&\n (turn.kind ?? \"message\") === \"message\" &&\n !turn.blocks.some((block) =>\n [\"mode_change\", \"plan_status\", \"ask_user_answer\"].includes(block.type),\n )\n ) {\n return turn.role === \"assistant\" ? (turn.post_chat_followup ?? null) : null\n }\n }\n return null\n}\n","export enum LayoutType {\n Default = \"default\",\n SkillEditor = \"skill-editor\",\n SolutionEditor = \"solution-editor\",\n SolutionApp = \"solution-app\",\n Custom = \"custom\",\n}\n\nexport interface Solution {\n id: string\n name: string\n version: string\n description?: string | null\n source?: \"builtin\" | \"personal\" | string | null\n layout_type: LayoutType | string\n initial_mode?: \"planning\" | \"executing\" | string | null\n initial_message?: string | null\n preview?: { url: string; title?: string | null } | null\n layout?: {\n available?: boolean\n source_dir?: string\n entry?: string\n export?: string\n } | null\n roles?: BizRole[] | null\n data?: Record<string, unknown> | null\n ui_config?: SolutionAppUiConfig | null\n}\n\nexport interface SolutionAppUiConfig {\n branding: {\n name: string\n subtitle?: string\n icon_text: string\n icon_gradient?: string\n }\n list: {\n title: string\n create_button: string\n card?: {\n subtitle?: string\n stats?: Array<{\n label: string\n value: string\n color?: string\n }>\n }\n }\n create: {\n title: string\n description?: string\n submit_button: string\n sections: Array<{\n id: string\n title: string\n description?: string\n fields: Array<SolutionAppField>\n }>\n }\n}\n\nexport type SolutionAppField =\n | {\n id: string\n kind: \"textarea\"\n label: string\n placeholder?: string\n }\n | {\n id: string\n kind: \"file-upload\"\n accept?: string[]\n categories?: Array<{\n label: string\n description: string\n color: string\n }>\n }\n\nexport interface SolutionAppState {\n pipeline: Array<{\n id: string\n label: string\n status: \"done\" | \"active\" | \"pending\" | \"error\"\n }>\n meta: Record<\n string,\n {\n label: string\n value: string\n color?: string\n }\n >\n}\n\nexport interface BizRole {\n id: string\n name: string\n description?: string | null\n preview?: { url: string; title?: string | null } | null\n}\n","import { type } from \"arktype\"\n\nexport const TaskStatus = type(\"'pending' | 'in_progress' | 'done' | 'failed' | 'skipped'\")\nexport type TaskStatus = typeof TaskStatus.infer\n\nexport const Task = type({\n id: \"string\",\n goal: \"string\",\n skills: \"string[]\",\n depends_on: \"string[]\",\n status: TaskStatus,\n result_summary: \"string\",\n number: \"string\",\n})\nexport type Task = typeof Task.infer\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAM,iBAAiB;AACvB,IAAM,eAAe;AAGd,IAAM,iBAAN,MAAqB;AAAA,EAI1B,YAA6B,YAAoB;AAApB;AAC3B,QAAI,CAAC,OAAO,SAAS,UAAU,KAAK,cAAc,KAAK,aAAa,gBAAgB;AAClF,YAAM,IAAI,WAAW,iDAAiD;AAAA,IACxE;AAAA,EACF;AAAA,EAJ6B;AAAA,EAHrB,WAAW;AAAA,EACX,SAAyB;AAAA,EAQjC,QAAc;AACZ,SAAK,WAAW;AAChB,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,OAAO,OAAsB;AAC3B,QACG,iBAAiB,SAAS,MAAM,SAAS,gBACzC,iBAAiB,iBAAiB,MAAM,SAAS,OAChD,MAAM,WAAW,OAAO,MAAM,WAAW,KAC3C;AACA,WAAK,SAAS;AACd;AAAA,IACF;AACA,SAAK,WAAW,KAAK,IAAI,KAAK,WAAW,GAAG,EAAE;AAC9C,UAAM,UAAU,KAAK,IAAI,gBAAgB,KAAK,aAAa,KAAK,KAAK,QAAQ;AAC7E,UAAM,UAAU,KAAK,IAAI,KAAK,YAAY,WAAW,MAAM,KAAK,OAAO,IAAI,IAAI;AAC/E,UAAM,SAAS,iBAAiB,gBAC5B,MAAM,SAAS,QAAQ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AA,oBAAiB;AACjB,EAAAA,YAAA,iBAAc;AACd,EAAAA,YAAA,YAAS;AALC,SAAAA;AAAA,GAAA;;;ACAZ,SAAS,YAAY;AAEd,IAAM,aAAa,KAAK,2DAA2D;AAGnF,IAAM,OAAO,KAAK;AAAA,EACvB,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,gBAAgB;AAAA,EAChB,QAAQ;AACV,CAAC;","names":["LayoutType"]}
@@ -2,6 +2,7 @@ import type { TopicAssetRef } from "../schemas/topic-assets";
2
2
  import type { BladeClient } from "../blade-client";
3
3
  export type JsonSchemaObject = Record<string, unknown>;
4
4
  export interface HeadlessRunOptions {
5
+ requestId?: string;
5
6
  schema?: JsonSchemaObject | null;
6
7
  model?: string | null;
7
8
  timeoutMs?: number;
@@ -20,7 +21,6 @@ export declare class HeadlessError extends Error {
20
21
  }
21
22
  export declare class HeadlessResource {
22
23
  private client;
23
- private readonly subscriptions;
24
24
  constructor(client: BladeClient);
25
25
  run<T = unknown>(prompt: string, options: HeadlessRunOptions & {
26
26
  schema: JsonSchemaObject;
@@ -35,4 +35,5 @@ export declare class HeadlessResource {
35
35
  }): Promise<HeadlessRunInSessionResult<T>>;
36
36
  runWithSession(prompt: string, options?: HeadlessRunOptions): Promise<HeadlessRunInSessionResult<string>>;
37
37
  private runTracked;
38
+ private stopInput;
38
39
  }
@@ -8,6 +8,7 @@ import type { BladeClient, UploadProgress } from "../blade-client";
8
8
  import type { AgentSession } from "../session/agent-session";
9
9
  import { type SessionDefinition } from "../session/definition";
10
10
  import type { SessionProfile } from "../types/sdk-profile";
11
+ export type CompactionPreference = "default" | "economical";
11
12
  export interface FileOpenerInstance {
12
13
  token: string;
13
14
  title: string;
@@ -126,6 +127,7 @@ export interface CreateSessionRequest {
126
127
  }[];
127
128
  session_solution_asset_id?: string | null;
128
129
  compaction_ratio?: number | null;
130
+ compaction_preference?: CompactionPreference;
129
131
  chat_group_id?: string | null;
130
132
  }
131
133
  export interface McpSourceConfig {
@@ -158,6 +160,7 @@ export interface UpdateSessionConfigurationRequest {
158
160
  mcp_sources?: McpSourceConfig[];
159
161
  skip_confirmations?: boolean;
160
162
  compaction_ratio?: number | null;
163
+ compaction_preference?: CompactionPreference;
161
164
  }
162
165
  export interface SessionConfiguration {
163
166
  session_id: string;
@@ -176,6 +179,7 @@ export interface SessionConfiguration {
176
179
  mcp_sources: Omit<McpSourceConfig, "bearer_token">[];
177
180
  skip_confirmations: boolean;
178
181
  compaction_ratio: number | null;
182
+ compaction_preference: CompactionPreference;
179
183
  };
180
184
  }
181
185
  export interface CheckpointNode {
@@ -273,6 +277,11 @@ export interface SessionContextStats {
273
277
  compaction_ratio: number;
274
278
  }
275
279
  export interface SessionTurnsPage {
280
+ /** Durable boundary of the complete projection, independent of pagination. */
281
+ logCursor?: {
282
+ afterLogSeq: number;
283
+ epoch: number;
284
+ };
276
285
  turns: TurnProjection[];
277
286
  nextBefore: string | null;
278
287
  currentMode: "planning" | "executing";
@@ -1,3 +1,9 @@
1
+ /** Execution-time read from an already authorized session MCP source. */
2
+ export interface ContextSource {
3
+ source: string;
4
+ /** Frozen object/selection identity; never a fetched snapshot. */
5
+ arguments?: Record<string, unknown>;
6
+ }
1
7
  /** Frozen application data belonging to one message. The server does not interpret business types. */
2
8
  export interface ContextAttachment {
3
9
  id: string;
@@ -1,4 +1,4 @@
1
- import { type ContextAttachment } from "../schemas/context-attachments";
1
+ import type { ContextAttachment, ContextSource } from "../schemas/context-attachments";
2
2
  import type { TopicAssetRef } from "../schemas/topic-assets";
3
3
  import { type RawEvent } from "../shared/projection";
4
4
  import type { MessageContent } from "../schemas/message";
@@ -59,7 +59,19 @@ export interface AttachAppOptions {
59
59
  /** 每次发送前执行一次;返回当前页面状态的 JSON 对象快照。 */
60
60
  getContext: () => Record<string, unknown> | Promise<Record<string, unknown>>;
61
61
  }
62
+ export type InputKind = "user" | "external_event" | "system";
63
+ export declare function captureClientInputTime(now?: Date): {
64
+ receivedAt: string;
65
+ timeZone?: string;
66
+ };
62
67
  export interface SendOptions {
68
+ /** Persist this ID with the original business input before sending if process recovery is needed. */
69
+ requestId?: string;
70
+ /** Stops local waiting only; never serialized or treated as a BA rejection. */
71
+ signal?: AbortSignal;
72
+ headless?: boolean;
73
+ outputSchema?: Record<string, unknown>;
74
+ contextSources?: ContextSource[];
63
75
  contextAttachments?: ContextAttachment[];
64
76
  /** planning / executing 模式。 */
65
77
  mode?: string;
@@ -85,24 +97,18 @@ export interface SendOptions {
85
97
  * 默认发送引导消息;显式为 true 时等待当前运行结束(等待回答时发送仍作答)。
86
98
  */
87
99
  queueWhenRunning?: boolean;
88
- }
89
- /** Durable text input with message-scoped application data. Persist this JSON value before calling sendPrepared. */
90
- export interface PreparedSend {
91
- sessionId: string;
92
- requestId: string;
93
- content: string;
94
- options: PreparedSendOptions;
95
- }
96
- export interface PreparedSendOptions {
97
- /** Require BA submit_result for this execution. */
98
- headless?: boolean;
99
- /** false 时补充当前运行;省略或 true 时等待下一轮。 */
100
- queueWhenRunning?: boolean;
101
- contextAttachments?: ContextAttachment[];
102
- mode?: "planning" | "executing";
103
- model?: string;
104
- thinkingOverride?: boolean;
105
- reasoningLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
100
+ /** Higher values run first; equal priorities retain queue order. */
101
+ queuePriority?: number;
102
+ /** End an existing native-question wait when no explicit answer is pending. */
103
+ releaseNativeWait?: boolean;
104
+ /** Explicitly allow compatible inputs with this key to share an execution. */
105
+ batchKey?: string;
106
+ /** 输入来源类别(默认 user)。 */
107
+ inputKind?: InputKind;
108
+ /** 首次接收时间(ISO-8601 带时区偏移)。 */
109
+ receivedAt?: string;
110
+ /** 客户端或事件来源 IANA 时区。 */
111
+ timeZone?: string;
106
112
  }
107
113
  export interface DeliveryReceipt {
108
114
  requestId: string;
@@ -111,7 +117,10 @@ export interface DeliveryReceipt {
111
117
  queueStatus?: string;
112
118
  executionId?: string | null;
113
119
  message?: string;
120
+ /** Explicit business rejection code; never inferred from display text. */
121
+ code?: string;
114
122
  }
123
+ export declare function createClientRequestId(): string;
115
124
  export declare function sessionStatusFromChatEnd(status: string | undefined): SessionStatus;
116
125
  /**
117
126
  * 一个会话的实时状态机:封装 Socket.IO 订阅、历史 + 流式合流、断线补数,
@@ -139,6 +148,8 @@ export declare class AgentSession {
139
148
  private joinPending;
140
149
  private subscriptionQueue;
141
150
  private replaceQueue;
151
+ private authoritativeHistoryPending;
152
+ private authoritativeHistoryRequested;
142
153
  private timelineEpoch;
143
154
  private locateToken;
144
155
  private locateAbort;
@@ -155,27 +166,17 @@ export declare class AgentSession {
155
166
  private commandRestoreRetryAttempt;
156
167
  private commandRestoreRetryHandle;
157
168
  private bufferedCommandDeliveries;
158
- private pendingReplayMessage;
159
- private pendingReplayMode;
160
- private pendingReplayRequestId;
161
- private pendingReplayAttachments;
162
- private pendingReplayRefs;
163
- private pendingReplayTopicAssetRefs;
164
- private recentChatEndAt;
165
- private lastDeliveredSystemError;
166
- private systemErrorGeneration;
167
169
  private subscriptionReplaySource;
168
170
  private readonly lifetimeAbort;
169
171
  private disposed;
170
172
  private getAppContext;
171
- private sendPending;
173
+ private readonly submissionWaits;
172
174
  private manualCompactionRequest;
173
175
  private epochReloadRequested;
174
176
  private epochReloadDone;
175
177
  private epochReloadRunning;
176
178
  private setManualCompactionRequest;
177
179
  private handleManualCompactionFinished;
178
- private pendingChatRequestId;
179
180
  private readonly workflowRunToolCalls;
180
181
  private desiredStreamTokens;
181
182
  private joinedStreamTokens;
@@ -267,21 +268,15 @@ export declare class AgentSession {
267
268
  attachApp(options: AttachAppOptions): Promise<AppCliAttachment | null>;
268
269
  /** 立即为整个会话切换模型,并接续因模型故障停下的任务。 */
269
270
  selectModel(model: string): Promise<boolean>;
270
- /** Prepare a durable text input without sending any network request. */
271
- prepareSend(content: string, options?: PreparedSendOptions): PreparedSend;
272
- /** Durably send a text input with its saved delivery intent. Retries must reuse the saved request. */
273
- sendPrepared(request: PreparedSend): Promise<DeliveryReceipt>;
274
- /** Owner-authorized lookup; receipts remain until the session is deleted. */
275
- getDelivery(requestId: string): Promise<DeliveryReceipt>;
276
- /** 发送一条消息。字符串或多模态内容均可。 */
277
- send(content: MessageContent, options?: SendOptions): Promise<boolean>;
278
271
  /**
279
- * 入队一条等待消息(运行中排队 / 暂停期间照常入队)。
280
- *
281
- * ack 超时或传输失败时结果未知:用**同一个** `client_request_id` 重试一次,
282
- * 服务端按 `(session_id, client_request_id)` 幂等,不会制造第二条。
272
+ * Reliably submit any supported input. Retries freeze one request ID and
273
+ * explicit intent until BA accepts or rejects it. Local stop/disposal and
274
+ * access/license failures end waiting without proving non-delivery.
283
275
  */
284
- queueMessage(content: string): Promise<QueueOperationResult>;
276
+ send(content: MessageContent, options?: SendOptions): Promise<DeliveryReceipt>;
277
+ private awaitSubmission;
278
+ /** Owner-authorized lookup; receipts remain until the session is deleted. */
279
+ getDelivery(requestId: string): Promise<DeliveryReceipt>;
285
280
  /** 修改一条等待消息的正文;`expectedVersion` 是客户端看到的条目版本。 */
286
281
  updateQueuedMessage(itemId: string, expectedVersion: number, content: string): Promise<QueueOperationResult>;
287
282
  /**
@@ -304,9 +299,6 @@ export declare class AgentSession {
304
299
  refreshQueue(): Promise<QueueOperationResult>;
305
300
  private requestQueueAck;
306
301
  private runQueueCommand;
307
- private sendUnlocked;
308
- private rollbackOptimisticSend;
309
- private discardOptimisticSend;
310
302
  /** 停止当前回复。 */
311
303
  stop(executionId?: string): Promise<Record<string, unknown>>;
312
304
  /** 手动触发上下文压缩。 */
@@ -364,10 +356,6 @@ export declare class AgentSession {
364
356
  replay_state?: Record<string, unknown> | null;
365
357
  }): void;
366
358
  _handleRewind(checkpointId: string): void;
367
- _handleReplayMismatch(data: {
368
- actual_message?: string;
369
- expected_message?: string;
370
- }): void;
371
359
  _handleSystemNotification(loopId: string, notification: Record<string, unknown>): void;
372
360
  _handleBackgroundTask(task: AgentSessionEvents["backgroundTask"]): void;
373
361
  _handleArtifact(data: Record<string, unknown>, kind: "created" | "updated", replayed?: boolean): void;
@@ -392,6 +380,7 @@ export declare class AgentSession {
392
380
  private deliverCommandNow;
393
381
  private notifySandboxOom;
394
382
  private refreshAuthoritativeHistory;
383
+ private readAuthoritativeHistory;
395
384
  private replaceFromHistory;
396
385
  private invalidateOlderPaging;
397
386
  private beginCommandRecovery;
@@ -399,5 +388,4 @@ export declare class AgentSession {
399
388
  private flushBufferedCommands;
400
389
  private seedToolCallDeliveryBaseline;
401
390
  private ensureJoined;
402
- private ensureIdleBeforeSend;
403
391
  }
@@ -1,4 +1,4 @@
1
- import type { McpSourceConfig } from "../resources/sessions";
1
+ import type { CompactionPreference, McpSourceConfig } from "../resources/sessions";
2
2
  export type TextFile = {
3
3
  path: string;
4
4
  content: string;
@@ -31,6 +31,7 @@ export interface SessionConfig {
31
31
  enableThinking?: boolean;
32
32
  memoryEnabled?: boolean;
33
33
  compactionRatio?: number;
34
+ compactionPreference?: CompactionPreference;
34
35
  env?: Record<string, string>;
35
36
  /** Disable tools or an entire platform domain, e.g. ["platform:schedule"]. */
36
37
  disableTools?: string[];
@@ -1,9 +1,15 @@
1
1
  import type { RawEvent } from "../shared/projection";
2
2
  /** Shared by full and status subscriptions. UI sequence and run_id are unrelated. */
3
3
  export declare class LogCursor {
4
+ private started;
4
5
  private sequence;
5
6
  private epoch;
6
7
  private readonly deltas;
8
+ /** Seed only a fresh instance; reconnect/live delivery always owns its cursor. */
9
+ seed(snapshot?: {
10
+ afterLogSeq: number;
11
+ epoch: number;
12
+ }): void;
7
13
  subscription(): {
8
14
  after_log_seq?: number;
9
15
  };
@@ -1,3 +1,4 @@
1
+ import type { ContextAttachment } from "./schemas/context-attachments";
1
2
  import type { BladeClient } from "./blade-client";
2
3
  export interface ProviderTool {
3
4
  name: string;
@@ -30,6 +31,16 @@ export interface ToolProviderOptions {
30
31
  /** Secret bound to the session's mcp_sources bearer_token. */
31
32
  capability: string;
32
33
  tools: ProviderTool[];
34
+ /** Read current business data for a frozen input selection over this same RPC connection. */
35
+ getContext?: (arguments_: Record<string, unknown>, context: {
36
+ sessionId: string;
37
+ signal: AbortSignal;
38
+ executionId?: string;
39
+ requestId?: string;
40
+ receivedAt?: string;
41
+ timeZone?: string;
42
+ previous?: Record<string, Record<string, unknown>>;
43
+ }) => ContextAttachment[] | Promise<ContextAttachment[]>;
33
44
  onError?: (error: Error) => void;
34
45
  }
35
46
  /** Backend-only outbound connection. Reconnects registrations, never tool calls. */
@@ -1,3 +1,4 @@
1
+ import type { CompactionPreference } from "../resources/sessions";
1
2
  export interface ExistingSolutionRef {
2
3
  kind: "existing";
3
4
  solutionId: string;
@@ -12,6 +13,7 @@ export type SolutionRef = ExistingSolutionRef | PreparedSolutionAsset;
12
13
  export interface SessionProfile {
13
14
  solution?: SolutionRef;
14
15
  model?: string;
16
+ compactionPreference?: CompactionPreference;
15
17
  compactionRatio?: number;
16
18
  enableThinking?: boolean;
17
19
  memoryEnabled?: boolean;