@tencent-ai/agent-harness 0.2.0-beta.2 → 0.2.0-beta.3

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.
Files changed (149) hide show
  1. package/CHANGELOG.md +26 -2
  2. package/cli/CHANGELOG.md +64 -0
  3. package/cli/dist-server/shared.cjs +379 -315
  4. package/cli/dist-server/types/node/bash-sandbox/bash-sandbox-protocol.d.ts +3 -0
  5. package/cli/dist-server/types/node/cli/cli-protocol.d.ts +3 -0
  6. package/cli/dist-server/types/node/cli/stream-json-protocol.d.ts +8 -1
  7. package/cli/dist-server/types/node/sensitive-content/sensitive-content-protocol.d.ts +7 -0
  8. package/cli/dist-server/types/node/server/boot.d.ts +7 -4
  9. package/{lib/components → cli/dist-server/types/node/server/formats}/acp/acp-error-model.d.ts +1 -1
  10. package/{lib/components → cli/dist-server/types/node/server/formats}/acp/acp-protocol.d.ts +2 -3
  11. package/cli/dist-server/types/node/server/formats/acp/index.d.ts +12 -0
  12. package/cli/dist-server/types/node/server/formats/acp/projection.d.ts +10 -0
  13. package/cli/dist-server/types/node/server/index.d.ts +1 -1
  14. package/cli/dist-server/types/node/server/sessions.d.ts +3 -2
  15. package/cli/dist-server/types/node/server/types.d.ts +59 -7
  16. package/cli/dist-server/types/node/tools/tool-protocol.d.ts +16 -2
  17. package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-protocol.d.ts +31 -2
  18. package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-purpose-protocol.d.ts +8 -4
  19. package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-purpose-scope.d.ts +46 -0
  20. package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-service.d.ts +26 -3
  21. package/cli/dist-server/types/vendor/cbc-core/node/agent/index.d.ts +3 -0
  22. package/cli/dist-server/types/vendor/cbc-core/node/agent/model-call-failure.d.ts +9 -0
  23. package/cli/dist-server/types/vendor/cbc-core/node/agent/model-step-sequence.d.ts +11 -0
  24. package/cli/dist-server/types/vendor/cbc-core/node/agent/runner-factory.d.ts +25 -9
  25. package/cli/dist-server/types/vendor/cbc-core/node/agent/tool-call-loop-guard-protocol.d.ts +1 -1
  26. package/cli/dist-server/types/vendor/cbc-core/node/agent/tool-call-loop-pattern.d.ts +9 -8
  27. package/cli/dist-server/types/vendor/cbc-core/node/context/compaction-lineage.d.ts +39 -0
  28. package/cli/dist-server/types/vendor/cbc-core/node/context/context-compact-summarizer.d.ts +2 -0
  29. package/cli/dist-server/types/vendor/cbc-core/node/context/context-protocol.d.ts +17 -0
  30. package/cli/dist-server/types/vendor/cbc-core/node/context/index.d.ts +1 -0
  31. package/cli/dist-server/types/vendor/cbc-core/node/context/pre-message-compact-strategy.d.ts +1 -2
  32. package/cli/dist-server/types/vendor/cbc-core/node/session/index.d.ts +1 -0
  33. package/cli/dist-server/types/vendor/cbc-core/node/session/interruption-service.d.ts +8 -0
  34. package/cli/dist-server/types/vendor/cbc-core/node/session/model-request-retry-phase.d.ts +16 -0
  35. package/cli/dist-server/types/vendor/cbc-core/node/session/model-response-interceptors.d.ts +15 -0
  36. package/cli/dist-server/types/vendor/cbc-core/node/session/session-manager-host-protocol.d.ts +3 -2
  37. package/cli/dist-server/types/vendor/cbc-core/node/session/session-manager.d.ts +7 -3
  38. package/cli/dist-server/types/vendor/cbc-core/node/session/session-protocol.d.ts +47 -5
  39. package/cli/dist-server/types/vendor/cbc-core/node/session/session-run-state-machine-protocol.d.ts +14 -1
  40. package/cli/dist-server/types/vendor/cbc-core/node/session/stream-timeout-retry-budget.d.ts +8 -1
  41. package/cli/dist-server/types/vendor/cbc-core/node/trace/turn-context.d.ts +28 -1
  42. package/cli/dist-server/types/vendor/cbc-core/node/utils/command-message-utils.d.ts +20 -0
  43. package/cli/dist-server/types/vendor/cbc-core/node/utils/history-utils.d.ts +4 -4
  44. package/cli/dist-server/types/vendor/cbc-core/node/utils/input-item-utils.d.ts +8 -0
  45. package/cli/dist-server/types/vendor/cbc-core/node/utils/token-utils.d.ts +3 -1
  46. package/cli/dist-server/types/vendor/cbc-shared/node/agent/openai-agents-types.d.ts +1 -0
  47. package/cli/dist-server/types/vendor/cbc-shared/node/checkpoint/checkpoint-types.d.ts +6 -0
  48. package/cli/dist-server/types/vendor/cbc-shared/node/model/model-errors.d.ts +30 -2
  49. package/cli/dist-server/types/workspace/agent-client-protocol/lib/common/index.d.ts +1 -0
  50. package/cli/dist-server/types/workspace/agent-client-protocol/lib/common/sandbox-rule-context.d.ts +38 -0
  51. package/cli/dist-server/types/workspace/authentication/lib/common/account-scoped-external-link-authentication-provider.d.ts +3 -3
  52. package/cli/dist-server/types/workspace/authentication/lib/common/authentication-manager.d.ts +6 -0
  53. package/cli/dist-server/types/workspace/authentication/lib/common/authentication-observation.d.ts +36 -0
  54. package/cli/dist-server/types/workspace/authentication/lib/common/authentication-protocol.d.ts +21 -0
  55. package/cli/dist-server/types/workspace/authentication/lib/common/external-link-authentication-provider.d.ts +20 -4
  56. package/cli/dist-server/types/workspace/authentication/lib/common/index.d.ts +1 -0
  57. package/cli/dist-server/types/workspace/cbc-checkpoint/lib/node/checkpoint/checkpoint-protocol.d.ts +2 -0
  58. package/cli/dist-server/types/workspace/cbc-checkpoint/lib/node/checkpoint/checkpoint-service.d.ts +1 -0
  59. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-protocol.d.ts +31 -2
  60. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-purpose-protocol.d.ts +8 -4
  61. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-purpose-scope.d.ts +46 -0
  62. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-service.d.ts +26 -3
  63. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/index.d.ts +3 -0
  64. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/model-call-failure.d.ts +9 -0
  65. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/model-step-sequence.d.ts +11 -0
  66. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/runner-factory.d.ts +25 -9
  67. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/tool-call-loop-guard-protocol.d.ts +1 -1
  68. package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/tool-call-loop-pattern.d.ts +9 -8
  69. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/compaction-lineage.d.ts +39 -0
  70. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/context-compact-summarizer.d.ts +2 -0
  71. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/context-protocol.d.ts +17 -0
  72. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/index.d.ts +1 -0
  73. package/cli/dist-server/types/workspace/cbc-core/lib/node/context/pre-message-compact-strategy.d.ts +1 -2
  74. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/index.d.ts +1 -0
  75. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/interruption-service.d.ts +8 -0
  76. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/model-request-retry-phase.d.ts +16 -0
  77. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/model-response-interceptors.d.ts +15 -0
  78. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-manager-host-protocol.d.ts +3 -2
  79. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-manager.d.ts +7 -3
  80. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-protocol.d.ts +47 -5
  81. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-run-state-machine-protocol.d.ts +14 -1
  82. package/cli/dist-server/types/workspace/cbc-core/lib/node/session/stream-timeout-retry-budget.d.ts +8 -1
  83. package/cli/dist-server/types/workspace/cbc-core/lib/node/trace/turn-context.d.ts +28 -1
  84. package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/command-message-utils.d.ts +20 -0
  85. package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/history-utils.d.ts +4 -4
  86. package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/input-item-utils.d.ts +8 -0
  87. package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/token-utils.d.ts +3 -1
  88. package/cli/dist-server/types/workspace/cbc-shared/lib/node/agent/openai-agents-types.d.ts +1 -0
  89. package/cli/dist-server/types/workspace/cbc-shared/lib/node/checkpoint/checkpoint-types.d.ts +6 -0
  90. package/cli/dist-server/types/workspace/cbc-shared/lib/node/model/model-errors.d.ts +30 -2
  91. package/cli/dist-server/types/workspace/cbc-worktree/lib/node/worktree/worktree-service.d.ts +5 -0
  92. package/cli/dist-server/types/workspace/core/lib/common/protocol.d.ts +8 -1
  93. package/cli/dist-server/types/workspace/product/lib/common/index.d.ts +1 -0
  94. package/cli/dist-server/types/workspace/product/lib/common/tencent-docs-endpoint.d.ts +37 -0
  95. package/cli/dist-server/types/workspace/product/lib/common/types/config.d.ts +12 -0
  96. package/cli/dist-server/types/workspace/product/lib/common/types/features.d.ts +1 -9
  97. package/cli/dist-server/types/workspace/product/lib/common/types/product.d.ts +15 -0
  98. package/cli/dist-server/types/workspace/sandbox-cli/lib/common/center-protocol.generated.d.ts +5 -0
  99. package/cli/dist-server/types/workspace/sandbox-cli/lib/common/file-policy.d.ts +4 -1
  100. package/cli/dist-server/types/workspace/sandbox-cli/lib/common/http-policy.d.ts +20 -0
  101. package/cli/dist-server/types/workspace/sandbox-cli/lib/common/rule-config.d.ts +10 -0
  102. package/cli/dist-server/types/workspace/sandbox-cli/lib/node/sandbox-center-client.d.ts +3 -0
  103. package/cli/dist-server/types/workspace/telemetry/lib/common/event/types/craft.d.ts +43 -3
  104. package/cli/package.json +1 -1
  105. package/cli/product.cloudhosted.json +4 -4
  106. package/cli/product.internal.json +11 -7
  107. package/cli/product.ioa.json +32 -24
  108. package/cli/product.json +45 -17
  109. package/cli/product.selfhosted.json +2 -2
  110. package/cli/vendor/shim/brokered-bin/7z +675 -0
  111. package/cli/vendor/shim/brokered-bin/7za +675 -0
  112. package/cli/vendor/shim/brokered-bin/7zz +675 -0
  113. package/cli/vendor/shim/brokered-bin/rar +675 -0
  114. package/cli/vendor/shim/brokered-bin/tar +675 -0
  115. package/cli/vendor/shim/brokered-bin/zip +187 -0
  116. package/docs/in-process.md +26 -2
  117. package/docs/protocol.md +7 -1
  118. package/docs/server.md +2 -0
  119. package/lib/agent/v2.js +1 -1
  120. package/lib/application/services.js +1 -1
  121. package/lib/client/client.js +1 -1
  122. package/lib/client/mcp.d.ts +1 -1
  123. package/lib/client/mcp.js +1 -1
  124. package/lib/components/acp-mcp-transport.d.mts +84 -1
  125. package/lib/components/question-elicitation.d.mts +20 -1
  126. package/lib/components/{acp/acp-prompt-input.d.ts → session/prompt-input.d.ts} +1 -1
  127. package/lib/components/session-replay.d.mts +6 -7
  128. package/lib/components/session-replay.mjs +1 -1
  129. package/lib/effect-runtime/mcp-lifecycle.mjs +1 -1
  130. package/lib/harness/create-harness.js +1 -1
  131. package/lib/integration/agent-integration.d.ts +5 -0
  132. package/lib/runtime/private-runtime-role.js +1 -1
  133. package/lib/session/agent-backend.d.ts +3 -0
  134. package/lib/session/agent-backend.js +1 -1
  135. package/lib/session/config-defaults.d.ts +4 -0
  136. package/lib/session/config-defaults.js +1 -0
  137. package/lib/session/config-store.d.ts +1 -1
  138. package/lib/session/config-store.js +1 -1
  139. package/lib/session/replay.d.ts +2 -2
  140. package/lib/session/replay.js +1 -1
  141. package/lib/session/server-config.d.ts +11 -2
  142. package/lib/session/server-config.js +1 -1
  143. package/lib/session/server-events.d.ts +10 -8
  144. package/lib/session/server-events.js +1 -1
  145. package/lib/session/server-mcp.js +1 -1
  146. package/package.json +20 -19
  147. package/lib/components/acp/acp-client-channel.d.ts +0 -36
  148. package/lib/components/acp/acp-mcp-transport.d.ts +0 -84
  149. package/lib/components/acp/acp-question-elicitation.d.ts +0 -20
