@steerable/agent-shell 0.9.2 → 0.10.1

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.
@@ -5,7 +5,13 @@ export declare function isProductApprovalEnabled(): boolean;
5
5
  export declare function resolveTurnApproval(storePath?: string): ReturnType<typeof buildHostApproval>;
6
6
  export declare function assertHostIpcAllowed(channel: string): void;
7
7
  export declare function resolveTurnChatMode(requested: unknown): ChatModeId;
8
- /** 解析当前产品是否启用多智能体编排六件套(STEERABLE_ORCHESTRATION 环境变量与回合 payload 优先)。 */
8
+ /**
9
+ * 解析当前产品是否启用多智能体编排六件套(STEERABLE_ORCHESTRATION 环境变量与回合 payload 优先)。
10
+ *
11
+ * `orchestration` 既接受布尔(旧客户端)也接受对象 `{enabled, maxDepth,
12
+ * maxParallel}`。对象形式是 R7 加上的:深度与并发是权限参数,用户在前端
13
+ * 设置页改的值必须真的到达 sidecar,否则界面上的数字是假的。
14
+ */
9
15
  export declare function resolveTurnOrchestration(payload?: Record<string, unknown>): {
10
16
  enabled: boolean;
11
17
  maxDepth: number;
@@ -32,27 +32,28 @@ export function assertHostIpcAllowed(channel) {
32
32
  export function resolveTurnChatMode(requested) {
33
33
  return clampChatMode(requested, resolveChatModes(getProductConfig().chatModes));
34
34
  }
35
- /** 解析当前产品是否启用多智能体编排六件套(STEERABLE_ORCHESTRATION 环境变量与回合 payload 优先)。 */
35
+ /**
36
+ * 解析当前产品是否启用多智能体编排六件套(STEERABLE_ORCHESTRATION 环境变量与回合 payload 优先)。
37
+ *
38
+ * `orchestration` 既接受布尔(旧客户端)也接受对象 `{enabled, maxDepth,
39
+ * maxParallel}`。对象形式是 R7 加上的:深度与并发是权限参数,用户在前端
40
+ * 设置页改的值必须真的到达 sidecar,否则界面上的数字是假的。
41
+ */
36
42
  export function resolveTurnOrchestration(payload) {
37
43
  if (process.env.STEERABLE_ORCHESTRATION === '0')
38
44
  return undefined;
39
45
  if (process.env.STEERABLE_ORCHESTRATION === '1') {
40
46
  return { enabled: true, maxDepth: 1, maxParallel: 4 };
41
47
  }
48
+ const readRequested = (value) => orchestrationFromValue(value);
42
49
  // 回合请求体优先(用户在前端设置中打开/关闭,随 metadata/payload 透传)
43
50
  if (payload) {
44
- if (payload.orchestration === false)
45
- return undefined;
46
- if (payload.orchestration === true) {
47
- return { enabled: true, maxDepth: 1, maxParallel: 4 };
51
+ if (payload.orchestration !== undefined) {
52
+ return readRequested(payload.orchestration);
48
53
  }
49
54
  const meta = payload.metadata;
50
- if (meta && typeof meta === 'object') {
51
- if (meta.orchestration === false)
52
- return undefined;
53
- if (meta.orchestration === true) {
54
- return { enabled: true, maxDepth: 1, maxParallel: 4 };
55
- }
55
+ if (meta && typeof meta === 'object' && meta.orchestration !== undefined) {
56
+ return readRequested(meta.orchestration);
56
57
  }
57
58
  }
58
59
  const config = getProductConfig().orchestration;
@@ -68,6 +69,38 @@ export function resolveTurnOrchestration(payload) {
68
69
  }
69
70
  return undefined;
70
71
  }
72
+ /**
73
+ * One `orchestration` value → the turn's settings.
74
+ *
75
+ * A boolean is the pre-R7 form and still means 1 / 4. An object is clamped to
76
+ * the ranges the settings page offers, because a value outside them would
77
+ * either be rejected by the sidecar or silently allow more nesting than the UI
78
+ * ever showed.
79
+ *
80
+ * @param value The payload's `orchestration` field.
81
+ * @returns The turn's settings, or undefined when the turn must not orchestrate.
82
+ */
83
+ function orchestrationFromValue(value) {
84
+ if (value === false)
85
+ return undefined;
86
+ if (value === true)
87
+ return { enabled: true, maxDepth: 1, maxParallel: 4 };
88
+ if (typeof value !== 'object' || value === null)
89
+ return undefined;
90
+ const config = value;
91
+ if (config.enabled === false)
92
+ return undefined;
93
+ return {
94
+ enabled: true,
95
+ maxDepth: clampInt(config.maxDepth, 1, 1, 3),
96
+ maxParallel: clampInt(config.maxParallel, 4, 1, 8),
97
+ };
98
+ }
99
+ function clampInt(value, fallback, min, max) {
100
+ if (typeof value !== 'number' || !Number.isFinite(value))
101
+ return fallback;
102
+ return Math.min(max, Math.max(min, Math.trunc(value)));
103
+ }
71
104
  export function isProductLlmLocked() {
72
105
  return !resolveSettingsChrome(getProductConfig().settings).llm;
73
106
  }
@@ -11,7 +11,7 @@
11
11
  * sidecar failed to start, the router fails loud with a 503 — there is no
12
12
  * in-process fallback loop or sidecar opt-out.
13
13
  */
14
- import type { SidecarChatStreamRequest, SidecarChildEvent, SidecarRawChunk, SidecarSupervisor } from '../sidecar/index.js';
14
+ import type { SidecarChatStreamRequest, SidecarChildEvent, SidecarChildUsage, SidecarRawChunk, SidecarStreamDone, SidecarSupervisor } from '../sidecar/index.js';
15
15
  import type { LlmMessage } from '../llm/types.js';
16
16
  export interface CoreLoopToolAction {
17
17
  id?: string;
@@ -71,7 +71,22 @@ export interface CoreLoopTurnOutcome {
71
71
  totalTokens: number;
72
72
  cachedPromptTokens?: number;
73
73
  costUsd?: number;
74
+ /**
75
+ * R5: the children's share of this turn, split per childId, and how many
76
+ * children reported nothing at all (external engines). Present only when
77
+ * the turn delegated.
78
+ */
79
+ childPromptTokens?: number;
80
+ childCompletionTokens?: number;
81
+ childTotalTokens?: number;
82
+ children?: SidecarChildUsage[];
83
+ unknownUsageChildren?: number;
74
84
  };
85
+ /**
86
+ * R5: the whole tree's spend against the turn's token limit. Absent when
87
+ * the host asked for no limit.
88
+ */
89
+ treeUsage?: SidecarStreamDone['treeUsage'];
75
90
  }
76
91
  /**
77
92
  * A6 分层披露:本轮技能目录的过滤上下文。sidecar 据此注入 catalog 层
@@ -363,6 +363,7 @@ export async function streamCoreLoopTurn(options) {
363
363
  reason: done.reason ?? (done.cancelled ? 'aborted_by_user' : undefined),
364
364
  traceId: done.traceId,
365
365
  usage: done.usage,
366
+ treeUsage: done.treeUsage,
366
367
  });
367
368
  },
368
369
  onChildEvent: (event) => {
@@ -887,6 +887,113 @@ export class LocalBackendRouter {
887
887
  data: { recordId, timeline: timelineFromHistoryEntries(entries) },
888
888
  };
889
889
  }
890
+ // 子代理停止:面板的「停止」。与「继续」不同,它不需要一个回合——协作取消
891
+ // 发生在正在跑的那次运行里,等回合只会让用户等自己的点击。
892
+ const childStopMatch = pathname.match(/^\/api\/v2\/children\/([^/]+)\/stop$/);
893
+ if (childStopMatch && method === 'POST') {
894
+ const chatId = url.searchParams.get('session')?.trim();
895
+ const childId = url.searchParams.get('child')?.trim();
896
+ if (!chatId || !childId) {
897
+ return {
898
+ status: 400,
899
+ data: { detail: 'session and child query parameters are required' },
900
+ };
901
+ }
902
+ const supervisor = getSidecarSupervisor();
903
+ if (!supervisor) {
904
+ return { status: 503, data: { detail: 'sidecar unavailable' } };
905
+ }
906
+ const result = await supervisor.childrenInterrupt(chatId, childId);
907
+ if (!result) {
908
+ return { status: 502, data: { detail: 'children interrupt failed' } };
909
+ }
910
+ return { status: 200, data: result };
911
+ }
912
+ // 子代理续跑:把一个已中断 / 撞墙 / 已完成但可续的子代理放回池里接着跑。
913
+ // 续跑必须经过一次真实回合——子代理要继承父回合的预算、审批与工具面,
914
+ // 所以这里只落一条用户消息并转发给 stream 路由,由父代理的 `agent_send`
915
+ // 触发重建(见 sidecar 的 `agent_send` 续跑分支)。直接起一个游离的子代理
916
+ // 会脱离父回合的预算与围栏。
917
+ const childResumeMatch = pathname.match(/^\/api\/v2\/children\/([^/]+)\/resume$/);
918
+ if (childResumeMatch && method === 'POST') {
919
+ const parentRecordId = url.searchParams.get('session')?.trim();
920
+ const childId = url.searchParams.get('child')?.trim();
921
+ if (!parentRecordId || !childId) {
922
+ return {
923
+ status: 400,
924
+ data: { detail: 'session and child query parameters are required' },
925
+ };
926
+ }
927
+ const supervisor = getSidecarSupervisor();
928
+ if (!supervisor) {
929
+ return { status: 503, data: { detail: 'sidecar unavailable' } };
930
+ }
931
+ // Ask the index first: a closed or unknown child must not start a turn
932
+ // that then fails with a confusing tool error.
933
+ const listed = await supervisor.childrenList({
934
+ parentRecordId,
935
+ includeFinished: true,
936
+ });
937
+ if (!listed) {
938
+ return { status: 502, data: { detail: 'children list failed' } };
939
+ }
940
+ const child = listed.children.find((row) => row.childId === childId);
941
+ if (!child) {
942
+ return {
943
+ status: 404,
944
+ data: { detail: `no child ${childId} for session ${parentRecordId}` },
945
+ };
946
+ }
947
+ if (!child.resumable) {
948
+ return {
949
+ status: 409,
950
+ data: {
951
+ detail: child.status === 'closed'
952
+ ? `child ${childId} is closed; have the parent spawn a new one`
953
+ : `child ${childId} is ${child.status}; wait for it to settle`,
954
+ },
955
+ };
956
+ }
957
+ const payload = this.toRecord(request.body);
958
+ const message = typeof payload.message === 'string' && payload.message.trim()
959
+ ? payload.message.trim()
960
+ : 'Continue the original task.';
961
+ return {
962
+ status: 200,
963
+ data: {
964
+ recordId: child.recordId,
965
+ childId: child.childId,
966
+ profile: child.profile,
967
+ depth: child.depth,
968
+ message,
969
+ // The host turns this into the parent turn's tool call; it carries
970
+ // what that turn needs, not a second execution path.
971
+ instruction: `Call agent_send with childId "${childId}" and this message: ${message}`,
972
+ },
973
+ };
974
+ }
975
+ // 子代理索引:这个会话派过哪些子代理、现在什么状态。
976
+ // 池只活一个回合,所以「上次派的还在不在」只能问 sidecar 的持久索引。
977
+ if (method === 'GET' && pathname === '/api/v2/children') {
978
+ const supervisor = getSidecarSupervisor();
979
+ if (!supervisor) {
980
+ return { status: 503, data: { detail: 'sidecar unavailable' } };
981
+ }
982
+ const parentRecordId = url.searchParams.get('session')?.trim();
983
+ const includeFinished = url.searchParams.get('active') !== '1';
984
+ const previewChars = Number(url.searchParams.get('previewChars') ?? '0');
985
+ const listed = await supervisor.childrenList({
986
+ ...(parentRecordId ? { parentRecordId } : {}),
987
+ includeFinished,
988
+ ...(Number.isFinite(previewChars) && previewChars > 0
989
+ ? { answerPreviewChars: Math.trunc(previewChars) }
990
+ : {}),
991
+ });
992
+ if (!listed) {
993
+ return { status: 502, data: { detail: 'children list failed' } };
994
+ }
995
+ return { status: 200, data: listed };
996
+ }
890
997
  // 4.6c Task×Worktree:合并到主仓 / 丢弃。两个操作都是幂等目标态
891
998
  // (worktreeState 非 pending 时 TaskService 抛错 → 409)。
892
999
  const taskActionMatch = pathname.match(/^\/api\/v2\/tasks\/([^/]+)\/(merge|discard)$/);
@@ -1221,6 +1328,13 @@ export class LocalBackendRouter {
1221
1328
  // 缺省允许其他技能:不勾技能的新智能体不该一个技能都加载不到。
1222
1329
  allowExternalSkills: typeof payload.allowExternalSkills === 'boolean' ? payload.allowExternalSkills : true,
1223
1330
  loadAllSkills: Boolean(payload.loadAllSkills),
1331
+ // R6: a role may pin the model and effort it delegates with. Absent
1332
+ // (or null) means "follow the parent", so an unconfigured agent
1333
+ // behaves exactly as before.
1334
+ model: typeof payload.model === 'string' && payload.model.trim() ? payload.model.trim() : null,
1335
+ reasoningEffort: typeof payload.reasoningEffort === 'string' && payload.reasoningEffort.trim()
1336
+ ? payload.reasoningEffort.trim()
1337
+ : null,
1224
1338
  isBuiltin: false,
1225
1339
  isArchived: false,
1226
1340
  sortOrder: typeof payload.sortOrder === 'number' ? payload.sortOrder : 0,
@@ -1683,6 +1797,18 @@ export class LocalBackendRouter {
1683
1797
  toolPolicy: payload.toolPolicy ? normalizeToolPolicy(payload.toolPolicy) : undefined,
1684
1798
  allowExternalSkills: typeof payload.allowExternalSkills === 'boolean' ? payload.allowExternalSkills : undefined,
1685
1799
  loadAllSkills: typeof payload.loadAllSkills === 'boolean' ? payload.loadAllSkills : undefined,
1800
+ // A PATCH that omits the field keeps the stored value; only an
1801
+ // explicit string (or explicit null) changes it.
1802
+ model: typeof payload.model === 'string'
1803
+ ? payload.model.trim() || null
1804
+ : payload.model === null
1805
+ ? null
1806
+ : undefined,
1807
+ reasoningEffort: typeof payload.reasoningEffort === 'string'
1808
+ ? payload.reasoningEffort.trim() || null
1809
+ : payload.reasoningEffort === null
1810
+ ? null
1811
+ : undefined,
1686
1812
  isArchived: typeof payload.isArchived === 'boolean' ? payload.isArchived : undefined,
1687
1813
  sortOrder: typeof payload.sortOrder === 'number' ? payload.sortOrder : undefined,
1688
1814
  });
@@ -4041,6 +4167,10 @@ export class LocalBackendRouter {
4041
4167
  const lifecycle = {
4042
4168
  kind: event.kind,
4043
4169
  childId: event.childId,
4170
+ // Wall-clock for the elapsed column: the renderer has no other
4171
+ // way to know when a child started once the turn is replayed
4172
+ // from persisted events.
4173
+ atMs: Date.now(),
4044
4174
  ...(event.task !== undefined ? { task: event.task } : {}),
4045
4175
  ...(event.depth !== undefined ? { depth: event.depth } : {}),
4046
4176
  ...(event.status !== undefined ? { status: event.status } : {}),
@@ -4048,6 +4178,11 @@ export class LocalBackendRouter {
4048
4178
  ...(event.profile !== undefined ? { profile: event.profile } : {}),
4049
4179
  // 子代理自己的 durable record:右侧过程面板据此回看它的推理与工具。
4050
4180
  ...(event.recordId !== undefined ? { recordId: event.recordId } : {}),
4181
+ // R5:子代理的账单。行内的 token 与「不计」都只读这一份,
4182
+ // 面板不再回头查注册表。
4183
+ ...(event.usage !== undefined ? { usage: event.usage } : {}),
4184
+ // R7-3:子代理在等用户回答。面板据此标「等待你的回答」。
4185
+ ...(event.intro !== undefined ? { intro: event.intro } : {}),
4051
4186
  };
4052
4187
  children.push(lifecycle);
4053
4188
  emit(this.sseData({ type: 'orchestration_child', ...lifecycle }));
@@ -4075,6 +4210,9 @@ export class LocalBackendRouter {
4075
4210
  turnPasses += 1;
4076
4211
  // W6-9 用量归因:落一条 chat 用量事件(含成本估算,无单价模型 costUsd=null)。
4077
4212
  // 每趟各落一条——续跑的花费是真实发生的,不该被合并掉。
4213
+ // R5:子代理的花费进同一条记录(父级 + children[]),而不是散成
4214
+ // 多条——一次回合的成本归因必须能一眼加总。外部引擎子代理不报
4215
+ // token,此时 usage_note='partial',不把缺失当零。
4078
4216
  if (outcome.usage) {
4079
4217
  try {
4080
4218
  await this.store.recordUsageEvent({
@@ -4082,11 +4220,12 @@ export class LocalBackendRouter {
4082
4220
  kind: 'chat',
4083
4221
  provider: settings.provider,
4084
4222
  model: overrideModel || settings.model,
4085
- promptTokens: outcome.usage.promptTokens,
4086
- completionTokens: outcome.usage.completionTokens,
4087
- totalTokens: outcome.usage.totalTokens,
4223
+ promptTokens: outcome.usage.promptTokens + (outcome.usage.childPromptTokens ?? 0),
4224
+ completionTokens: outcome.usage.completionTokens + (outcome.usage.childCompletionTokens ?? 0),
4225
+ totalTokens: outcome.usage.totalTokens + (outcome.usage.childTotalTokens ?? 0),
4088
4226
  cachedPromptTokens: outcome.usage.cachedPromptTokens,
4089
4227
  costUsd: outcome.usage.costUsd ?? null,
4228
+ usageNote: (outcome.usage.unknownUsageChildren ?? 0) > 0 ? 'partial' : null,
4090
4229
  });
4091
4230
  }
4092
4231
  catch (usageErr) {
@@ -9,7 +9,9 @@
9
9
  * 设计约束:
10
10
  * - 画像的 toolFilter 引用的是桌面模型可见工具面(tool-router)里的
11
11
  * 真实工具名;收窄即权限边界(explore 够不到写工具是构造性的)。
12
- * - per-profile model 刻意不设:跟随父模型;模型路由留给设置面。
12
+ * - 画像可以钉模型与推理强度(`model` / `reasoningEffort`),未钉的项
13
+ * 跟随父级。钉住的值由 sidecar 的 provider factory 重建 provider;宿主
14
+ * 服务不了的名字在建 provider 时失败即拒绝,不静默退回父模型。
13
15
  * - 画像系统提示是种进子 loop 的第一条 system 消息(子代理看不到
14
16
  * 主对话的系统提示,画像提示就是它的全部角色设定)。
15
17
  * - W2 落地前 toolFilter 必须与父本轮工具面取交集(子 ⊆ 父)。
@@ -21,6 +23,14 @@ export interface BuiltinSubagentProfile {
21
23
  concurrent?: boolean;
22
24
  description: string;
23
25
  systemPrompt?: string;
26
+ /**
27
+ * Model this profile's children run on. Omitted follows the parent — a
28
+ * role that did not ask for a model must cost the same as the agent that
29
+ * spawned it.
30
+ */
31
+ model?: string;
32
+ /** Reasoning effort for this profile's children; omitted follows the parent. */
33
+ reasoningEffort?: string;
24
34
  }
25
35
  /** 映射用的智能体子集(身份 + 能力面),不依赖存储层类型。 */
26
36
  export interface SubagentAgentInput extends AgentCapabilityInput {
@@ -29,6 +39,10 @@ export interface SubagentAgentInput extends AgentCapabilityInput {
29
39
  name: string;
30
40
  rolePrompt: string | null;
31
41
  description?: string | null;
42
+ /** R6: model this agent's children run on; null/absent follows the parent. */
43
+ model?: string | null;
44
+ /** R6: reasoning effort for this agent's children; null/absent follows the parent. */
45
+ reasoningEffort?: string | null;
32
46
  /** 画像缓存的失效依据:改配置即换键。缺省则该智能体的画像每轮重建。 */
33
47
  updatedAt?: string;
34
48
  }
@@ -9,7 +9,9 @@
9
9
  * 设计约束:
10
10
  * - 画像的 toolFilter 引用的是桌面模型可见工具面(tool-router)里的
11
11
  * 真实工具名;收窄即权限边界(explore 够不到写工具是构造性的)。
12
- * - per-profile model 刻意不设:跟随父模型;模型路由留给设置面。
12
+ * - 画像可以钉模型与推理强度(`model` / `reasoningEffort`),未钉的项
13
+ * 跟随父级。钉住的值由 sidecar 的 provider factory 重建 provider;宿主
14
+ * 服务不了的名字在建 provider 时失败即拒绝,不静默退回父模型。
13
15
  * - 画像系统提示是种进子 loop 的第一条 system 消息(子代理看不到
14
16
  * 主对话的系统提示,画像提示就是它的全部角色设定)。
15
17
  * - W2 落地前 toolFilter 必须与父本轮工具面取交集(子 ⊆ 父)。
@@ -35,6 +37,11 @@ export const BUILTIN_SUBAGENT_PROFILES = {
35
37
  explore: {
36
38
  toolFilter: READ_ONLY_TOOLS,
37
39
  concurrent: true,
40
+ // Read-only reconnaissance: finding something by searching and reading
41
+ // is not a reasoning-heavy task, so this role runs at the cheapest
42
+ // thinking level. No model is pinned — it follows whatever the parent
43
+ // conversation is already paying for.
44
+ reasoningEffort: 'low',
38
45
  description: '只读代码侦察。搜索、读文件、定位「在哪里/是什么」类问题;不做任何修改,返回带路径:行号的发现。',
39
46
  systemPrompt: [
40
47
  '你是只读探索代理,任务是在代码库中定位信息并汇报发现。',
@@ -47,6 +54,9 @@ export const BUILTIN_SUBAGENT_PROFILES = {
47
54
  research: {
48
55
  toolFilter: [...READ_ONLY_TOOLS, 'local_write_file'],
49
56
  concurrent: true,
57
+ // Cross-checking sources is mechanical reading and comparing; the deep
58
+ // thinking belongs to whoever acts on the report.
59
+ reasoningEffort: 'low',
50
60
  description: '深度调研。多轮 web 搜索/抓取并交叉验证,给出带来源 URL 的结论;可把报告写入文件。',
51
61
  systemPrompt: [
52
62
  '你是调研代理,任务是对一个问题做深度调研并给出可核验的结论。',
@@ -223,6 +233,8 @@ async function buildOneDelegateProfile(agent, parentToolNames) {
223
233
  agent.updatedAt,
224
234
  agent.slug ?? '',
225
235
  agent.name,
236
+ agent.model ?? '',
237
+ agent.reasoningEffort ?? '',
226
238
  parentToolNames.join(','),
227
239
  ].join('\u0000')
228
240
  : null;
@@ -260,6 +272,10 @@ async function buildProfileUncached(agent, parentToolNames) {
260
272
  concurrent: readOnly,
261
273
  description: profileDescription(agent),
262
274
  systemPrompt: built.prompt,
275
+ // A role that pinned nothing stays unpinned: the sidecar then reuses the
276
+ // parent's provider instead of rebuilding one at its defaults.
277
+ ...(agent.model ? { model: agent.model } : {}),
278
+ ...(agent.reasoningEffort ? { reasoningEffort: agent.reasoningEffort } : {}),
263
279
  };
264
280
  }
265
281
  /**
@@ -11,4 +11,4 @@
11
11
  */
12
12
  export { SidecarSupervisor } from './supervisor.js';
13
13
  export { SidecarBootError, SidecarMethodError, SidecarShutdownError, SidecarSandboxUnavailableError, } from './errors.js';
14
- export type { SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarChildEvent, SidecarHealthSnapshot, SidecarMethodOptions, SidecarRawChunk, SidecarSandboxPosture, SidecarSessionForkResult, SidecarStartOptions, SidecarStreamChunk, SidecarStreamDone, SidecarStreamError, SidecarToolResult, } from './types.js';
14
+ export type { SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarChildEvent, SidecarChildUsage, SidecarHealthSnapshot, SidecarMethodOptions, SidecarRawChunk, SidecarSandboxPosture, SidecarSessionForkResult, SidecarStartOptions, SidecarStreamChunk, SidecarStreamDone, SidecarStreamError, SidecarToolResult, } from './types.js';
@@ -10,7 +10,7 @@
10
10
  * - kill the process when the Electron app quits.
11
11
  */
12
12
  import { EventEmitter } from 'node:events';
13
- import type { SidecarApplyEditsResult, SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarHealthSnapshot, SidecarMethodOptions, SidecarModelCatalog, SidecarReverseHandler, SidecarSandboxPosture, SidecarSessionBranches, SidecarSessionForkOutcome, SidecarSessionMessages, SidecarSessionTree, SidecarSkillModule, SidecarStartOptions, SidecarToolResult } from './types.js';
13
+ import type { SidecarApplyEditsResult, SidecarChatStreamHandlers, SidecarChatStreamRequest, SidecarHealthSnapshot, SidecarMethodOptions, SidecarModelCatalog, SidecarReverseHandler, SidecarSandboxPosture, SidecarSessionBranches, SidecarSessionForkOutcome, SidecarSessionMessages, SidecarSessionTree, SidecarChildrenList, SidecarSkillModule, SidecarStartOptions, SidecarToolResult } from './types.js';
14
14
  /**
15
15
  * Tool names carried by a `tool.list` reply.
16
16
  *
@@ -147,6 +147,33 @@ export declare class SidecarSupervisor extends EventEmitter {
147
147
  * the read path for rendering a branch after a switch. Soft-fail null.
148
148
  */
149
149
  sessionMessages(recordId: string): Promise<SidecarSessionMessages | null>;
150
+ /**
151
+ * Every child agent recorded for one parent session.
152
+ *
153
+ * Soft-fail null keeps the caller honest: an empty list would be
154
+ * indistinguishable from "this session spawned nothing", and the two mean
155
+ * very different things to a "resume your children" panel.
156
+ */
157
+ childrenList(params: {
158
+ parentRecordId?: string;
159
+ prefix?: string;
160
+ includeFinished?: boolean;
161
+ answerPreviewChars?: number;
162
+ }): Promise<SidecarChildrenList | null>;
163
+ /**
164
+ * Cooperatively interrupt one running child of a chat's live turn.
165
+ *
166
+ * Soft-fails `null` (the caller treats it as "nothing to stop"): the panel
167
+ * pressed stop on a row that may have settled a moment ago, which is not an
168
+ * error worth showing.
169
+ *
170
+ * @param chatId The chat whose turn owns the child.
171
+ * @param childId The child's lineage id.
172
+ */
173
+ childrenInterrupt(chatId: string, childId: string): Promise<{
174
+ interrupted: boolean;
175
+ reason?: string;
176
+ } | null>;
150
177
  /**
151
178
  * Inject a user message into a running CoreLoop turn (mid-turn steering).
152
179
  * Soft-fails (`{ ok: false }`) when the turn already ended — the caller
@@ -307,6 +307,41 @@ export class SidecarSupervisor extends EventEmitter {
307
307
  return null;
308
308
  }
309
309
  }
310
+ /**
311
+ * Every child agent recorded for one parent session.
312
+ *
313
+ * Soft-fail null keeps the caller honest: an empty list would be
314
+ * indistinguishable from "this session spawned nothing", and the two mean
315
+ * very different things to a "resume your children" panel.
316
+ */
317
+ async childrenList(params) {
318
+ try {
319
+ return await this.call('agent.children.list', params, {
320
+ timeoutMs: 15_000,
321
+ });
322
+ }
323
+ catch {
324
+ return null;
325
+ }
326
+ }
327
+ /**
328
+ * Cooperatively interrupt one running child of a chat's live turn.
329
+ *
330
+ * Soft-fails `null` (the caller treats it as "nothing to stop"): the panel
331
+ * pressed stop on a row that may have settled a moment ago, which is not an
332
+ * error worth showing.
333
+ *
334
+ * @param chatId The chat whose turn owns the child.
335
+ * @param childId The child's lineage id.
336
+ */
337
+ async childrenInterrupt(chatId, childId) {
338
+ try {
339
+ return await this.call('agent.children.interrupt', { chatId, childId }, { timeoutMs: 15_000 });
340
+ }
341
+ catch {
342
+ return null;
343
+ }
344
+ }
310
345
  /**
311
346
  * Inject a user message into a running CoreLoop turn (mid-turn steering).
312
347
  * Soft-fails (`{ ok: false }`) when the turn already ended — the caller
@@ -184,6 +184,34 @@ export interface SidecarSessionMessages {
184
184
  content: string;
185
185
  }>;
186
186
  }
187
+ /**
188
+ * `agent.children.list` result: the durable child-agent index for one parent
189
+ * session. `status` is composed, never stored raw — a terminal row reports
190
+ * its own status, a non-terminal row with a live handle reports `running`,
191
+ * and one with no handle reports `interrupted` (`resumable` says whether a
192
+ * send can continue it).
193
+ */
194
+ export interface SidecarChildAgent {
195
+ recordId: string;
196
+ parentRecordId: string;
197
+ childId: string;
198
+ depth: number;
199
+ profile: string | null;
200
+ engine: string;
201
+ status: string;
202
+ resumable: boolean;
203
+ live: boolean;
204
+ promptTokens: number | null;
205
+ completionTokens: number | null;
206
+ usageKnown: boolean;
207
+ createdAt: string;
208
+ updatedAt: string;
209
+ answerPreview?: string;
210
+ }
211
+ export interface SidecarChildrenList {
212
+ parentRecordId: string | null;
213
+ children: SidecarChildAgent[];
214
+ }
187
215
  /**
188
216
  * W6-1: `workspace.apply_edits` result — the pure structured-edit algorithm
189
217
  * run in the sidecar on host-supplied content. The host owns all file I/O.
@@ -368,6 +396,12 @@ export interface SidecarChatStreamRequest {
368
396
  profiles?: Record<string, {
369
397
  toolFilter?: string[];
370
398
  model?: string;
399
+ /**
400
+ * R6: reasoning effort for this profile's children. Omitted follows
401
+ * the parent's request; an unsupportable level fails at provider
402
+ * construction rather than being silently dropped.
403
+ */
404
+ reasoningEffort?: string;
371
405
  maxRounds?: number;
372
406
  maxToolErrors?: number;
373
407
  concurrent?: boolean;
@@ -583,6 +617,12 @@ export interface SidecarStreamDone {
583
617
  * W6-9: the run's accumulated billable usage (summed over every provider
584
618
  * request this turn), plus `costUsd` when the model is priced. Absent on
585
619
  * paths that don't report usage.
620
+ *
621
+ * R5: when the turn delegated, the same object also carries the children's
622
+ * share — `child*` totals and a per-child `children` split, so a host can
623
+ * show the turn's real cost without walking the registry. Children whose
624
+ * engine reports no tokens at all (an external ACP agent) are counted in
625
+ * `unknownUsageChildren` rather than folded in as zeros.
586
626
  */
587
627
  usage?: {
588
628
  promptTokens: number;
@@ -590,7 +630,30 @@ export interface SidecarStreamDone {
590
630
  totalTokens: number;
591
631
  cachedPromptTokens?: number;
592
632
  costUsd?: number;
633
+ childPromptTokens?: number;
634
+ childCompletionTokens?: number;
635
+ childTotalTokens?: number;
636
+ children?: SidecarChildUsage[];
637
+ unknownUsageChildren?: number;
593
638
  };
639
+ /**
640
+ * R5: the whole turn tree's spend against `budgetTokens`. Absent when the
641
+ * host asked for no tree limit — "no limit" must stay distinguishable from
642
+ * "spent nothing".
643
+ */
644
+ treeUsage?: {
645
+ limit: number;
646
+ spent: number;
647
+ byAgent: Record<string, number>;
648
+ };
649
+ }
650
+ /** One child's bill inside `stream.done`'s `usage.children`. */
651
+ export interface SidecarChildUsage {
652
+ childId: string;
653
+ profile?: string;
654
+ promptTokens: number;
655
+ completionTokens: number;
656
+ totalTokens: number;
594
657
  }
595
658
  export interface SidecarStreamError {
596
659
  streamId: string;
@@ -638,6 +701,22 @@ export interface SidecarChildEvent {
638
701
  * back to render the delegation's reasoning + tool calls.
639
702
  */
640
703
  recordId?: string;
704
+ /**
705
+ * R5: this child's bill, on the terminal event. Absent means it has not
706
+ * settled yet; a settled external-engine child carries no `usage` at all,
707
+ * and the row says "not counted" rather than "0 tok".
708
+ */
709
+ usage?: {
710
+ promptTokens: number;
711
+ completionTokens: number;
712
+ totalTokens: number;
713
+ };
714
+ /**
715
+ * R7-3: the child's intro when it is blocked on the user
716
+ * (`child_needs_input`). The panel marks the row and the question card
717
+ * names the child it came from.
718
+ */
719
+ intro?: string;
641
720
  }
642
721
  export interface SidecarChatStreamHandlers {
643
722
  onChunk?: (chunk: SidecarStreamChunk) => void;
@@ -64,6 +64,17 @@ export interface ChatAgentRecord {
64
64
  * `/技能名` 显式触发三处都拦)。
65
65
  */
66
66
  allowExternalSkills: boolean;
67
+ /**
68
+ * 委派给这个智能体时用的模型。`null` 跟随父级——一个没表达的偏好不该
69
+ * 悄悄换成另一个模型。非空时经 sidecar 的 provider factory 重建 provider,
70
+ * 宿主服务不了的名字在建 provider 时失败即拒绝。
71
+ */
72
+ model: string | null;
73
+ /**
74
+ * 委派给这个智能体时的推理强度。`null` 跟随父级;不支持该档位时同样
75
+ * 失败即拒绝,错误点名画像、模型与取值。
76
+ */
77
+ reasoningEffort: string | null;
67
78
  /**
68
79
  * true = 无视技能的触发条件全量加载(内置「智能助手」的行为)。
69
80
  * 与 `allowExternalSkills: false` 同时设置时白名单仍然优先。
@@ -337,6 +348,12 @@ export declare class SqliteScopedStore implements ScopedStore {
337
348
  retried?: boolean;
338
349
  /** Whether any request went direct instead of through the proxy. */
339
350
  usedDirect?: boolean;
351
+ /**
352
+ * `'partial'` when the totals exclude spend the host knows happened: a
353
+ * child agent on an external engine reports no tokens. Storing the note
354
+ * keeps a smaller number from reading as a complete bill.
355
+ */
356
+ usageNote?: 'partial' | null;
340
357
  }): Promise<void>;
341
358
  /**
342
359
  * Reliability summary for the last `sinceDays` days.
@@ -349,6 +349,13 @@ export class SqliteScopedStore {
349
349
  // 是否发生过重试,以及是否改走过直连。
350
350
  this.ensureColumn('usage_events', 'retried', 'INTEGER NOT NULL DEFAULT 0');
351
351
  this.ensureColumn('usage_events', 'used_direct', 'INTEGER NOT NULL DEFAULT 0');
352
+ // R5 子代理用量:partial 表示这一行不含全部花费(外部引擎子代理不报
353
+ // token)。NULL 表示数字就是全部账单——「缺一块」和「完整」必须能区分。
354
+ this.ensureColumn('usage_events', 'usage_note', 'TEXT');
355
+ // R6 角色级模型:委派画像可以钉模型与推理强度。NULL = 跟随父级,
356
+ // 所以旧行(与未配置的智能体)行为与改前一致。
357
+ this.ensureColumn('chat_agents', 'model', 'TEXT');
358
+ this.ensureColumn('chat_agents', 'reasoning_effort', 'TEXT');
352
359
  // 智能体技能面(增量迁移):load_all_skills = 无视触发条件全量加载。
353
360
  // 此前这个行为是 router 里 `chatAgentId === 'all-round-assistant'` 的
354
361
  // 硬编码,自建智能体拿不到;建列时一次性回填给内置「智能助手」,之后
@@ -977,9 +984,10 @@ export class SqliteScopedStore {
977
984
  tenant_id, user_id,
978
985
  id, slug, name, icon, color, description, role_prompt, forbidden_prompt,
979
986
  skill_ids, tool_policy, allow_external_skills, load_all_skills,
987
+ model, reasoning_effort,
980
988
  is_builtin, is_archived, sort_order, created_at, updated_at
981
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
982
- `).run(this.scope.tenantId, this.scope.userId, id, input.slug ?? null, input.name, input.icon ?? null, input.color ?? null, input.description ?? null, input.rolePrompt ?? null, input.forbiddenPrompt ?? null, JSON.stringify(input.skillIds ?? []), JSON.stringify(input.toolPolicy ?? { mode: 'all', tools: [] }), input.allowExternalSkills ? 1 : 0, input.loadAllSkills ? 1 : 0, input.isBuiltin ? 1 : 0, input.isArchived ? 1 : 0, input.sortOrder ?? 0, now, now);
989
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
990
+ `).run(this.scope.tenantId, this.scope.userId, id, input.slug ?? null, input.name, input.icon ?? null, input.color ?? null, input.description ?? null, input.rolePrompt ?? null, input.forbiddenPrompt ?? null, JSON.stringify(input.skillIds ?? []), JSON.stringify(input.toolPolicy ?? { mode: 'all', tools: [] }), input.allowExternalSkills ? 1 : 0, input.loadAllSkills ? 1 : 0, input.model ?? null, input.reasoningEffort ?? null, input.isBuiltin ? 1 : 0, input.isArchived ? 1 : 0, input.sortOrder ?? 0, now, now);
983
991
  const created = await this.getChatAgent(id);
984
992
  if (!created)
985
993
  throw new Error('Failed to create chat agent');
@@ -1002,9 +1010,10 @@ export class SqliteScopedStore {
1002
1010
  UPDATE chat_agents
1003
1011
  SET slug = ?, name = ?, icon = ?, color = ?, description = ?, role_prompt = ?, forbidden_prompt = ?,
1004
1012
  skill_ids = ?, tool_policy = ?, allow_external_skills = ?, load_all_skills = ?,
1013
+ model = ?, reasoning_effort = ?,
1005
1014
  is_builtin = ?, is_archived = ?, sort_order = ?, updated_at = ?
1006
1015
  WHERE tenant_id = ? AND user_id = ? AND id = ?
1007
- `).run(merged.slug, merged.name, merged.icon, merged.color, merged.description, merged.rolePrompt, merged.forbiddenPrompt, JSON.stringify(merged.skillIds), JSON.stringify(merged.toolPolicy), merged.allowExternalSkills ? 1 : 0, merged.loadAllSkills ? 1 : 0, merged.isBuiltin ? 1 : 0, merged.isArchived ? 1 : 0, merged.sortOrder, merged.updatedAt, this.scope.tenantId, this.scope.userId, agentId);
1016
+ `).run(merged.slug, merged.name, merged.icon, merged.color, merged.description, merged.rolePrompt, merged.forbiddenPrompt, JSON.stringify(merged.skillIds), JSON.stringify(merged.toolPolicy), merged.allowExternalSkills ? 1 : 0, merged.loadAllSkills ? 1 : 0, merged.model ?? null, merged.reasoningEffort ?? null, merged.isBuiltin ? 1 : 0, merged.isArchived ? 1 : 0, merged.sortOrder, merged.updatedAt, this.scope.tenantId, this.scope.userId, agentId);
1008
1017
  return await this.getChatAgent(agentId);
1009
1018
  }
1010
1019
  async archiveChatAgent(agentId) {
@@ -1138,9 +1147,9 @@ export class SqliteScopedStore {
1138
1147
  async recordUsageEvent(input) {
1139
1148
  this.db.prepare(`
1140
1149
  INSERT INTO usage_events
1141
- (tenant_id, user_id, id, chat_id, kind, provider, model, prompt_tokens, completion_tokens, total_tokens, cached_prompt_tokens, cost_usd, created_at, outcome, failure_kind, attempts, retried, used_direct)
1142
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1143
- `).run(this.scope.tenantId, this.scope.userId, randomUUID(), input.chatId ?? null, input.kind, input.provider ?? null, input.model ?? null, Math.max(0, Math.floor(input.promptTokens)), Math.max(0, Math.floor(input.completionTokens)), Math.max(0, Math.floor(input.totalTokens)), Math.max(0, Math.floor(input.cachedPromptTokens ?? 0)), input.costUsd ?? null, new Date().toISOString(), input.outcome ?? 'completed', input.failureKind ?? null, input.attempts ?? null, input.retried ? 1 : 0, input.usedDirect ? 1 : 0);
1150
+ (tenant_id, user_id, id, chat_id, kind, provider, model, prompt_tokens, completion_tokens, total_tokens, cached_prompt_tokens, cost_usd, created_at, outcome, failure_kind, attempts, retried, used_direct, usage_note)
1151
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1152
+ `).run(this.scope.tenantId, this.scope.userId, randomUUID(), input.chatId ?? null, input.kind, input.provider ?? null, input.model ?? null, Math.max(0, Math.floor(input.promptTokens)), Math.max(0, Math.floor(input.completionTokens)), Math.max(0, Math.floor(input.totalTokens)), Math.max(0, Math.floor(input.cachedPromptTokens ?? 0)), input.costUsd ?? null, new Date().toISOString(), input.outcome ?? 'completed', input.failureKind ?? null, input.attempts ?? null, input.retried ? 1 : 0, input.usedDirect ? 1 : 0, input.usageNote ?? null);
1144
1153
  }
1145
1154
  /**
1146
1155
  * Reliability summary for the last `sinceDays` days.
@@ -1208,6 +1217,7 @@ export class SqliteScopedStore {
1208
1217
  SUM(completion_tokens) AS completion_tokens,
1209
1218
  SUM(total_tokens) AS total_tokens,
1210
1219
  SUM(cached_prompt_tokens) AS cached_prompt_tokens,
1220
+ SUM(CASE WHEN usage_note = 'partial' THEN 1 ELSE 0 END) AS partial_turns,
1211
1221
  SUM(cost_usd) AS cost_usd
1212
1222
  FROM usage_events
1213
1223
  WHERE tenant_id = ? AND user_id = ? AND created_at >= ?
@@ -1489,6 +1499,8 @@ export class SqliteScopedStore {
1489
1499
  toolPolicy: this.safeJson(row.tool_policy, { mode: 'all', tools: [] }),
1490
1500
  allowExternalSkills: Number(row.allow_external_skills ?? 0) === 1,
1491
1501
  loadAllSkills: Number(row.load_all_skills ?? 0) === 1,
1502
+ model: row.model ? String(row.model) : null,
1503
+ reasoningEffort: row.reasoning_effort ? String(row.reasoning_effort) : null,
1492
1504
  isBuiltin: Number(row.is_builtin ?? 0) === 1,
1493
1505
  isArchived: Number(row.is_archived ?? 0) === 1,
1494
1506
  sortOrder: Number(row.sort_order ?? 0),
@@ -85,6 +85,12 @@ export interface ScopedStore {
85
85
  attempts?: number | null;
86
86
  retried?: boolean;
87
87
  usedDirect?: boolean;
88
+ /**
89
+ * R5: `'partial'` when part of the turn's spend is missing from these
90
+ * totals — an external-engine child reports no tokens at all. Absent
91
+ * means the numbers are the whole bill.
92
+ */
93
+ usageNote?: 'partial' | null;
88
94
  }): Promise<void>;
89
95
  getUsageSummary(sinceDays?: number): Promise<UsageSummary>;
90
96
  getReliabilitySummary(sinceDays?: number): Promise<ReliabilitySummary>;
@@ -34,6 +34,11 @@ export interface UsageSummary {
34
34
  cachedPromptTokens: number;
35
35
  /** 所有有单价模型的成本合计(无单价模型不计入)。 */
36
36
  costUsd: number;
37
+ /**
38
+ * R5:行数里有多少条只是部分账单(外部引擎子代理不报 token)。
39
+ * 面板据此提示「合计不含部分子代理」,而不是让偏小的数字冒充完整账单。
40
+ */
41
+ partialTurns: number;
37
42
  };
38
43
  }
39
44
  /** `getUsageSummary` SQL 查询返回的原始行(snake_case 列)。 */
@@ -46,6 +51,8 @@ export interface UsageSummaryRow {
46
51
  total_tokens: number;
47
52
  cached_prompt_tokens: number;
48
53
  cost_usd: number | null;
54
+ /** R5: how many rows in this bucket are only a partial bill. */
55
+ partial_turns: number;
49
56
  }
50
57
  /**
51
58
  * 把 SQL 分桶行聚合成 `UsageSummary`。
@@ -34,5 +34,14 @@ export function buildUsageSummary(rows, sinceDays) {
34
34
  cachedPromptTokens: acc.cachedPromptTokens + b.cachedPromptTokens,
35
35
  costUsd: acc.costUsd + (b.costUsd ?? 0),
36
36
  }), { turns: 0, promptTokens: 0, completionTokens: 0, totalTokens: 0, cachedPromptTokens: 0, costUsd: 0 });
37
- return { sinceDays, byModel, totals };
37
+ return {
38
+ sinceDays,
39
+ byModel,
40
+ totals: {
41
+ ...totals,
42
+ // Summed over rows rather than buckets: "how many turns are missing
43
+ // spend" is a fact about the window, not about one model.
44
+ partialTurns: rows.reduce((sum, row) => sum + Number(row.partial_turns ?? 0), 0),
45
+ },
46
+ };
38
47
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steerable/agent-shell",
3
- "version": "0.9.2",
3
+ "version": "0.10.1",
4
4
  "description": "Steerable framework — product-neutral Node HostRuntime and headless HTTP server shared by Tauri desktop and browser deployments; scenario packs extend it through @steerable/pack-sdk.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://steerableframework.com/",
@@ -53,10 +53,10 @@
53
53
  "jpeg-js": "^0.4.4",
54
54
  "node-pty": "^1.1.0",
55
55
  "pngjs": "^7.0.0",
56
- "@steerable/agent-harness": "0.9.2",
57
- "@steerable/agent-protocol": "0.9.2",
58
- "@steerable/agent-runtime": "0.9.2",
59
- "@steerable/pack-sdk": "0.9.2"
56
+ "@steerable/agent-harness": "0.10.1",
57
+ "@steerable/agent-protocol": "0.10.1",
58
+ "@steerable/agent-runtime": "0.10.1",
59
+ "@steerable/pack-sdk": "0.10.1"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@types/better-sqlite3": "^7.6.13",