Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/monorepo",
"version": "0.11.1",
"version": "0.12.0",
"private": true,
"type": "module",
"packageManager": "pnpm@10.23.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-cli/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-cli",
"version": "0.11.1",
"version": "0.12.0",
"description": "Product-neutral command line for a Steerable host. Products supply the bin name and brand.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-client/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-client",
"version": "0.11.1",
"version": "0.12.0",
"description": "In-process client for a Steerable host: HTTP-shaped requests, turn streams, and approval replies.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-harness/py/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "steerable-agent-harness"
version = "0.11.1"
version = "0.12.0"
description = "Steerable harness helpers for Python"
license = { text = "Apache-2.0" }
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-harness/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-harness",
"version": "0.11.1",
"version": "0.12.0",
"description": "Steerable framework Tier 2 \u2014 TypeScript facade over the Python harness (policy, budget, retry, completion, tracing) used for cross-language conformance tests. Production code should depend on the Python harness.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-protocol/py/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "steerable-agent-protocol"
version = "0.11.1"
version = "0.12.0"
description = "Steerable protocol schemas for Python"
license = { text = "Apache-2.0" }
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-protocol/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-protocol",
"version": "0.11.1",
"version": "0.12.0",
"description": "Steerable framework Tier 1 \u2014 wire-format types (SSEEvent, ChatMessage, ToolCall, ToolResult, AgentSession, HarnessTrace, sidecar JSON-RPC) shared by every Steerable client and server.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-runtime/py/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "steerable-agent-runtime"
version = "0.11.1"
version = "0.12.0"
description = "Steerable agent runtime: LLM, tool, storage, and transport adapters."
license = { text = "Apache-2.0" }
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-runtime/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-runtime",
"version": "0.11.1",
"version": "0.12.0",
"description": "Steerable framework \u2014 official TypeScript production runtime. Owns the embedded Python sidecar lifecycle (spawn / ready handshake / health / bounded auto-restart / graceful drain) and exposes the CoreLoop-level API over the sidecar JSON-RPC surface. There is no TS CoreLoop; this package drives the same Rust CoreLoop the server uses (via the Python sidecar facade), so cross-language conformance holds by construction.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-shell/tauri/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-shell-tauri",
"version": "0.11.1",
"version": "0.12.0",
"description": "Reusable Tauri Rust host source for @steerable/agent-shell",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-shell/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-shell",
"version": "0.11.1",
"version": "0.12.0",
"description": "Steerable framework \u2014 product-neutral Node HostRuntime and headless HTTP server shared by Tauri desktop and browser deployments; scenario packs extend it through @steerable/pack-sdk.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
32 changes: 29 additions & 3 deletions packages/agent-shell/ts/src/local-backend/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
streamCoreLoopTurn,
toTurnTool,
type CoreLoopToolAction,
type CoreLoopTurnOutcome,
type SkillTurnContext,
type StreamCoreLoopTurnOptions,
type TurnFailureInfo,
Expand Down Expand Up @@ -2739,6 +2740,9 @@ export class LocalBackendRouter {
* - 同步真实 messageId:`data: {"type":"message_id","messageId":"..."}`
* - 工具执行结果(无需用户确认):`data: {"type":"executed_actions","actions":[...]}`
* - 回合产物文件列表(仅非空时发,在 message_id 之前):`data: {"type":"turn_files","files":[...]}`
* - 回合账单(仅有时发,在 message_id 之前):`data: {"type":"turn_usage","usage":{...}}`
* 与 `turn_files` 同批归档:前端按 message_id 把它挂到落库消息上,刷新后
* 从 `messageMetadata.usage` 水合。整轮总计与子代理分项只在这一次出现。
* - 错误:保留 `event:error` + `data: {"message":"..."}`(前端会忽略,但日志/未来 UI 用)
* - 结束:标准 SSE `[DONE]` 串。
*/
Expand Down Expand Up @@ -4397,6 +4401,13 @@ export class LocalBackendRouter {
// `turn_active` marker survives — that marker is exactly what
// `detectInterruptedTurn` reads to offer "continue" on the next open.
let sidecarLost = false;
// R6: the turn's bill, lifted out of `driveWithAutoContinue` so the
// assistant row and the `turn_usage` event can carry it. It holds the
// LAST pass's figures: the turn total already lives in `usage_events`
// (the router writes one row per pass) and this is the per-turn view the
// message shows — a resumed pass re-reads what the previous one left, so
// summing passes here would double-count.
let turnUsage: CoreLoopTurnOutcome['usage'];
// Every pass records its own sidecar trace; all of them are persisted
// against the one assistant message this turn produces.
const passTraceIds: string[] = [];
Expand Down Expand Up @@ -4707,9 +4718,10 @@ export class LocalBackendRouter {
turnPasses += 1;
// W6-9 用量归因:落一条 chat 用量事件(含成本估算,无单价模型 costUsd=null)。
// 每趟各落一条——续跑的花费是真实发生的,不该被合并掉。
// R5:子代理的花费进同一条记录(父级 + children[]),而不是散成
// 多条——一次回合的成本归因必须能一眼加总。外部引擎子代理不报
// token,此时 usage_note='partial',不把缺失当零。
// R5: 子代理的花费进同一条记录。注意 `usage.totalTokens` 与
// `childTotalTokens` 是**两份并列**的账单(父级 / 子代理),不是
// 「总计与其中一部分」,所以相加才是整轮成本。外部引擎子代理报
// 不出 token,此时 usage_note='partial',不把缺失当零。
if (outcome.usage) {
try {
await this.store.recordUsageEvent({
Expand Down Expand Up @@ -4745,6 +4757,7 @@ export class LocalBackendRouter {
outcomeTraceId = finalOutcome.traceId;
autoContinuations = finalContinuations;
sidecarLost = finalOutcome.sidecarLost === true;
turnUsage = finalOutcome.usage;
// 干净失败的趟(sidecar 正常收流但 status=failed,如 LLM 401/超时)
// 不走下面的 catch——这里补发 error 事件,否则前端只渲染一条空消息,
// 用户完全看不到失败原因。
Expand Down Expand Up @@ -4892,6 +4905,11 @@ export class LocalBackendRouter {
...(durationMs != null ? { durationMs } : {}),
...(autoContinuations > 0 ? { autoContinuations } : {}),
...(turnFiles.length > 0 ? { turnFiles } : {}),
// R6: the turn's bill, kept on the row so a replayed message shows
// the same figures the live turn did — the child rows only carry
// their own slice, and the per-turn total is not derivable from
// them (the parent's own spend is not in any child).
...(turnUsage ? { usage: turnUsage } : {}),
...(failureInfo ? { failure: failureInfo } : {}),
})
);
Expand Down Expand Up @@ -5010,6 +5028,14 @@ export class LocalBackendRouter {
if (turnFiles.length > 0) {
emit(this.sseData({ type: 'turn_files', files: turnFiles }));
}
// R6: the turn's bill, emitted just before `message_id` so it archives
// with the rest of the turn's queues. This is the only place the parent's
// own spend and the children's share appear together — the child rows
// carry only their own slice, so a host that wants "what did this turn
// cost, and how much of it was sub-agents" cannot add them up itself.
if (turnUsage) {
emit(this.sseData({ type: 'turn_usage', usage: turnUsage }));
}
if (assistant) {
emit(this.sseData({ type: 'message_id', messageId: assistant.id }));
}
Expand Down
74 changes: 74 additions & 0 deletions packages/agent-shell/ts/tests/local-backend/router-stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1928,6 +1928,80 @@ describe('回合产物文件列表', () => {
}
});

// -------------------------------------------------------------------------
// R6 回合账单(turn_usage)
// -------------------------------------------------------------------------

it('回合账单经 turn_usage 事件下发(先于 message_id)并落 metadata', async () => {
const { dir, chat, toolRouter } = await seedProjectChat();
try {
installStream(
(opts) => {
opts.onText('做完了');
},
{
status: 'completed',
usage: {
promptTokens: 4000,
completionTokens: 1000,
totalTokens: 5000,
cachedPromptTokens: 1200,
childPromptTokens: 2400,
childCompletionTokens: 600,
childTotalTokens: 3000,
unknownUsageChildren: 1,
},
},
);
const cap = makeEmitCapture();
await makeRouter({ toolRouter }).handleStream(
{ method: 'POST', path: `/api/v2/chats/${chat.id}/send`, body: { message: '派活' } },
cap.emit,
);

const usageEvents = cap.byType('turn_usage');
expect(usageEvents).toHaveLength(1);
expect((usageEvents[0].data as { usage: { totalTokens: number } }).usage.totalTokens).toBe(5000);

// 顺序约定与 turn_files 一致:先于 message_id,前端按 message_id 归档。
const types = cap
.events()
.map((c) => (typeof c.data === 'object' && c.data !== null ? (c.data as { type?: string }).type : null));
expect(types.indexOf('turn_usage')).toBeLessThan(types.indexOf('message_id'));

// 落库,刷新后水合到同一条消息上。
const assistant = (await h.store.listMessages(chat.id, 10))[0];
const metadata = JSON.parse(assistant.messageMetadata!);
expect(metadata.usage.totalTokens).toBe(5000);
expect(metadata.usage.childTotalTokens).toBe(3000);
// 外部引擎子代理报不出 token,这个计数是「合计只是下限」的唯一依据。
expect(metadata.usage.unknownUsageChildren).toBe(1);
} finally {
await fs.rm(dir, { recursive: true, force: true });
}
});

it('回合没有账单时不发 turn_usage,metadata 不带 usage', async () => {
const { dir, chat, toolRouter } = await seedProjectChat();
try {
installStream((opts) => {
opts.onText('没有用量的路径');
});
const cap = makeEmitCapture();
await makeRouter({ toolRouter }).handleStream(
{ method: 'POST', path: `/api/v2/chats/${chat.id}/send`, body: { message: '跑一下' } },
cap.emit,
);

expect(cap.byType('turn_usage')).toHaveLength(0);
const assistant = (await h.store.listMessages(chat.id, 10))[0];
const metadata = JSON.parse(assistant.messageMetadata!);
expect(metadata.usage).toBeUndefined();
} finally {
await fs.rm(dir, { recursive: true, force: true });
}
});

it('未绑定项目的会话没有扫描根,不产事件', async () => {
const chat = await seedChat();
installStream((opts) => opts.onText('纯聊天'));
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-shell/web/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-shell-web",
"version": "0.11.1",
"version": "0.12.0",
"type": "module",
"description": "Steerable framework \u2014 product-neutral renderer SPA source for @steerable/agent-shell (React + Vite). Consumed by product web entry points via the `@/` alias (anchored at this package's src/) and the createProductViteConfig factory. Published as a source package (src/), plus the compiled vite.base config factory (vite.base.js + .d.ts) for Node-side config loading.",
"license": "Apache-2.0",
Expand Down
10 changes: 10 additions & 0 deletions packages/agent-shell/web/src/components/chat/AssistantMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import type { TurnBlock } from './turn-timeline';
import { TurnProcessGroup } from './TurnProcessGroup';
import { TurnFilesCard } from './TurnFilesCard';
import type { TurnFile } from './turn-files';
import type { TurnUsage } from './turn-usage';
import { stripNextStepsTags } from './next-steps-tags';
import {
formatTokenSpeed,
Expand Down Expand Up @@ -151,6 +152,13 @@ interface AssistantMessageProps {
* 气泡之下,点击用系统默认应用打开。空/undefined = 不渲染。
*/
turnFiles?: TurnFile[];
/**
* R6:本回合的账单(local-backend 把 sidecar 的 `stream.done.usage` 经
* `turn_usage` SSE + messageMetadata.usage 落库)。面板据此显示「这一轮
* 花了多少、其中子代理占多少」;父级自己的花费不在任何子代理行里,
* 所以这份数据没有替代品。
*/
turnUsage?: TurnUsage;
/**
* 分享当前对话(截图复制到剪贴板)。只传给最近一条助手消息,画在时间戳
* 行上,跟复制 / 重新生成同一排。
Expand Down Expand Up @@ -458,6 +466,7 @@ export function AssistantMessage({
durationMs,
llmSpeed,
turnFiles,
turnUsage,
onShare,
onInspectTask,
onContinueChild,
Expand Down Expand Up @@ -555,6 +564,7 @@ export function AssistantMessage({
chatId={chatId}
onInspectTask={onInspectTask}
orchestrationChildren={orchestrationChildren}
turnUsage={turnUsage}
onContinueChild={onContinueChild}
onStopChild={onStopChild}
emptyFallback={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type { InspectTaskInput } from './executed-actions-model';
import type { ChildInfo } from './OrchestrationChildrenCard';
import type { TurnBlock } from './turn-timeline';
import type { TurnFile } from './turn-files';
import type { TurnUsage } from './turn-usage';
import type { RetryState } from './RetryStatus';
import type { TurnFailureCardProps } from './TurnFailureCard';
import type { LlmSpeedSnapshot } from './process-status';
Expand Down Expand Up @@ -117,6 +118,10 @@ export interface LocalChatPanelProps {
turnFilesByMessageId?: Record<string, TurnFile[]>;
/** 当轮产物文件(流尾声到达、尚未归档到落库 id 的尾部消息用)。 */
currentTurnFiles?: TurnFile[];
/** R6 回合账单(按落库消息 id 键控),转发给 MessageList。 */
turnUsageByMessageId?: Record<string, TurnUsage>;
/** 当轮账单:与 currentTurnFiles 同款尾部回退。 */
currentTurnUsage?: TurnUsage;
/** P3.1: in-flight child agents + per-message reconciliation map. */
currentTurnChildren?: ChildInfo[];
orchestrationChildrenByMessageId?: Record<string, ChildInfo[]>;
Expand Down Expand Up @@ -206,6 +211,8 @@ export function LocalChatPanel({
llmSpeedByMessageId,
turnFilesByMessageId,
currentTurnFiles,
turnUsageByMessageId,
currentTurnUsage,
currentTurnChildren,
orchestrationChildrenByMessageId,
currentRound,
Expand Down Expand Up @@ -526,6 +533,8 @@ export function LocalChatPanel({
llmSpeedByMessageId={llmSpeedByMessageId}
turnFilesByMessageId={turnFilesByMessageId}
currentTurnFiles={currentTurnFiles}
turnUsageByMessageId={turnUsageByMessageId}
currentTurnUsage={currentTurnUsage}
currentTurnChildren={currentTurnChildren}
orchestrationChildrenByMessageId={orchestrationChildrenByMessageId}
currentRound={currentRound}
Expand Down
18 changes: 18 additions & 0 deletions packages/agent-shell/web/src/components/chat/MessageList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type { ChildInfo } from './OrchestrationChildrenCard';
import type { ChatMode } from './ChatInput';
import type { TurnBlock } from './turn-timeline';
import { followedPreviewPath, type TurnFile } from './turn-files';
import type { TurnUsage } from './turn-usage';
import { publishConversationPreview } from '@/layouts/conversation-preview';
import { inferDurationMs, readPersistedDurationMs } from './elapsed';
import type { LlmSpeedSnapshot } from './process-status';
Expand Down Expand Up @@ -138,6 +139,13 @@ interface MessageListProps {
* 与 currentTurnActions 同款尾部回退。
*/
currentTurnFiles?: TurnFile[];
/**
* R6: 每回合的账单,按落库消息 id 键控(与水合/归档同 turnFiles 一路)。
* 这是唯一同时含父级与子代理的两段数字的地方——面板行内只有子代理那一份。
*/
turnUsageByMessageId?: Record<string, TurnUsage>;
/** 当轮账单:与 currentTurnFiles 同款尾部回退。 */
currentTurnUsage?: TurnUsage;
/**
* Tool calls accumulated for the in-flight assistant message that the
* backend hasn't assigned a DB id to yet. Rendered under the latest
Expand Down Expand Up @@ -219,6 +227,8 @@ export function MessageList({
llmSpeedByMessageId,
turnFilesByMessageId,
currentTurnFiles,
turnUsageByMessageId,
currentTurnUsage,
currentTurnChildren,
orchestrationChildrenByMessageId,
currentRound,
Expand Down Expand Up @@ -513,6 +523,13 @@ export function MessageList({
const turnFiles = persistedTurnFiles
?? (isTurnFilesTail ? currentTurnFiles : undefined);

// R6: 同 turnFiles 的尾部回退。区别是它没有「非空才算」
// 的条件——一份全零的账单仍然说明这一轮跑过。
const persistedTurnUsage = turnUsageByMessageId?.[message.id];
const isTurnUsageTail = isLast && currentTurnUsage !== undefined;
const turnUsage =
persistedTurnUsage ?? (isTurnUsageTail ? currentTurnUsage : undefined);

const metadataJson =
typeof message.messageMetadata === 'string'
? message.messageMetadata
Expand Down Expand Up @@ -567,6 +584,7 @@ export function MessageList({
durationMs={durationMs}
llmSpeed={llmSpeed}
turnFiles={turnFiles}
turnUsage={turnUsage}
onShare={message.id === lastAssistantId ? onShare : undefined}
onInspectTask={onInspectTask}
onContinueChild={onContinueChild}
Expand Down
Loading
Loading