@xiaozhiclaw/qlogicagent-core 0.1.6 → 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.
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Pure Agent types with zero I/O framework dependencies.
3
+ *
4
+ * Wire-level types (ChatMessage, ToolDefinition) are canonical in
5
+ * contracts/. This file re-exports them and adds
6
+ * execution configuration supplied by the product.
7
+ */
8
+ import type { HookRegistry } from "../contracts/hooks.js";
9
+ import type { WireTokenUsage } from "../contracts/usage.js";
10
+ import type { AccumulatedToolCall, LLMChunk, LLMRequest, LLMTransport } from "../runtime/ports/index.js";
11
+ import type { ChatMessage as WireChatMessage, ChatMessageRole as WireChatMessageRole, ThinkingBlock as WireThinkingBlock, ToolCallMessage as WireToolCallMessage, ToolDefinition as WireToolDefinition } from "../contracts/chat.js";
12
+ import type { ToolCallExecutionEvidence } from "../contracts/tool-execution-evidence.js";
13
+ export type ChatMessageRole = WireChatMessageRole;
14
+ export type ThinkingBlock = WireThinkingBlock;
15
+ export type ToolCallMessage = WireToolCallMessage;
16
+ export type ChatMessage = WireChatMessage;
17
+ export type { AccumulatedToolCall, LLMChunk, LLMRequest, LLMTransport, };
18
+ export type ToolDefinition = WireToolDefinition;
19
+ /**
20
+ * Token usage unified with WireTokenUsage from contracts.
21
+ * No more internal/wire split: all code uses the same field names
22
+ * (inputTokens, outputTokens, reasoningTokens, cacheRead, cacheWrite).
23
+ */
24
+ export type TokenUsage = WireTokenUsage;
25
+ export type { TurnEvent, } from "../contracts/turn-event.js";
26
+ /** Observable reason why the provider loop started another inference round. */
27
+ export type ToolLoopTransition = {
28
+ reason: "reactive_compact_retry";
29
+ } | {
30
+ reason: "next_turn";
31
+ };
32
+ /** Terminal exit reasons from the tool loop. */
33
+ export type ToolLoopTerminal = {
34
+ reason: "completed";
35
+ } | {
36
+ reason: "aborted";
37
+ } | {
38
+ reason: "prompt_too_long";
39
+ } | {
40
+ reason: "image_error";
41
+ } | {
42
+ reason: "model_error";
43
+ error?: unknown;
44
+ } | {
45
+ reason: "max_turns";
46
+ } | {
47
+ reason: "budget_exhausted";
48
+ } | {
49
+ reason: "tool_loop_limit";
50
+ } | {
51
+ reason: "stop_hook_prevented";
52
+ } | {
53
+ reason: "hook_stopped";
54
+ };
55
+ export interface TurnRequest {
56
+ turnId: string;
57
+ sessionId: string;
58
+ continuation?: {
59
+ completedRounds: number;
60
+ usage: TokenUsage;
61
+ };
62
+ messages: ChatMessage[];
63
+ /** Full registered tool surface before per-turn policy filtering. */
64
+ availableTools?: ToolDefinition[];
65
+ /** Exact tool names whose full parameter schemas are loaded only after Agent selection. */
66
+ deferredToolNames?: string[];
67
+ /**
68
+ * Session-owned names whose deferred schemas the Agent already selected and loaded.
69
+ * The loop reconciles this set against the current authoritative tool snapshot and
70
+ * adds newly loaded names; it never stores schema content or capability authority.
71
+ */
72
+ loadedDeferredToolNames?: Set<string>;
73
+ tools: ToolDefinition[];
74
+ /**
75
+ * Live tool-manifest rebuild, consulted each loop iteration (turnCount > 1).
76
+ * It may retract or restore tools from the turn's initial authoritative snapshot.
77
+ * Newly registered tools become visible on the next user turn so they cannot bypass
78
+ * the complete directory, schema deferral, or permission snapshot for this turn.
79
+ */
80
+ refreshTools?: () => ToolDefinition[];
81
+ /**
82
+ * Drain user guidance queued mid-turn (运行中引导). Consulted at the top of every
83
+ * tool-loop round; returned strings become user messages before the next LLM call.
84
+ */
85
+ drainPendingGuidance?: () => string[];
86
+ /**
87
+ * Drain bounded background-task results for this session. Consulted between
88
+ * rounds so completed product jobs can rejoin the parent without model polling.
89
+ */
90
+ drainPendingTaskNotifications?: () => string[];
91
+ /**
92
+ * Route media a tool returns that the MAIN model can't consume (e.g. `read` returning an image
93
+ * for a text-only model) to the understanding model; folds the description into the message text
94
+ * and drops the raw media. Forwarded to the tool loop; mutates the message in place.
95
+ */
96
+ sanitizeToolResultMedia?: (message: Record<string, unknown>) => Promise<void>;
97
+ systemPrompt?: string;
98
+ config?: TurnConfig;
99
+ }
100
+ export interface TurnConfig {
101
+ /** Model id, e.g. "deepseek-v4-flash" */
102
+ model?: string;
103
+ /** Inference credential injected by the product service. */
104
+ apiKey?: string;
105
+ /** Explicit max tool-call rounds per turn. Undefined means unbounded. */
106
+ maxRounds?: number;
107
+ /** Temperature override */
108
+ temperature?: number;
109
+ /** Context window size in tokens (for turn-loop-guard budget checks) */
110
+ contextWindowTokens?: number;
111
+ /** Max output tokens for current model */
112
+ maxOutputTokens?: number;
113
+ /** Tool choice strategy: "auto" (default), "none", "required" */
114
+ toolChoice?: "auto" | "none" | "required";
115
+ /** Max turns (tool loop iterations). 0 or undefined = use maxRounds. */
116
+ maxTurns?: number;
117
+ /** Max concurrent tool executions (0 = unlimited). */
118
+ maxConcurrentTools?: number;
119
+ /** Model requires streaming; disable transport-level non-streaming fallback. */
120
+ streamRequired?: boolean;
121
+ /** Reasoning effort for models that support it (GPT-5.x, o-series). */
122
+ reasoning?: {
123
+ effort: "auto" | "minimal" | "low" | "medium" | "high" | "xhigh";
124
+ includeEncryptedReasoning?: boolean;
125
+ };
126
+ /** Prompt cache bucketing key used instead of the provider-level `user` field. */
127
+ promptCacheKey?: string;
128
+ /** Prompt cache retention: "in_memory" (5-10min) or "24h". */
129
+ promptCacheRetention?: "in_memory" | "24h";
130
+ /** Service tier selected by the product model configuration. */
131
+ serviceTier?: "auto" | "default" | "flex" | "priority";
132
+ /** Max genuinely executable tool calls accepted from one model response; resets each round. */
133
+ maxToolCalls?: number;
134
+ /** Disable parallel tool calling (force sequential). */
135
+ parallelToolCalls?: boolean;
136
+ /** Text output verbosity hint: "low", "medium", "high". */
137
+ textVerbosity?: "low" | "medium" | "high";
138
+ }
139
+ export type { ToolCallExecutionEvidence };
140
+ /**
141
+ * ToolInvoker: injected execution boundary owned by the SaaS product.
142
+ */
143
+ export interface ToolInvoker {
144
+ invoke(turnId: string, name: string, args: string, signal?: AbortSignal, invocation?: {
145
+ callId: string;
146
+ sessionId: string;
147
+ round: number;
148
+ }): Promise<import("../contracts/tool-result.js").ToolResult>;
149
+ }
150
+ /**
151
+ * AgentLogger: structured logging interface.
152
+ * The SaaS service injects its own logging implementation.
153
+ */
154
+ export interface AgentLogger {
155
+ info(message: string): void;
156
+ info(obj: Record<string, unknown>, message: string): void;
157
+ warn(message: string): void;
158
+ warn(obj: Record<string, unknown>, message: string): void;
159
+ error(message: string): void;
160
+ error(obj: Record<string, unknown>, message: string): void;
161
+ debug(message: string): void;
162
+ debug(obj: Record<string, unknown>, message: string): void;
163
+ }
164
+ export type { HookRegistry };
@@ -0,0 +1,150 @@
1
+ /** Internal SaaS model messages and product-supplied tool metadata. */
2
+ /**
3
+ * Versioned, model-readable capability semantics supplied by a tool owner.
4
+ *
5
+ * These fields describe meaning rather than forming a closed routing taxonomy:
6
+ * selection remains a semantic model decision over the user's whole request.
7
+ */
8
+ export interface SemanticToolCapability {
9
+ schemaVersion: 1;
10
+ summary: string;
11
+ scenarios?: string[];
12
+ prerequisites?: string[];
13
+ effects?: string[];
14
+ modalities?: string[];
15
+ constraints?: string[];
16
+ }
17
+ export type ChatMessageRole = "system" | "user" | "assistant" | "tool";
18
+ export type ContextAnchorCategory = "objective" | "acceptance" | "decision" | "constraint" | "task" | "blocker" | "artifact";
19
+ export interface ContextAnchor {
20
+ category: ContextAnchorCategory;
21
+ value: string;
22
+ }
23
+ /**
24
+ * Canonical Goal/thread facts supplied by the product for one Agent turn.
25
+ * This is context for Agent-local compaction, never a second Goal state store.
26
+ */
27
+ export interface ContextEnvelope {
28
+ threadId: string;
29
+ turnId: string;
30
+ itemId: string;
31
+ anchors: ContextAnchor[];
32
+ }
33
+ /** Thinking block from Anthropic Messages API (DeepSeek, Claude, etc.) */
34
+ export interface ThinkingBlock {
35
+ thinking: string;
36
+ signature: string;
37
+ }
38
+ /** Tool call within an assistant message. */
39
+ export interface ToolCallMessage {
40
+ id: string;
41
+ type: "function";
42
+ function: {
43
+ name: string;
44
+ arguments: string;
45
+ };
46
+ }
47
+ /** Product-supplied model conversation; no local session store. */
48
+ export interface ChatMessage {
49
+ role: ChatMessageRole;
50
+ content: string | null;
51
+ /** Canonical coordinates and durable facts used by Agent-local compaction receipts. */
52
+ threadId?: string;
53
+ turnId?: string;
54
+ itemId?: string;
55
+ contextAnchors?: ContextAnchor[];
56
+ /** Derived projection of product facts, replaceable by the context transform. */
57
+ contextProjection?: "facts";
58
+ /** For assistant messages with tool calls. */
59
+ tool_calls?: ToolCallMessage[];
60
+ /** For tool result messages. */
61
+ tool_call_id?: string;
62
+ /** For tool result messages — tool name. */
63
+ name?: string;
64
+ /** Tool-result error flag propagated so every transport can signal failure to the model. */
65
+ is_error?: boolean;
66
+ /** OpenAI-chat reasoning content (GLM/DeepSeek) carried across tool-call rounds on the assistant message. */
67
+ reasoning_content?: string;
68
+ /** Anthropic tool_reference metadata for tool_result blocks. */
69
+ toolReferences?: string[];
70
+ /** Anthropic thinking blocks — must be passed back to API in subsequent requests. */
71
+ thinkingBlocks?: ThinkingBlock[];
72
+ /** Image URLs for vision-capable models. */
73
+ imageUrls?: string[];
74
+ /** Exact MCP content blocks retained alongside the model-compatible text/media projection. */
75
+ contentBlocks?: import("./tool-result.js").ToolResult["contentBlocks"];
76
+ /** Exact standard MCP structuredContent field. */
77
+ structuredContent?: Record<string, unknown>;
78
+ /** Exact standard MCP result `_meta` field. */
79
+ mcpMeta?: Record<string, unknown>;
80
+ /** Exact standard MCP result isError field, including explicit false. */
81
+ mcpIsError?: boolean;
82
+ /** Image detail level: 'auto' | 'low' | 'high' | 'xhigh'. */
83
+ imageDetail?: "auto" | "low" | "high" | "xhigh";
84
+ /** Max image pixels budget (Volcengine image_pixel_limit). */
85
+ imagePixelLimit?: {
86
+ minPixels?: number;
87
+ maxPixels?: number;
88
+ };
89
+ /** Video URLs for video-understanding models. */
90
+ videoUrls?: string[];
91
+ /** Per-video fps for video understanding (0.2-5, default 1). */
92
+ videoFps?: number;
93
+ /** Audio format hint: 'mp3' | 'wav' | 'aac' | 'm4a'. */
94
+ audioFormat?: "mp3" | "wav" | "aac" | "m4a";
95
+ /** Audio URLs for audio-understanding models. */
96
+ audioUrls?: string[];
97
+ /** Pre-uploaded file IDs for document/media understanding. */
98
+ fileIds?: Array<{
99
+ id: string;
100
+ mimeType?: string;
101
+ size?: number;
102
+ }>;
103
+ /** UI-facing structured blocks persisted with transcripts; ignored by model transports. */
104
+ blocks?: Array<Record<string, unknown>>;
105
+ /**
106
+ * Structured attachment entries (product UI: element/browserView/file/image/…),
107
+ * persisted with the transcript and surfaced to the UI as chips. Opaque to the agent and ignored
108
+ * by model transports — the model-facing context is derived product-side and appended transiently
109
+ * to the LLM message, never stored here.
110
+ */
111
+ attachmentEntries?: Array<Record<string, unknown>>;
112
+ }
113
+ export type ToolCapabilityCategory = "business" | "skill" | "mcp" | "orchestration";
114
+ export interface LocalizedToolText {
115
+ key: string;
116
+ fallback: string;
117
+ values?: Partial<Record<string, string>>;
118
+ }
119
+ /**
120
+ * Canonical identity authored by the execution owner. Third-party tools do not
121
+ * supply this object: the product derives it while projecting the tool.
122
+ */
123
+ export interface ToolIdentity {
124
+ schemaVersion: 1;
125
+ wireName: string;
126
+ logicalName: string;
127
+ family: "business" | "skill" | "mcp" | "orchestration";
128
+ owner: "product";
129
+ serverId?: string;
130
+ capabilityId: string;
131
+ }
132
+ /** Product-supplied tool definition; execution remains product-owned. */
133
+ export interface ToolDefinition {
134
+ type: "function";
135
+ function: {
136
+ name: string;
137
+ description: string;
138
+ parameters?: Record<string, unknown>;
139
+ };
140
+ /** Product-supplied tool identity and execution metadata. */
141
+ meta?: {
142
+ identity?: ToolIdentity;
143
+ category?: ToolCapabilityCategory;
144
+ displayName?: LocalizedToolText;
145
+ displayDescription?: LocalizedToolText;
146
+ semanticCapability?: SemanticToolCapability;
147
+ /** Tool-specific deadline supplied by the product. */
148
+ executionTimeoutMs?: number;
149
+ };
150
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Hook system types for the Agent Runtime.
3
+ *
4
+ * Internal loop hooks allow injected middleware to observe execution
5
+ * at well-defined lifecycle points during session, turn, and tool execution.
6
+ */
7
+ /**
8
+ * All supported hook points in the Agent Runtime lifecycle.
9
+ */
10
+ export type HookPoint = "turn.submitted" | "turn.before_inference" | "turn.after_inference" | "turn.completed" | "turn.failed" | "tool.before_invoke" | "tool.after_invoke" | "tool.invoke_failed" | "context.before_compact" | "context.after_compact" | "stop" | "stop.failure";
11
+ export interface HookSessionContext {
12
+ sessionId: string;
13
+ }
14
+ export interface HookTurnContext extends HookSessionContext {
15
+ turnId: string;
16
+ executionId?: string;
17
+ rootExecutionId?: string;
18
+ }
19
+ export interface HookToolContext extends HookTurnContext {
20
+ callId: string;
21
+ toolName: string;
22
+ arguments?: Record<string, unknown>;
23
+ }
24
+ export interface HookStopContext extends HookSessionContext {
25
+ reason?: string;
26
+ error?: string;
27
+ }
28
+ export interface HookContextMap {
29
+ "turn.submitted": HookTurnContext & {
30
+ prompt?: string;
31
+ };
32
+ "turn.before_inference": HookTurnContext & {
33
+ model?: string;
34
+ messages?: unknown[];
35
+ };
36
+ "turn.after_inference": HookTurnContext & {
37
+ model?: string;
38
+ response?: unknown;
39
+ success?: boolean;
40
+ error?: string;
41
+ };
42
+ "turn.completed": HookTurnContext & {
43
+ outcomeId?: string;
44
+ prompt?: string;
45
+ response?: string;
46
+ };
47
+ "turn.failed": HookTurnContext & {
48
+ code?: string;
49
+ error?: string;
50
+ };
51
+ "tool.before_invoke": HookToolContext;
52
+ "tool.after_invoke": HookToolContext & {
53
+ result?: unknown;
54
+ ok: boolean;
55
+ };
56
+ "tool.invoke_failed": HookToolContext & {
57
+ error?: string;
58
+ };
59
+ "context.before_compact": HookTurnContext & {
60
+ tokenCount?: number;
61
+ messageCount?: number;
62
+ };
63
+ "context.after_compact": HookTurnContext & {
64
+ tokenCount?: number;
65
+ removedCount?: number;
66
+ };
67
+ "stop": HookStopContext;
68
+ "stop.failure": HookStopContext & {
69
+ errorDetails?: string;
70
+ };
71
+ }
72
+ /**
73
+ * Result of a hook handler invocation.
74
+ *
75
+ * - `continue`: proceed normally (optionally with modified context)
76
+ * - `abort`: stop execution (for "before" hooks only)
77
+ * - `skip`: skip this step but continue the overall flow
78
+ */
79
+ export interface HookResult<T = unknown> {
80
+ action: "continue" | "abort" | "skip" | "prevent";
81
+ /** Modified context to pass downstream (only for "continue") */
82
+ context?: T;
83
+ /** Reason for abort/skip/prevent (for logging) */
84
+ reason?: string;
85
+ }
86
+ /**
87
+ * A hook handler function.
88
+ *
89
+ * @param point - The hook point being invoked
90
+ * @param context - Event-specific context data
91
+ * @returns A HookResult or void (treated as "continue")
92
+ */
93
+ export type HookHandler<P extends HookPoint = HookPoint> = (point: P, context: HookContextMap[P]) => HookResult<HookContextMap[P]> | void | Promise<HookResult<HookContextMap[P]> | void>;
94
+ /**
95
+ * Hook registration entry.
96
+ */
97
+ export interface HookRegistration<P extends HookPoint = HookPoint> {
98
+ point: P;
99
+ handler: HookHandler<P>;
100
+ /** Priority (lower = earlier). Default: 100 */
101
+ priority?: number;
102
+ /** Optional label for debugging */
103
+ label?: string;
104
+ /**
105
+ * Critical hooks are part of the execution preflight. If they throw, the
106
+ * registry returns an abort result instead of treating the failure as a
107
+ * non-blocking observer error.
108
+ */
109
+ critical?: boolean;
110
+ }
111
+ /**
112
+ * Interface for a hook registry that manages hook handlers.
113
+ */
114
+ export interface HookRegistry {
115
+ register<P extends HookPoint>(registration: HookRegistration<P>): () => void;
116
+ invoke<P extends HookPoint>(point: P, context: HookContextMap[P]): Promise<HookResult<HookContextMap[P]>>;
117
+ }
@@ -0,0 +1,24 @@
1
+ import type { ToolIdentity } from "./chat.js";
2
+ export interface ToolCallExecutionEvidence {
3
+ sequence: number;
4
+ callId: string;
5
+ name: string;
6
+ identity: ToolIdentity;
7
+ status: "running" | "succeeded" | "failed" | "blocked";
8
+ arguments?: string;
9
+ error?: string;
10
+ failureKind?: "policy_blocked" | "semantic_quality_failed" | "timeout" | "mcp_start_failed" | "mcp_unavailable" | "tool_execution_failed";
11
+ }
12
+ export declare function classifyToolFailureKind(result: {
13
+ blocked?: boolean;
14
+ blockReason?: string;
15
+ error?: string;
16
+ details?: Record<string, unknown>;
17
+ }): ToolCallExecutionEvidence["failureKind"];
18
+ export declare function summarizeToolExecutionOutcomes(toolCalls: readonly Pick<ToolCallExecutionEvidence, "name" | "status">[], blockedToolCalls: readonly {
19
+ name: string;
20
+ reason: string;
21
+ }[]): {
22
+ failedTools: string[];
23
+ blockedTools: string[];
24
+ };
@@ -0,0 +1,13 @@
1
+ import type { AgentContentBlock } from "../embedded/content-blocks.js";
2
+ /** Original product result, including opaque standard MCP blocks and provenance. */
3
+ export interface ToolResult {
4
+ result: string;
5
+ error?: string;
6
+ toolReferences?: string[];
7
+ imageUrls?: string[];
8
+ contentBlocks?: Array<AgentContentBlock | Record<string, unknown>>;
9
+ structuredContent?: Record<string, unknown>;
10
+ mcpMeta?: Record<string, unknown>;
11
+ mcpIsError?: boolean;
12
+ details?: Record<string, unknown>;
13
+ }
@@ -0,0 +1,123 @@
1
+ import type { WireTokenUsage } from "./usage.js";
2
+ export type TurnEvent = {
3
+ type: "start";
4
+ turnId: string;
5
+ /**
6
+ * Effective caller max-rounds and per-model-round tool-call limit after provider
7
+ * normalization. A zero/absent round limit is unbounded; the tool-call limit resets
8
+ * for every model response and is not a cumulative turn execution budget.
9
+ */
10
+ effectiveMaxRounds?: number;
11
+ /** Maximum executable calls accepted from one model response. */
12
+ effectiveMaxToolCalls?: number;
13
+ } | {
14
+ type: "delta";
15
+ turnId: string;
16
+ text: string;
17
+ } | {
18
+ type: "tool_call";
19
+ turnId: string;
20
+ callId: string;
21
+ name: string;
22
+ displayName?: string;
23
+ arguments: string;
24
+ inputSummary?: string;
25
+ } | {
26
+ type: "end";
27
+ turnId: string;
28
+ content: string;
29
+ /** Adapter lifecycle only; it is not a semantic task-success claim. */
30
+ turnStatus?: "completed" | "stopped";
31
+ /** Task success remains unverified unless a higher-level product workflow proves it. */
32
+ taskOutcome?: "unverified";
33
+ usage?: WireTokenUsage;
34
+ model?: string;
35
+ provider?: string;
36
+ /** Per-turn recovery trace (action -> count); present only when recoveries fired. */
37
+ recoveryTrace?: Record<string, number>;
38
+ contentBlocks?: import("../embedded/content-blocks.js").AgentContentBlock[];
39
+ } | {
40
+ type: "error";
41
+ turnId: string;
42
+ error: string;
43
+ code?: string;
44
+ usage?: WireTokenUsage;
45
+ } | {
46
+ type: "tool_result";
47
+ turnId: string;
48
+ callId: string;
49
+ name: string;
50
+ ok: boolean;
51
+ error?: string;
52
+ outputPreview?: string;
53
+ durationMs?: number;
54
+ details?: Record<string, unknown>;
55
+ } | {
56
+ type: "tool_blocked";
57
+ turnId: string;
58
+ callId: string;
59
+ name: string;
60
+ reason: string;
61
+ } | {
62
+ type: "recovery";
63
+ turnId: string;
64
+ action: string;
65
+ detail?: string;
66
+ } | {
67
+ /**
68
+ * 作废本回合已发出但随后被丢弃的助手文本。
69
+ *
70
+ * 为什么不复用 `recovery`:recovery 同时覆盖"丢弃本轮文本"与"保留前缀并续写"两类
71
+ * (max_output_tokens 续写把上一轮 roundText 当作 assistant 前缀带进下一轮)。把它当作
72
+ * 统一作废信号会在最常见的长输出续写场景下错抹合法前缀,因此作废必须是独立事件。
73
+ *
74
+ * 语义:作废永远是**后缀截断**,截断点由 Agent 权威下发,消费端只执行不推断。
75
+ * 一个 turn 内只有一条线性文本流,因此不需要 roundId/segmentId 编号体系。
76
+ */
77
+ type: "text_rollback";
78
+ turnId: string;
79
+ /**
80
+ * 本 turn 保留的助手文本长度,单位 **UTF-16 code unit**,按全部已发出文本段的逻辑拼接计算
81
+ * (activity 等非文本段不计入长度,也不被截断删除)。
82
+ *
83
+ * 必须满足 `committedLength <= keepLength <= sentLength`:下界是已提交轮次的累计长度,
84
+ * 低于它会删掉早先轮次的合法过程性文本(那些文本不由 `turn.end.content` 覆盖,删了不会回来)。
85
+ * 重复下发同一 keepLength 必须幂等。
86
+ */
87
+ keepLength: number;
88
+ /** 供 UI 呈现"已重试/已重新生成"的轻量状态,以及诊断归因。 */
89
+ reason: string;
90
+ } | {
91
+ type: "tool_use_summary";
92
+ turnId: string;
93
+ telemetrySource?: "agent";
94
+ /** Versioned terminal ledger for per-call execution evidence. */
95
+ ledgerSchemaVersion: 5;
96
+ toolCalls: import("./tool-execution-evidence.js").ToolCallExecutionEvidence[];
97
+ availableToolNames: string[];
98
+ enabledToolNames: string[];
99
+ toolCallNames: string[];
100
+ blockedToolCalls: Array<{
101
+ name: string;
102
+ reason: string;
103
+ }>;
104
+ } | {
105
+ type: "lifecycle";
106
+ turnId: string;
107
+ kind: "context_compression";
108
+ status: string;
109
+ detail: string;
110
+ } | {
111
+ type: "reasoning_delta";
112
+ turnId: string;
113
+ text: string;
114
+ } | {
115
+ type: "annotations";
116
+ turnId: string;
117
+ annotations: Array<{
118
+ type: string;
119
+ url?: string;
120
+ title?: string;
121
+ [key: string]: unknown;
122
+ }>;
123
+ };
@@ -0,0 +1,27 @@
1
+ /** Token accounting returned by an Agent turn. */
2
+ export type WireUsageSource = "llmrouter.settlement" | "provider.reported" | "host.observed" | "estimated";
3
+ export interface WireUsageRecord {
4
+ schemaVersion: 1;
5
+ source: WireUsageSource;
6
+ requestIds: string[];
7
+ tokens: {
8
+ inputTokens?: number;
9
+ outputTokens?: number;
10
+ totalTokens?: number;
11
+ reasoningTokens?: number;
12
+ cacheReadTokens?: number;
13
+ cacheWriteTokens?: number;
14
+ };
15
+ cost?: {
16
+ currency: string;
17
+ amount: string;
18
+ };
19
+ }
20
+ export interface WireTokenUsage {
21
+ inputTokens: number;
22
+ outputTokens: number;
23
+ reasoningTokens?: number;
24
+ cacheRead?: number;
25
+ cacheWrite?: number;
26
+ records?: WireUsageRecord[];
27
+ }
@@ -0,0 +1,63 @@
1
+ import type { ToolDefinition } from "./contracts.js";
2
+ /** Versioned platform knowledge; enterprise data and permission facts stay product-owned. */
3
+ export interface BusinessAssistantContext {
4
+ module: {
5
+ id: string;
6
+ version: string;
7
+ fields: Record<string, unknown>[];
8
+ operations: Array<{
9
+ id: string;
10
+ description: string;
11
+ prerequisites: string[];
12
+ }>;
13
+ };
14
+ enterprise: {
15
+ configurationRevision: string;
16
+ configuration: Record<string, unknown>;
17
+ dataSources: Array<{
18
+ id: string;
19
+ state: "ready" | "missing" | "unavailable";
20
+ reference?: string;
21
+ }>;
22
+ };
23
+ employee: {
24
+ permissionRevision: string;
25
+ allowedOperations: string[];
26
+ };
27
+ knowledge: {
28
+ revision: string;
29
+ skill: string;
30
+ examples: Array<{
31
+ operation: string;
32
+ input: string;
33
+ expectedOutcome: string;
34
+ evidenceReference: string;
35
+ }>;
36
+ exceptions: Array<{
37
+ code: string;
38
+ handling: string;
39
+ }>;
40
+ };
41
+ }
42
+ export interface BusinessGoal {
43
+ id: string;
44
+ description: string;
45
+ criteria: Array<{
46
+ id: string;
47
+ description: string;
48
+ }>;
49
+ }
50
+ export interface BusinessGoalEvidence {
51
+ criteria: Array<{
52
+ id: string;
53
+ status: "satisfied" | "missing" | "failed";
54
+ references: string[];
55
+ }>;
56
+ }
57
+ export interface BusinessGoalOutcome extends BusinessGoalEvidence {
58
+ status: "satisfied" | "incomplete";
59
+ }
60
+ /** Validate the product's versioned context without choosing or narrowing its tools. */
61
+ export declare function validateBusinessAssistantContext(value: BusinessAssistantContext, tools: ToolDefinition[]): void;
62
+ export declare function validateBusinessGoal(goal: BusinessGoal): void;
63
+ export declare function verifyBusinessGoalEvidence(goal: BusinessGoal, evidence: BusinessGoalEvidence): BusinessGoalOutcome;