zcodeSessionProjection.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /* oxlint-disable eslint(max-lines) -- ZCode session 到当前聊天 projection 的迁移桥需要同时保持 snapshot 和 event 映射一致。 */
  2. import {
  3. decodeCustomModelValue,
  4. deriveZCodeTaskStatusFromSessionSnapshot,
  5. generateTraceId,
  6. parseModelPickerValue as parseSharedModelSelection,
  7. formatModelPickerValue as formatSharedModelSelection,
  8. resolveZCodeVisibleSessionTitle,
  9. ZCODE_AGENT_PROVIDER,
  10. type ZCodeConfigOption,
  11. type ZCodeTaskGoal,
  12. type ZCodeTaskMode,
  13. type ZCodeTaskModeInfo,
  14. type ZCodeTaskMeta,
  15. type ZCodeMessageWithParts,
  16. type ModelSelection,
  17. type ZCodeSessionMode,
  18. type ZCodeSessionSettingsState,
  19. type ZCodeSessionStateSnapshot,
  20. } from "@zcode/shared";
  21. const MODEL_CONFIG_ID = "model";
  22. const THOUGHT_LEVEL_CONFIG_ID = "thought_level";
  23. const MODE_CONFIG_ID = "mode";
  24. const ZCODE_AGENT_MODE_OPTIONS = [
  25. {
  26. id: "build",
  27. name: "Ask before changes",
  28. description: "Ask before each file changes.",
  29. },
  30. {
  31. id: "edit",
  32. name: "Edit automatically",
  33. description: "Edit selected files or relevant workspace files automatically.",
  34. },
  35. {
  36. id: "plan",
  37. name: "Plan mode",
  38. description: "Inspect the code and present a plan before editing.",
  39. },
  40. {
  41. id: "yolo",
  42. name: "Full access",
  43. description: "Edit and run commands with fewer confirmations.",
  44. },
  45. ] as const satisfies readonly ZCodeTaskModeInfo[];
  46. const ZCODE_AGENT_MODE_ID_SET = new Set<string>(ZCODE_AGENT_MODE_OPTIONS.map((mode) => mode.id));
  47. export function formatModelPickerValue(ref: ModelSelection | undefined): string {
  48. return formatSharedModelSelection(ref);
  49. }
  50. function resolveLatestMessageModelSelection(
  51. messages: readonly ZCodeMessageWithParts[],
  52. ): ModelSelection | undefined {
  53. for (let index = messages.length - 1; index >= 0; index -= 1) {
  54. const model = messages[index]?.info.model;
  55. if (model) {
  56. return model;
  57. }
  58. }
  59. return undefined;
  60. }
  61. function resolveTaskMetaModelSelectionFromSnapshot(
  62. snapshot: ZCodeSessionStateSnapshot,
  63. ): ModelSelection | undefined {
  64. // 历史 resume 被错误 runtimeModel 覆盖时,settings.current 会变成 app 当前默认模型,
  65. // 但消息 info.model 仍记录真实使用的模型。task meta 会作为下次冷恢复 hint,
  66. // 因此优先用最近消息模型让已污染的历史记录自愈。
  67. return resolveLatestMessageModelSelection(snapshot.messages) ?? snapshot.settings.model.current;
  68. }
  69. export function parseModelPickerValue(value: string): ModelSelection {
  70. const customModel = decodeCustomModelValue(value);
  71. if (customModel?.providerId && customModel.modelName) {
  72. // UI 自定义模型值是展示态 custom:provider:model,
  73. // ZCode Protocol 必须收到严格的 providerId/modelId 结构。
  74. return {
  75. providerId: customModel.providerId,
  76. modelId: customModel.modelName,
  77. };
  78. }
  79. return parseSharedModelSelection(value);
  80. }
  81. export function zcodeSessionSettingsToConfigOptions(
  82. settings: ZCodeSessionSettingsState,
  83. ): ZCodeConfigOption[] {
  84. const configOptions: ZCodeConfigOption[] = [
  85. {
  86. id: MODEL_CONFIG_ID,
  87. name: "Model",
  88. category: "model",
  89. type: "select",
  90. currentValue: formatModelPickerValue(settings.model.current),
  91. options: settings.model.available.map((model) => {
  92. const modelThoughtLevels = model.reasoning?.levels.map((level) => level.value);
  93. const modelDefaultThoughtLevel =
  94. model.reasoning?.defaultLevel &&
  95. modelThoughtLevels?.includes(model.reasoning.defaultLevel)
  96. ? model.reasoning.defaultLevel
  97. : undefined;
  98. return {
  99. value: formatModelPickerValue(model.ref),
  100. name: model.label,
  101. description: model.description,
  102. modelProviderId: model.ref.providerId,
  103. modelProviderName: model.providerLabel ?? model.ref.providerId,
  104. ...(modelThoughtLevels ? { modelThoughtLevels } : {}),
  105. ...(modelDefaultThoughtLevel ? { modelDefaultThoughtLevel } : {}),
  106. };
  107. }),
  108. },
  109. {
  110. id: MODE_CONFIG_ID,
  111. name: "Mode",
  112. category: "mode",
  113. type: "select",
  114. currentValue: normalizeAvailableZCodeMode(settings.mode.current),
  115. options: getZCodeAgentModeSelectOptions(),
  116. },
  117. ];
  118. if (settings.thoughtLevel.enabled) {
  119. configOptions.push({
  120. id: THOUGHT_LEVEL_CONFIG_ID,
  121. name: "Thought Level",
  122. category: "thought_level",
  123. type: "select",
  124. currentValue: resolveSettingsThoughtLevelCurrentValue(settings.thoughtLevel) ?? "",
  125. options: settings.thoughtLevel.available.map((level) => ({
  126. value: level.value,
  127. name: level.label,
  128. description: level.description,
  129. })),
  130. });
  131. }
  132. return configOptions;
  133. }
  134. export function zcodeWorkspacePresentationToConfigOptions(
  135. mode: ZCodeSessionMode,
  136. ): ZCodeConfigOption[] {
  137. return [
  138. {
  139. id: MODE_CONFIG_ID,
  140. name: "Mode",
  141. category: "mode",
  142. type: "select",
  143. currentValue: normalizeAvailableZCodeMode(mode),
  144. options: getZCodeAgentModeSelectOptions(),
  145. },
  146. ];
  147. }
  148. function resolveSettingsThoughtLevelCurrentValue(
  149. thoughtLevel: ZCodeSessionSettingsState["thoughtLevel"],
  150. ): string | undefined {
  151. const thoughtLevelValues = new Set(thoughtLevel.available.map((level) => level.value));
  152. const currentThoughtLevel =
  153. thoughtLevel.current && thoughtLevelValues.has(thoughtLevel.current)
  154. ? thoughtLevel.current
  155. : undefined;
  156. const defaultThoughtLevel =
  157. thoughtLevel.defaultLevel && thoughtLevelValues.has(thoughtLevel.defaultLevel)
  158. ? thoughtLevel.defaultLevel
  159. : undefined;
  160. // ZCode Protocol 的 defaultLevel 是模型事实,current 为空时表示用户尚未显式修改。
  161. // 实时模型状态事件也要投影默认值,否则工具栏会拿到空 currentValue,出现没有档位被选中的 UI。
  162. return currentThoughtLevel ?? defaultThoughtLevel ?? thoughtLevel.available[0]?.value;
  163. }
  164. export function zcodeSessionSnapshotToTaskMeta(snapshot: ZCodeSessionStateSnapshot): ZCodeTaskMeta {
  165. return {
  166. taskId: snapshot.session.sessionId,
  167. traceId: generateTraceId(snapshot.session.sessionId),
  168. title: deriveTitleFromSnapshot(snapshot),
  169. workspacePath: snapshot.session.workspace.workspacePath,
  170. workspaceIdentity: snapshot.session.workspace.workspaceIdentity,
  171. createdAt: snapshot.session.createdAt,
  172. updatedAt: snapshot.session.updatedAt,
  173. mode: fromZCodeMode(snapshot.session.mode),
  174. model: formatModelPickerValue(resolveTaskMetaModelSelectionFromSnapshot(snapshot)),
  175. thoughtLevel: snapshot.settings.thoughtLevel.current,
  176. provider: ZCODE_AGENT_PROVIDER,
  177. status: deriveZCodeTaskStatusFromSessionSnapshot(snapshot),
  178. lastError: snapshot.projection.lastError
  179. ? {
  180. code: snapshot.projection.lastError.code ?? snapshot.projection.lastError.type,
  181. ...(snapshot.projection.lastError.detail
  182. ? { detail: snapshot.projection.lastError.detail }
  183. : {}),
  184. ...(snapshot.projection.lastError.attribution
  185. ? { attribution: snapshot.projection.lastError.attribution }
  186. : {}),
  187. message: snapshot.projection.lastError.message,
  188. }
  189. : undefined,
  190. target: snapshot.projection.target
  191. ? fromZCodeGoal(snapshot.projection.target)
  192. : snapshot.projection.target,
  193. };
  194. }
  195. function deriveTitleFromSnapshot(snapshot: ZCodeSessionStateSnapshot): string {
  196. return resolveZCodeVisibleSessionTitle({
  197. title: snapshot.session.title,
  198. messages: snapshot.messages,
  199. target: snapshot.projection.target,
  200. });
  201. }
  202. function fromZCodeMode(mode: ZCodeSessionMode): ZCodeTaskMode {
  203. return mode === "build" ? "build" : mode;
  204. }
  205. function normalizeAvailableZCodeMode(mode: ZCodeSessionMode): string {
  206. return ZCODE_AGENT_MODE_ID_SET.has(mode) ? mode : "build";
  207. }
  208. function getZCodeAgentModeSelectOptions(): NonNullable<ZCodeConfigOption["options"]> {
  209. return ZCODE_AGENT_MODE_OPTIONS.map((mode) => ({
  210. value: mode.id,
  211. name: mode.name,
  212. description: mode.description,
  213. }));
  214. }
  215. function fromZCodeGoal(goal: unknown): ZCodeTaskGoal {
  216. const record = asRecord(goal);
  217. const time = asRecord(record.time);
  218. const status = stringValue(record.status);
  219. return {
  220. sessionID: stringValue(record.sessionID) ?? stringValue(record.sessionId) ?? "",
  221. targetID: stringValue(record.targetID) ?? stringValue(record.targetId) ?? "",
  222. objective: stringValue(record.objective) ?? "",
  223. summaryTitle: stringValue(record.summaryTitle) ?? null,
  224. status: isZCodeTaskGoalStatus(status) ? status : "active",
  225. tokenBudget: typeof record.tokenBudget === "number" ? record.tokenBudget : null,
  226. tokensUsed: numberValue(record.tokensUsed) ?? 0,
  227. timeUsedSeconds: numberValue(record.timeUsedSeconds) ?? 0,
  228. activeInputId: stringValue(record.activeInputId) ?? null,
  229. activeRunStartedAtMs: numberValue(record.activeRunStartedAtMs) ?? null,
  230. activeRunLastSeenAtMs: numberValue(record.activeRunLastSeenAtMs) ?? null,
  231. time: {
  232. created: numberValue(time.created) ?? numberValue(record.createdAt) ?? 0,
  233. updated: numberValue(time.updated) ?? numberValue(record.updatedAt) ?? 0,
  234. },
  235. };
  236. }
  237. function isZCodeTaskGoalStatus(status: string | undefined): status is ZCodeTaskGoal["status"] {
  238. return (
  239. status === "active" ||
  240. status === "paused" ||
  241. status === "budget_limited" ||
  242. status === "complete"
  243. );
  244. }
  245. function asRecord(value: unknown): Record<string, unknown> {
  246. return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {};
  247. }
  248. function stringValue(value: unknown): string | undefined {
  249. return typeof value === "string" && value.length > 0 ? value : undefined;
  250. }
  251. function numberValue(value: unknown): number | undefined {
  252. return typeof value === "number" && Number.isFinite(value) ? value : undefined;
  253. }