@@ -226,10 +226,10 @@ export declare abstract class HistoryUtils {
226
226
  * <conversation_history_summary>…</conversation_history_summary> 包裹的正文)。
227
227
  *
228
228
  * 规则(与 replaceCompactWithSummary / getCompactHistory 对齐):
229
- * 1. 仅查看 `providerData.agent === AgentNames.COMPACT` 且为 assistant 的 message
230
- * 2. 从后向前扫描,命中第一条满足格式的 compact assistant 即返回
231
- * 3. "满足格式"由 `SummaryUtils.extractCompactSummaryFromText` 统一判定
232
- * (内含结构校验 + 非空正文双闸)
229
+ * 1. 查看 compact-agent assistant,或 PreMessage/MaxToken 写入的显式 compact boundary
230
+ * 2. 从后向前扫描,命中第一条可用摘要即返回
231
+ * 3. compact assistant 继续要求结构化 summary envelope;显式 boundary 同时支持
232
+ * 工程压缩的 `<cb_summary>` 与 LLM summary envelope
233
233
  * 4. 全程扫描都拿不到 → 返回 `undefined`(history 中**从未**出现过合法摘要)
234
234
  *
235
235
  * ⚠️ 不适合用于"判断本次 compact run 是否成功"!
@@ -256,6 +256,14 @@ export declare abstract class InputItemUtils {
256
256
  static isUserInterrupted(item: AgentInputItem): boolean;
257
257
  static isSuccessfulFunctionCallResultItem(item: AgentInputItem): item is FunctionCallResultItem;
258
258
  static isCompactBoundaryMessage(item: AgentInputItem): boolean;
259
+ /**
260
+ * 仅凭 providerData 结构化标记判定 compact boundary,不使用内容正则兜底。
261
+ *
262
+ * 会删除或改写消息的路径(如 replaceCompactWithSummary)必须用这个版本:
263
+ * 内容兜底会把用户粘贴的 `<cb_summary>` / `<conversation_history_summary>` 文本
264
+ * 误判为 boundary,导致真实用户输入被移除。
265
+ */
266
+ static isStructuredCompactBoundaryMessage(item: AgentInputItem): boolean;
259
267
  static isReplayRecoverableCompactMessage(item: AgentInputItem): item is UserMessageItem;
260
268
  static isCompactUserMessage(item: AgentInputItem): item is UserMessageItem;
261
269
  private static hasCompactBoundaryContent;
@@ -64,7 +64,9 @@ export declare class TokenUtils {
64
64
  * tool call 执行后产生的 function_call_result(这些结果在 API 返回后才追加到 history)。
65
65
  * 为了更准确地判断是否需要触发压缩,需要把这部分 token 补上。
66
66
  *
67
- * 从 history 末尾往前扫描,收集连续的 function_call_result 条目直到遇到其他类型为止。
67
+ * 从 history 末尾往前扫描,只收集紧挨在末尾的连续 function_call_result。
68
+ * 一遇到非 function_call_result(含 function_call)即停止:function_call 属于上一轮
69
+ * 已经进过请求的内容,穿过它会把更早轮次的 result 重复计入 inputTokens(#133055)。
68
70
  * 注意:估算前会移除图片内容,避免 base64 图片数据导致 token 严重偏高。
69
71
  */
70
72
  static estimateTrailingToolResultTokens(history: any[]): number;
@@ -31,6 +31,7 @@ import type { AgentOutputType, getAllMcpTools as getAllMcpToolsFn, MaxTurnsExcee
31
31
  import type { TextOutput, UnknownContext, UserContent } from '@openai/agents-core/types';
32
32
  import type { AcpTerminalStateItem, FileHistorySnapshotItem, ModelUsageItem, ResendForkNoticeItem } from './custom-input-item-types';
33
33
  export * from './custom-input-item-types';
34
+ export type { RunStreamEvent } from '@openai/agents-core';
34
35
  export type Agent<TContext = UnknownContext, TOutput extends AgentOutputType = TextOutput> = AgentTypeCtor<TContext, TOutput>;
35
36
  export type RunContext<TContext = UnknownContext> = RunContextTypeCtor<TContext>;
36
37
  export type Runner = RunnerTypeCtor;
@@ -64,4 +64,10 @@ export interface CheckpointFileChangeStats {
64
64
  additions: number;
65
65
  /** 删除行数 */
66
66
  deletions: number;
67
+ /**
68
+ * 行数为近似值(PTC/Code Mode 兜底:files 来自本轮 trackFile 快照,additions/deletions
69
+ * 暂记 0)。需要精确行数的调用方(如 TUI rewind 面板)据此异步调用
70
+ * compareWithCurrentFiles 补齐后清除本标记。仅内存态,不持久化。
71
+ */
72
+ approximate?: boolean;
67
73
  }
@@ -20,11 +20,23 @@ export declare class StreamTimeoutError extends CustomError {
20
20
  * reasoning-only:已流出思考、finish_reason=error 且无可用输出(#63761 / #122115)。
21
21
  * no-token:finish_reason=error 到达时一个模型 token 都没有(连 reasoning 也没有)。
22
22
  *
23
- * reasoning-only 与 no-token 都是上游瞬时失败,会话层按 error 恢复预算重试;
23
+ * reasoning-only 与 no-token 按「上游瞬时失败」处理,会话层按 error 恢复预算重试——
24
+ * 但仅限流没跑太久的那些:已经烧满上游硬时限的同样形态重跑必然再次跑满,由
25
+ * `isRetryableEmptyStreamError` 按 {@link EmptyStreamError.elapsedMs} 收口(#132616)。
24
26
  * placeholder 必须与 no-token 分开——两者共用一个值时,放开 no-token 会连带
25
27
  * 推翻空 200 的终态判定。
26
28
  */
27
29
  export type EmptyStreamKind = 'placeholder' | 'reasoning-only' | 'no-token';
30
+ /**
31
+ * 空流错误的结构化 category,两条上报通道共用一个值。
32
+ *
33
+ * ACP 侧 `classifyErrorAsRequestError` 早就用它(前端按此映射业务码 3008「模型服务未返回消息」);
34
+ * stream-json 侧此前没有任何结构化维度,`errors_info` 整体缺席,sandbox-proxy 的
35
+ * `BuildErrorMessageFromCLIErrors` 只能兜底成 `category=internal`,再由
36
+ * `ClassifyInBandPromptError` 推出 `error_origin=cli`——把上游故障记成 CLI 内部错误。
37
+ * 挂到错误对象的 `data` 上让两条通道读到同一个值,不再各说各话。
38
+ */
39
+ export declare const EMPTY_STREAM_ERROR_CATEGORY = "empty_model_response";
28
40
  /**
29
41
  * 空流错误
30
42
  * 语义上仍然是"上游没有提供模型输出",所以继承 StreamTimeoutError
@@ -33,10 +45,26 @@ export type EmptyStreamKind = 'placeholder' | 'reasoning-only' | 'no-token';
33
45
  * 典型触发:某些 OpenAI 兼容网关在后端异常时没有透传错误码,而是发一帧全空
34
46
  * `{"delta":{"role":"assistant","content":"","tool_calls":[],"refusal":""},"finish_reason":""}`
35
47
  * 然后直接关闭连接——用户看到的现象是 cbc 当前轮"空响应"并被 ACP 分类为 refusal。
48
+ *
49
+ * message **必须**按 kind 分开写:三种 kind 共用一句「only placeholder chunks」会谎报失败形态。
50
+ * 0924 沙箱实测的 reasoning-only 样本里上游发了 20397 帧 / 9.5 MB 真实 reasoning,
51
+ * 与「只有占位帧」正相反;而下游报表、看板、排障全靠这个字符串归因,于是把上游
52
+ * ~900s 时限问题记成了 CLI 内部错误(#132616)。
36
53
  */
37
54
  export declare class EmptyStreamError extends StreamTimeoutError {
38
55
  readonly emptyStreamKind: EmptyStreamKind;
39
- constructor(chunkCount: number, totalBytes: number, kind?: EmptyStreamKind);
56
+ /**
57
+ * 流从打开到判定空流的时长。
58
+ *
59
+ * 用来区分「上游瞬时抖动(秒级空响应)」和「跑满上游硬时限(0924 实测 ~900s)」——
60
+ * 后者重跑同一段 prompt 必然再次跑满,重试只是把静默时长翻倍,见
61
+ * `isRetryableEmptyStreamError` 的时长闸门。
62
+ */
63
+ readonly elapsedMs: number;
64
+ readonly data: Readonly<{
65
+ category: "empty_model_response";
66
+ }>;
67
+ constructor(chunkCount: number, totalBytes: number, kind?: EmptyStreamKind, elapsedMs?: number);
40
68
  }
41
69
  /**
42
70
  * 认证缺失错误
@@ -3,6 +3,7 @@ export * from './prompt-codec.js';
3
3
  export * from './prompt-context-xml.js';
4
4
  export * from './to-resolve-blocks.js';
5
5
  export * from './interactive-question-tools.js';
6
+ export * from './sandbox-rule-context.js';
6
7
  export * from './sdk.js';
7
8
  export * from './transport/streamable-http.js';
8
9
  export * from './client/index.js';
@@ -0,0 +1,38 @@
1
+ export type SandboxRuleDomain = 'file' | 'command' | 'network';
2
+ export type SandboxRuleSource = 'enterprise' | 'preset' | 'user';
3
+ export type SandboxRuleCause = {
4
+ kind: 'ordered-rule';
5
+ domain: SandboxRuleDomain;
6
+ ruleRef: string;
7
+ } | {
8
+ kind: 'sensitive-rule';
9
+ ruleId: string;
10
+ source?: SandboxRuleSource;
11
+ } | {
12
+ kind: 'policy';
13
+ code: string;
14
+ };
15
+ export interface SandboxRuleContext {
16
+ causes: SandboxRuleCause[];
17
+ }
18
+ export interface FileApprovalScope {
19
+ directory: string;
20
+ operation: 'read' | 'write' | 'delete';
21
+ recursive: boolean;
22
+ lifetime: 'session';
23
+ }
24
+ export declare const SANDBOX_RULE_CONTEXT_META_KEY = "codebuddy.ai/sandboxRuleContext";
25
+ export declare const FILE_APPROVAL_SCOPE_META_KEY = "codebuddy.ai/fileApprovalScope";
26
+ /** 仅复制显示所需字段,不能将归因标识作为授权凭证。 */
27
+ export declare function parseSandboxRuleContext(value: unknown): SandboxRuleContext | undefined;
28
+ export declare function parseFileApprovalScope(value: unknown): FileApprovalScope | undefined;
29
+ /**
30
+ * 目录授权的专用应答 optionId,不出现在 requestPermission 的选项列表中。
31
+ * 只有展示了 fileApprovalScope 的卡片会回传它;按选项 kind 自动应答的 IM、
32
+ * 自动化或旧 UI 选不到它,因而无法替用户登记目录授权。
33
+ */
34
+ export declare const FILE_DIRECTORY_APPROVAL_OPTION_ID = "allow_directory";
35
+ export declare function parseSandboxPermissionMetadata(meta: unknown): {
36
+ ruleContext?: SandboxRuleContext;
37
+ fileApprovalScope?: FileApprovalScope;
38
+ };
@@ -1,7 +1,7 @@
1
1
  import { RestOperations } from '@celljs/http';
2
2
  import { AuthenticationType, ClientInfoProvider, ProductConfiguration, ProductManager } from '../../../product/lib/common/index.js';
3
3
  import { ExternalUriOpener } from '../../../runtime/lib/common/index.js';
4
- import { Logger } from '../../../telemetry/lib/common/index.js';
4
+ import { Logger, type Span } from '../../../telemetry/lib/common/index.js';
5
5
  import { Account, APIResult, AuthenticationProvider, AuthSession, AuthState, AuthToken, LoginContext, LogoutOptions, ProductEnvService, SignContext } from './authentication-protocol.js';
6
6
  /**
7
7
  * External-link auth variant whose current account is scoped by the token.
@@ -29,11 +29,11 @@ export declare class AccountScopedExternalLinkAuthenticationProvider implements
29
29
  removeSession(_session?: AuthSession, _options?: LogoutOptions): Promise<void>;
30
30
  switchAccount(account: Account, authSession: AuthSession, ctx: SignContext): Promise<AuthSession>;
31
31
  private toSessionAccountLists;
32
- protected openAuthUrl(authState: AuthState): Promise<void>;
32
+ protected openAuthUrl(authState: AuthState, handoffSpan?: Span): Promise<void>;
33
33
  private fetchAuthState;
34
34
  private loopGetToken;
35
35
  private loopGetCurrentAccount;
36
- protected fetchCurrentAccount(auth: AuthToken, ctx: SignContext): Promise<Account>;
36
+ protected fetchCurrentAccount(auth: AuthToken, ctx: SignContext, requestSpan?: Span): Promise<Account>;
37
37
  protected enterpriseHeaders(auth?: AuthToken): Record<string, string>;
38
38
  protected calculateExpiresAt(authToken: AuthToken): void;
39
39
  private isAuthenticationInvalidError;
@@ -18,6 +18,12 @@ import { Account, APIResult, AuthenticationManager, AuthenticationProvider, type
18
18
  */
19
19
  export declare function setAuthDoInitProbeSink(sink: ((line: string) => void) | undefined): void;
20
20
  export declare class AuthenticationManagerImpl implements AuthenticationManager {
21
+ /** Host observation hook, called after currentSessionSubject published the session. No-op by default. */
22
+ protected observeSession(_session: AuthSession | undefined, _source: string, _observation?: unknown): void;
23
+ /** Captures host metadata while the storage publisher's synchronous context is available. */
24
+ protected captureSessionObservation(): unknown;
25
+ private notifySessionObserver;
26
+ private safelyCaptureSessionObservation;
21
27
  protected readonly productManager: ProductManager;
22
28
  protected readonly productEnvService: ProductEnvService;
23
29
  protected readonly authenticationProvider: Provider<AuthenticationProvider>;
@@ -0,0 +1,36 @@
1
+ import { type Span } from '../../../telemetry/lib/common/index.js';
2
+ /** Login observation helpers. Every export swallows its own failures; authentication never depends on them. */
3
+ /** W3C context for the login chain only; the shared Span.requestHeaders stay legacy-only. */
4
+ export declare function loginTraceCarrier(span?: Span): {
5
+ traceparent?: string;
6
+ tracestate?: string;
7
+ };
8
+ /** Only for a host that registered login observation; other products keep their legacy login trace unchanged. */
9
+ export declare function addLoginSpanEvent(span: Span | undefined, name: string, attributes?: Record<string, string>): void;
10
+ /** Host login observation context registered together with setLoginStepCallback. */
11
+ export interface LoginObservationContext {
12
+ /** Reauthentication correlation (`recovery_of_loss_id` / `previous_auth_session_id`). */
13
+ recovery?: Record<string, string>;
14
+ /** The host's login attempt ID; the web login page records it as the owner of its journey. */
15
+ journeyOwnerId?: string;
16
+ /** Entry context of the host-owned login journey. */
17
+ traceparent?: string;
18
+ }
19
+ export declare function setLoginObservationContext(context?: LoginObservationContext): void;
20
+ export declare function appendLoginTraceParams(url: URL, span?: Span): void;
21
+ /** Web login page parameters that join the host login journey. */
22
+ export declare function appendLoginObservationParams(url: URL, handoffSpan?: Span): void;
23
+ /** Narrow host hook: no credential/header objects or telemetry implementation cross this boundary. */
24
+ export interface AuthRequestObservationInput {
25
+ method?: string;
26
+ url?: string;
27
+ traceparent?: string;
28
+ }
29
+ export type AuthRequestObservation = (request: AuthRequestObservationInput) => ((status?: number, businessCode?: number) => void) | undefined;
30
+ export declare function setAuthRequestObservation(observer?: AuthRequestObservation): void;
31
+ export declare function observeAuthRequest(config: {
32
+ method?: string;
33
+ url?: string;
34
+ headers?: Record<string, unknown>;
35
+ }): void;
36
+ export declare function observeAuthResponse(config: unknown, status?: number, businessCode?: unknown): void;
@@ -67,6 +67,27 @@ export declare const HTTP_HEADER_NO_AUTHORIZATION = "X-No-Authorization";
67
67
  * 用于请求发往自定义端点(如 LiteLLM 网关)时,避免携带 copilot 内部认证信息。
68
68
  */
69
69
  export declare const HTTP_HEADER_SKIP_AUTH_INTERCEPTOR = "X-Skip-Auth-Interceptor";
70
+ /**
71
+ * `auth/state` 额外请求头数据源(可选 DI 依赖,中立抽象;Issue #94672)。
72
+ *
73
+ * authentication 包对具体头一无所知:只负责在登录链路的 `auth/state` 请求上
74
+ * 把本 provider 返回的所有 header 原样透传。**具体带哪些头、值怎么取,全部由
75
+ * 业务侧(WorkBuddy Desktop daemon 装配层)在实现里决定**,让上游 authentication
76
+ * 包无需反向依赖 Electron / Turing / qimei 等下游能力。
77
+ *
78
+ * 由宿主**可选**绑定到 CellJS 容器;未绑定(CLI / Web / headless / 单测)时按
79
+ * `@Optional()` 注入为 undefined,`auth/state` 不携带任何额外 header,对这些形态
80
+ * 零影响。
81
+ *
82
+ * 语义约定:**尽力而为、不等待、不阻断登录**。`provide()` 应立即返回当前快照
83
+ * (读缓存 / env),拿不到的头业务侧自己省略即可;内部异常由 authentication 包
84
+ * 兜底吞掉,绝不因遥测公参阻断登录。
85
+ */
86
+ export declare const AuthStateHeaderProvider: unique symbol;
87
+ export interface AuthStateHeaderProvider {
88
+ /** 返回要附加到 `auth/state` 请求上的额外 header 集合(可能为空)。 */
89
+ provide(): Promise<Record<string, string>>;
90
+ }
70
91
  export declare const enum Edition {
71
92
  Pro = "pro",
72
93
  Personal = "personal",
@@ -1,8 +1,9 @@
1
1
  import { RestOperations } from '@celljs/http';
2
2
  import { AuthenticationType, ClientInfoProvider, ProductManager } from '../../../product/lib/common/index.js';
3
3
  import { ExternalUriOpener } from '../../../runtime/lib/common/index.js';
4
- import { Logger } from '../../../telemetry/lib/common/index.js';
5
- import { Account, APIResult, AuthenticationProvider, AuthSession, LoginContext, LogoutOptions, ProductEnvService, SignContext, SignLicenseError } from './authentication-protocol.js';
4
+ import { Logger, type Span } from '../../../telemetry/lib/common/index.js';
5
+ import { type LoginObservationContext } from './authentication-observation.js';
6
+ import { Account, APIResult, AuthenticationProvider, AuthSession, AuthStateHeaderProvider, LoginContext, LogoutOptions, ProductEnvService, SignContext, SignLicenseError } from './authentication-protocol.js';
6
7
  /** 登录漏斗步骤回调,由外部消费者(如 workbuddy-server)注入上报逻辑。 */
7
8
  export type LoginStepCallback = (step: string, dims: Record<string, string>) => void;
8
9
  /**
@@ -10,9 +11,14 @@ export type LoginStepCallback = (step: string, dims: Record<string, string>) =>
10
11
  * @param callback 回调函数,undefined 表示清除
11
12
  * @param onlyIfVersion 可选,传入时只有当前 version 匹配才执行清除(防止旧轮 finally 覆盖新轮)
12
13
  * @param loginSessionId 可选,当前登录会话 ID,供 openAuthUrl 注入到 authUrl 中传递给 Web 登录页
14
+ * @param observation 可选,宿主登录观测上下文,与回调同生命周期
13
15
  * @returns 设置后的 version
14
16
  */
15
- export declare function setLoginStepCallback(callback: LoginStepCallback | undefined, onlyIfVersion?: number, loginSessionId?: string): number;
17
+ export declare function setLoginStepCallback(callback: LoginStepCallback | undefined, onlyIfVersion?: number, loginSessionId?: string, observation?: LoginObservationContext): number;
18
+ /** Whether the host registered login observation; other products keep their login URLs unchanged. */
19
+ export declare function hasHostLoginObservation(): boolean;
20
+ /** 让 Web 登录页加入宿主登录 journey(仅国内版 workbuddy 平台);宿主未注册观测时不改 URL。 */
21
+ export declare function appendHostLoginJourneyParams(url: URL, platform: string | undefined, handoffSpan?: Span): void;
16
22
  interface AuthState {
17
23
  state: string;
18
24
  authUrl: string;
@@ -35,6 +41,11 @@ export declare class ExternalLinkAuthenticationProvider implements Authenticatio
35
41
  protected readonly restOperations: RestOperations;
36
42
  protected readonly logger: Logger;
37
43
  protected readonly clientInfoProvider: ClientInfoProvider;
44
+ /**
45
+ * `auth/state` 额外请求头数据源(Issue #94672)。可选依赖:仅 WorkBuddy Desktop
46
+ * daemon 绑定,CLI / Web / headless / 单测未绑定时为 undefined,不携带额外 header。
47
+ */
48
+ protected readonly authStateHeaderProvider?: AuthStateHeaderProvider;
38
49
  private configuration;
39
50
  /**
40
51
  * The last auth URL that was opened in the browser.
@@ -57,8 +68,13 @@ export declare class ExternalLinkAuthenticationProvider implements Authenticatio
57
68
  refreshSession(session: AuthSession, ctx: SignContext): Promise<AuthSession>;
58
69
  removeSession(session?: AuthSession, options?: LogoutOptions): Promise<void>;
59
70
  switchAccount(account: Account, authSession: AuthSession, ctx: SignContext): Promise<AuthSession>;
71
+ /**
72
+ * 取 `auth/state` 的额外请求头(Issue #94672)。provider 未绑定(CLI / Web /
73
+ * headless / 单测)返回空对象;实现内部任何异常都吞掉退化为空,绝不阻断登录。
74
+ */
75
+ private resolveAuthStateExtraHeaders;
60
76
  private fetchAuthState;
61
- protected openAuthUrl(authState: AuthState): Promise<void>;
77
+ protected openAuthUrl(authState: AuthState, handoffSpan?: Span): Promise<void>;
62
78
  /**
63
79
  * 打开登录页前对 authUrl 追加环境相关参数的可覆写钩子。
64
80
  * 基类默认不追加任何参数;子类(如 CLI IOA 分支)覆写此方法即可注入自己的 query,
@@ -10,3 +10,4 @@ export * from './custom-token-authentication-storage.js';
10
10
  export * from './wx-authentication-provider.js';
11
11
  export * from './product-env-service.js';
12
12
  export * from './account-utils.js';
13
+ export * from './authentication-observation.js';
@@ -30,6 +30,7 @@ export interface CheckpointService {
30
30
  * @param options.autoAddToHistory - 是否自动添加到 session history (默认 true)
31
31
  * @param options.messageId - 快照关联的消息ID (默认为空)
32
32
  * @param options.isSnapshotUpdate - 是否为快照更新 (默认 false)
33
+ * @param options.filePath - 只更新该路径的文件版本 (默认更新全部已跟踪文件)
33
34
  * @returns 创建的 checkpoint,无需创建时返回 undefined
34
35
  */
35
36
  createCheckpoint(session: Session, options?: {
@@ -37,6 +38,7 @@ export interface CheckpointService {
37
38
  throwOnError?: boolean;
38
39
  messageId?: string;
39
40
  isSnapshotUpdate?: boolean;
41
+ filePath?: string;
40
42
  }): Promise<Checkpoint | undefined>;
41
43
  /** 回退到指定 checkpoint */
42
44
  revertToCheckpoint(session: Session, checkpoint: Checkpoint, scope: RevertScope): Promise<void>;
@@ -16,6 +16,7 @@ export declare class CheckpointServiceImpl implements CheckpointService {
16
16
  throwOnError?: boolean;
17
17
  messageId?: string;
18
18
  isSnapshotUpdate?: boolean;
19
+ filePath?: string;
19
20
  }): Promise<Checkpoint | undefined>;
20
21
  revertToCheckpoint(session: Session, checkpoint: Checkpoint, scope: import('./checkpoint-protocol.js').RevertScope): Promise<void>;
21
22
  getRewindableCheckpoints(session: Session): Checkpoint[];
@@ -550,6 +550,19 @@ export interface AgentServiceRunControlOptions {
550
550
  bypassMessageQueue?: boolean;
551
551
  /** Input is already present in Session history; do not append it again. */
552
552
  skipAddHistory?: boolean;
553
+ /** Let an interactive host route external `/compact` before normal run admission. */
554
+ routeManualCompact?: boolean;
555
+ /**
556
+ * Per-call out-signal of `runDefault`: invoked once, synchronously, after
557
+ * this call passed run admission (its startup controller is installed on
558
+ * the Session) and before the agent is resolved. Not invoked when admission
559
+ * throws. It says nothing about the model having started or the run
560
+ * succeeding; without `bypassMessageQueue` the run may still be queued
561
+ * afterwards (see `onEnqueued`). A throwing callback is logged and does not
562
+ * affect the run. Internal re-runs pass fresh options and never carry it; it
563
+ * is stripped before AgentRunRequest and the SDK.
564
+ */
565
+ onAdmitted?: () => void;
553
566
  }
554
567
  /** Options for an isolated run or an SDK RunState resume. */
555
568
  export type AgentStandardRunOptions<TContext = Session> = AgentSdkRunOptions<TContext> & AgentServiceRunControlOptions & {
@@ -566,6 +579,8 @@ export type AgentStandardRunOptions<TContext = Session> = AgentSdkRunOptions<TCo
566
579
  * cannot clobber each other's outcome.
567
580
  */
568
581
  onEnqueued?: () => void;
582
+ /** Exact result of this arrival, including execution after a queue drain. */
583
+ onResult?: (result: NonNullable<Session['resultSubject']['value']>) => void;
569
584
  };
570
585
  /**
571
586
  * Explicitly claim the current process-local logical turn.
@@ -585,12 +600,19 @@ export interface AgentService {
585
600
  tryCloseTaskSession?(session: Session, result: NonNullable<Session['resultSubject']['value']>): Promise<boolean>;
586
601
  /** Stop accepting task work and join its physical runs before releasing dependencies. */
587
602
  retireTaskSession?(session: Session): Promise<void>;
603
+ /**
604
+ * 有界等待该 session 上的物理 run 收尾(含它把最终产出写进 history)。
605
+ *
606
+ * `agent_end` 早于 run 的 finalize,所以「上一轮 history 已写完」不能靠 `agent_end`
607
+ * 判定;需要该因果的调用方(队列 drain)join 到这里。超时会放行并告警,不会挂死。
608
+ */
609
+ waitForRunsSettled?(session: Session): Promise<void>;
588
610
  run<TAgent extends Agent<any, any>>(agent: TAgent, input: string | AgentInputItem[], options: AgentCurrentContinuationOptions): Promise<void>;
589
611
  run<TAgent extends Agent<any, any>, TContext = Session>(agent: TAgent, input: string | AgentInputItem[] | RunState<TContext, TAgent>, options?: AgentStandardRunOptions<TContext>): Promise<void>;
590
612
  runDefault<TAgent extends Agent<any, any>>(input: string | AgentInputItem[], options: AgentCurrentContinuationOptions): Promise<void>;
591
613
  runDefault<TAgent extends Agent<any, any>, TContext = Session>(input: string | AgentInputItem[] | RunState<TContext, TAgent>, options?: AgentStandardRunOptions<TContext>): Promise<void>;
592
- runOneTime<TContext = Session>(agentName: string, input: string | AgentInputItem[], options?: NonStreamRunOptions<TContext>): Promise<string>;
593
- runOneTime<TContext = Session>(agentName: string, input: string | AgentInputItem[], options?: StreamRunOptions<TContext>): Promise<string>;
614
+ runOneTime<TContext = Session>(agentName: string, input: string | AgentInputItem[], options?: NonStreamRunOptions<TContext> & OneTimeRunOptions): Promise<string>;
615
+ runOneTime<TContext = Session>(agentName: string, input: string | AgentInputItem[], options?: StreamRunOptions<TContext> & OneTimeRunOptions): Promise<string>;
594
616
  /**
595
617
  * Run a one-shot agent call in a forked (isolated) session that inherits
596
618
  * the conversation history from the parent session. The forked session is
@@ -656,6 +678,11 @@ export interface ForkedAgentOptions {
656
678
  /** Optional cap on number of turns (default: 1 for one-shot) */
657
679
  maxTurns?: number;
658
680
  }
681
+ /** Options of `runOneTime` on top of the SDK run options. */
682
+ export interface OneTimeRunOptions {
683
+ /** X-Agent-Purpose of the call; defaults to the agent's `AGENT_PURPOSE_MAP` entry, else its name. */
684
+ purpose?: string;
685
+ }
659
686
  export interface RunRequest {
660
687
  prompt?: string;
661
688
  inputFormat?: 'text' | 'stream-json';
@@ -697,6 +724,8 @@ export interface AgentRunRequest<TContext = Session> extends SessionOptions {
697
724
  skipAddHistory?: boolean;
698
725
  bypassMessageQueue?: boolean;
699
726
  inputOrigin?: AgentRunOrigin;
727
+ /** Process-local arrival callback; never passed to the SDK. */
728
+ onResult?: AgentStandardRunOptions['onResult'];
700
729
  traceId?: string;
701
730
  /**
702
731
  * #59319-5: 普通 run 二次裁决发现 session 仍 busy 时由 AgentService 设置。
@@ -58,7 +58,9 @@ export declare enum AgentPurpose {
58
58
  /** Auto mode permission risk classification (runOneTime: AUTO_MODE_CLASSIFIER) */
59
59
  AutoModeClassifier = "auto_mode_classifier",
60
60
  /** Automation scheduled task execution */
61
- Automation = "automation"
61
+ Automation = "automation",
62
+ /** `/btw` side question on a forked Session (runForked); Claude Code's `side_question` source */
63
+ SideQuestion = "side_question"
62
64
  }
63
65
  /**
64
66
  * Dynamic purpose prefix for built-in subagents.
@@ -127,6 +129,9 @@ export declare const AUXILIARY_PURPOSES: ReadonlySet<string>;
127
129
  * 时 purpose 可能尚未设置的普通对话仍按原行为发出 MODEL_REQUEST_STARTED。
128
130
  */
129
131
  export declare function isAuxiliaryPurpose(purpose?: string): boolean;
132
+ /** Purposes of compaction summary calls (X-Agent-Type `compaction`). */
133
+ export declare const COMPACTION_PURPOSES: ReadonlySet<string>;
134
+ export declare function isCompactionPurpose(purpose?: string): boolean;
130
135
  /**
131
136
  * 按 purpose 旁路 agent 生命周期事件(agent_start / agent_end / tool / handoff)。
132
137
  *
@@ -145,9 +150,8 @@ export declare function isAuxiliaryPurpose(purpose?: string): boolean;
145
150
  *
146
151
  * 因此这里只收 PreMessage 这一种 purpose。
147
152
  *
148
- * 依赖前提:`PreMessageCompactStrategy` 在 runOneTime 前后设置 / 还原
149
- * `session.agentPurpose`,且用 try/finally 保证异常路径也会还原——否则 purpose 泄漏
150
- * 会让**主 run** 也被误旁路,反而放大本要修复的孤儿 run 问题。
153
+ * The purpose is scoped to the summary call (`runOneTime` → `runWithAgentPurpose`), so it
154
+ * cannot leak onto the pending main run.
151
155
  *
152
156
  * multi-session(#44317)回归时,PreMessage 承载应改回临时子 Session;本名单保留为
153
157
  * 冗余防线即可(临时 Session 上旁路是无害的)。
@@ -0,0 +1,46 @@
1
+ import type { AgentType } from '../../../../telemetry/lib/common/index.js';
2
+ interface PurposeCarrier {
3
+ agentPurpose?: string;
4
+ conversationRequestId?: string;
5
+ }
6
+ /**
7
+ * Runs an auxiliary model call (title, summary, WebFetch analysis, ...) on a
8
+ * caller-owned Session without writing its purpose / request id onto the shared
9
+ * Session, where a concurrent main run would read and send them as its own.
10
+ */
11
+ export declare function runWithAgentPurpose<T>(session: object, purpose: string, callback: () => T, options?: {
12
+ conversationRequestId?: string;
13
+ }): T;
14
+ /** True when the current async chain is an auxiliary call scoped to `session`. */
15
+ export declare function isInAgentPurposeScope(session: object | undefined): boolean;
16
+ /** Purpose of the model call running in the current async chain. */
17
+ export declare function getEffectiveAgentPurpose(session: PurposeCarrier | undefined): string | undefined;
18
+ /** Request id of the model call running in the current async chain. */
19
+ export declare function getEffectiveConversationRequestId(session: PurposeCarrier | undefined): string | undefined;
20
+ /** Purposes whose model calls are steps of a Session's own agent loop. */
21
+ export declare function isMainConversationPurpose(purpose: string | undefined): boolean;
22
+ /** True when the model call in the current async chain is a step of `session`'s agent loop. */
23
+ export declare function isMainLoopModelCall(session: PurposeCarrier | undefined): boolean;
24
+ /** True when the model call in the current async chain has an `AUXILIARY_PURPOSES` purpose. */
25
+ export declare function isAuxiliaryPurposeCall(session: PurposeCarrier | undefined): boolean;
26
+ /**
27
+ * Runs `callback` outside any purpose scope. A run started from a helper call's async
28
+ * chain (e.g. a queued message drained on its agent_end) is a new agent-loop run.
29
+ */
30
+ export declare function runOutsideAgentPurposeScope<T>(callback: () => T): T;
31
+ export type ModelCallAgentType = AgentType;
32
+ /** Role of the Session's own agent loop, for request-level events. */
33
+ export declare function resolveSessionAgentType(session: {
34
+ meta?: Record<string, unknown>;
35
+ }): 'main' | 'subagent' | 'team';
36
+ /**
37
+ * Role of the model call in the current async chain (X-Agent-Type / telemetry
38
+ * `agentType`), mirroring Claude Code's `x-claude-code-request-class`: compaction
39
+ * summaries report `compaction`, other one-shot helpers (title, WebFetch analysis,
40
+ * ...) report `auxiliary`, whatever Session they run on. The specific helper
41
+ * stays in X-Agent-Purpose.
42
+ */
43
+ export declare function resolveModelCallAgentType(session: PurposeCarrier & {
44
+ meta?: Record<string, unknown>;
45
+ }): ModelCallAgentType;
46
+ export {};
@@ -3,10 +3,11 @@ import { AuthenticationManager } from '../../../../authentication/lib/common/ind
3
3
  import { type AbortLinkDisposer, Agent, type AgentInputItem, type NonStreamRunOptions, RunState, type StreamRunOptions } from '../../../../cbc-shared/lib/node/index.js';
4
4
  import { type LanguageModel } from '../../../../product/lib/common/index.js';
5
5
  import { Logger } from '../../../../telemetry/lib/common/index.js';
6
+ import { type ManualCompactRequestHandler as ManualCompactRequestHandlerContract } from '../context/context-protocol.js';
6
7
  import { type FileRollbackOperationLock as FileRollbackOperationLockContract } from '../file-rollback/file-rollback-service-protocol.js';
7
8
  import { Session, SessionManager } from '../session/session-protocol.js';
8
9
  import { SessionRunStateMachine } from '../session/session-run-state-machine-protocol.js';
9
- import { type AgentCurrentContinuationOptions, AgentManager, AgentRunInterceptor, AgentRunRequest, AgentService, type AgentStandardRunOptions, RunnerProvider } from './agent-protocol.js';
10
+ import { type AgentCurrentContinuationOptions, AgentManager, AgentRunInterceptor, AgentRunRequest, AgentService, type AgentStandardRunOptions, type OneTimeRunOptions, RunnerProvider } from './agent-protocol.js';
10
11
  import { type AgentRunScope as IAgentRunScope } from './agent-run-scope.js';
11
12
  import { AgentPluginRefresh, AgentRunObserver, AgentRuntimeResolver } from './agent-runtime-protocol.js';
12
13
  export declare class AgentServiceImpl implements AgentService {
@@ -22,6 +23,7 @@ export declare class AgentServiceImpl implements AgentService {
22
23
  protected readonly agentRunInterceptorProvider: Provider<AgentRunInterceptor>;
23
24
  protected readonly fileRollbackOperationLock?: FileRollbackOperationLockContract;
24
25
  protected readonly logger: Logger;
26
+ protected readonly manualCompactRequestHandler?: ManualCompactRequestHandlerContract;
25
27
  /**
26
28
  * Preserve the pre-start cancellation snapshot across runDefault's agent
27
29
  * lookup controller and run()'s own controller. This is process-local
@@ -40,6 +42,20 @@ export declare class AgentServiceImpl implements AgentService {
40
42
  protected getLifecycleOwners(): WeakMap<Session, AbortController>;
41
43
  tryCloseTaskSession(session: Session, result: NonNullable<Session['resultSubject']['value']>): Promise<boolean>;
42
44
  retireTaskSession(session: Session): Promise<void>;
45
+ waitForRunsSettled(session: Session): Promise<void>;
46
+ /**
47
+ * 有界 join:等到该 session 上的物理 run 全部交还 lifecycle owner 与 in-flight 信号。
48
+ *
49
+ * 为什么需要它而不是直接看 `agent_end`:`finalizeRun` 晚于本轮把最终产出写进
50
+ * history,`agent_end` 却早于 `finalizeRun`。任何依赖「上一轮 history 已写完」这个
51
+ * 因果的调用方(如队列 drain)必须 join 到这里。
52
+ *
53
+ * Bounded: `runSettledSubject` is optional, so a session built without
54
+ * one has nothing to observe and would hang the caller's cleanup — which
55
+ * owns hook, MCP and background-shell teardown. `agent_end` 也可能来自没有物理
56
+ * run 的路径(skipRun / 迟到事件),无界等待会把调用方永久挂住。
57
+ */
58
+ private joinRunsSettled;
43
59
  /** compare-and-delete:仅当 token 仍指向本轮 controller 时清除。 */
44
60
  private clearLifecycleOwner;
45
61
  /** 本轮是否是当前 lifecycle owner。 */
@@ -156,6 +172,7 @@ export declare class AgentServiceImpl implements AgentService {
156
172
  protected resolveRunOneTimeModel(agentName: string, session?: Session): Promise<LanguageModel>;
157
173
  run<TAgent extends Agent<any, any>>(agent: TAgent, input: string | AgentInputItem[], options: AgentCurrentContinuationOptions): Promise<void>;
158
174
  run<TAgent extends Agent<any, any>, TContext = Session>(agent: TAgent, input: string | AgentInputItem[] | RunState<TContext, TAgent>, options?: AgentStandardRunOptions<TContext>): Promise<void>;
175
+ private runPipeline;
159
176
  /**
160
177
  * #59319-stream: 抽取的 physical run cleanup 逻辑。
161
178
  * 非 stream 路径由 run() finally 同步调用;
@@ -189,8 +206,14 @@ export declare class AgentServiceImpl implements AgentService {
189
206
  private prepareRunAdmission;
190
207
  runDefault<TAgent extends Agent<any, any>>(input: string | AgentInputItem[], options: AgentCurrentContinuationOptions): Promise<void>;
191
208
  runDefault<TAgent extends Agent<any, any>, TContext = Session>(input: string | AgentInputItem[] | RunState<TContext, TAgent>, options?: AgentStandardRunOptions<TContext>): Promise<void>;
192
- runOneTime<TContext = Session>(agentName: string, input: string | AgentInputItem[], options?: NonStreamRunOptions<TContext>): Promise<string>;
193
- runOneTime<TContext = Session>(agentName: string, input: string | AgentInputItem[], options?: StreamRunOptions<TContext>): Promise<string>;
209
+ /**
210
+ * Streams the text of a one-shot run on `session`. A reused caller Session is shared
211
+ * with its in-flight main run, so the call's purpose and request id live in its async
212
+ * scope instead of on the Session.
213
+ */
214
+ private streamOneTimeText;
215
+ runOneTime<TContext = Session>(agentName: string, input: string | AgentInputItem[], options?: NonStreamRunOptions<TContext> & OneTimeRunOptions): Promise<string>;
216
+ runOneTime<TContext = Session>(agentName: string, input: string | AgentInputItem[], options?: StreamRunOptions<TContext> & OneTimeRunOptions): Promise<string>;
194
217
  /**
195
218
  * Enhanced version of runOneTime that supports per-request overrides
196
219
  * for temperature, maxTokens, maxTurns, systemPrompt, and bypassPermissions.
@@ -1,5 +1,8 @@
1
1
  export * from './agent-protocol.js';
2
2
  export * from './agent-purpose-protocol.js';
3
+ export * from './agent-purpose-scope.js';
4
+ export * from './model-step-sequence.js';
5
+ export * from './model-call-failure.js';
3
6
  export * from './agent-runtime-protocol.js';
4
7
  export * from './agent-run-scope.js';
5
8
  export * from './agent-service.js';
@@ -0,0 +1,9 @@
1
+ import type { ModelCallGeneration } from '../session/session-protocol.js';
2
+ /**
3
+ * Marks `error` as the failure of one model call. The call's ids live in the model-call
4
+ * async scope, which does not reach the consumer of the SDK run stream; the error does.
5
+ * An error rethrown through an outer call keeps the innermost call's mark.
6
+ */
7
+ export declare function markModelCallFailure<T>(error: T, sessionId: string, generation: ModelCallGeneration): T;
8
+ /** The model call of this Session that failed with `error`; undefined when the failure is not one. */
9
+ export declare function getFailedModelCall(error: unknown, sessionId: string): ModelCallGeneration | undefined;
@@ -0,0 +1,11 @@
1
+ import type { Session } from '../session/session-protocol.js';
2
+ type StepSequenceSession = Pick<Session, 'id' | 'history' | 'agentPurpose' | 'modelStepSeq'>;
3
+ /** Latest step of the Session's agent loop, restored from persisted history after resume. */
4
+ export declare function currentModelStepSeq(session: StepSequenceSession): number;
5
+ /**
6
+ * Step number for the model call in the current async chain. Agent-loop calls
7
+ * advance the counter; auxiliary calls reuse the latest step. The counter never
8
+ * resets across runs, compaction continuations or teammate wake-ups.
9
+ */
10
+ export declare function allocateModelStepSeq(session: StepSequenceSession): number;
11
+ export {};