@tea-agent/loop-agent 0.53.0 → 0.54.0-next.2

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 (88) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/executors/pi-sdk-executor.js +3 -3
  4. package/dist/infrastructure/console/app-data.js +17 -0
  5. package/dist/shared/package-metadata.js +33 -2
  6. package/dist/shared/pi-model-services.js +93 -0
  7. package/dist/worker/console/chat/pi-runtime.js +63 -15
  8. package/dist/worker/console/chat/routes.js +9 -0
  9. package/dist/worker/console/chat/session-catalog.js +2 -1
  10. package/dist/worker/console/chat/session-store.js +72 -6
  11. package/dist/worker/console/pi-credentials.js +3 -1
  12. package/dist/worker/console/pi-readiness.js +0 -1
  13. package/dist/worker/console/routes.js +32 -19
  14. package/dist/worker/console/server.js +18 -8
  15. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BQGQzeB4.js → abnfDiagram-N423BO3Z-C29lbS0T.js} +1 -1
  16. package/dist/worker/console/static/assets/{arc-VohM6k-u.js → arc--Vi-BzUR.js} +1 -1
  17. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-B4aiPVwO.js → architectureDiagram-T3A2C74G-DwdFPJd-.js} +1 -1
  18. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BiOHLIjV.js → blockDiagram-VBNYF7ZC-BFuPq4yu.js} +1 -1
  19. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BeyEgSte.js → c4Diagram-5PPSVZJV-oKn9EfQa.js} +1 -1
  20. package/dist/worker/console/static/assets/channel-o_uspxIc.js +1 -0
  21. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-BlHEbEDm.js → chunk-2GRJ4B5K-TwXtrEhU.js} +1 -1
  22. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-ABS6wshI.js → chunk-2Q5K7J3B-Cc3zFHjT.js} +1 -1
  23. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-CfxvbyTL.js → chunk-5RXB4S5H-xJfu4YKo.js} +1 -1
  24. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-C5Le1PPI.js → chunk-5VM5RSS4-VBNdtRqb.js} +1 -1
  25. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DniQmSFb.js → chunk-6Q2QTUOP-DxhJidW7.js} +1 -1
  26. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-BBXIq87q.js → chunk-GF5L2VYU-P6N3qPX5.js} +1 -1
  27. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-CuZFyj4e.js → chunk-JWPE2WC7-LE21hHhq.js} +1 -1
  28. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-BqltI7Xa.js → chunk-KBJHAD2P-CZmtvzKZ.js} +1 -1
  29. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-LYNDI4V3.js → chunk-RYQCIY6F-BQrw57-q.js} +1 -1
  30. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-ehKC3TY6.js → chunk-XXDRQBXY-DSNQHlxO.js} +1 -1
  31. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BAMhQfS-.js +1 -0
  32. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BAMhQfS-.js +1 -0
  33. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BgLB7_Gs.js → cose-bilkent-JH36ORCC-Ckm2oC4s.js} +1 -1
  34. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-9_ELNaGh.js → cynefinDiagram-MW4NZA55-B7ecDXon.js} +1 -1
  35. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-BQ2TK9_p.js → dagre-VZM6K2ZE-Cx_kCtwr.js} +1 -1
  36. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-BkM26qk5.js → diagram-7IWD3JNH-DTqfz-9k.js} +1 -1
  37. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CrAzvppm.js → diagram-B4RE2ZJO-BH8nNNYl.js} +1 -1
  38. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-DpGT-pk8.js → diagram-LBJQPF4R-mwUmtiIR.js} +1 -1
  39. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-Diukaccq.js → diagram-Q27KOJAE-B6_cW-cc.js} +1 -1
  40. package/dist/worker/console/static/assets/{diagram-UB23O5K3-C2B4xR64.js → diagram-UB23O5K3-D1sGiHf5.js} +1 -1
  41. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-ClHD75wJ.js → ebnfDiagram-BXEA7PRR-C07tYieV.js} +1 -1
  42. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-BjDCis5U.js → erDiagram-JOGREHBK-eHwocxI1.js} +1 -1
  43. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-D8htdME5.js → flowDiagram-UKHOOZJN-B1B-mb0t.js} +1 -1
  44. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-jnfyRfrb.js → ganttDiagram-PKOTCBZU-B2fpno6f.js} +1 -1
  45. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Bjbg88s7.js → gitGraphDiagram-DS77QQ5N-DcM98HR9.js} +1 -1
  46. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DOHcqlQa.js → infoDiagram-6WML65LV-edHmAaaC.js} +1 -1
  47. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BhFciWDX.js → ishikawaDiagram-WSZJBQD7-Df_rsjoZ.js} +1 -1
  48. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-hdKB39Nb.js → journeyDiagram-NVQOT4AX-BqK30536.js} +1 -1
  49. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BdQwpama.js → kanban-definition-27J2QSJJ-DCvcYw-F.js} +1 -1
  50. package/dist/worker/console/static/assets/{linear-Duip0xUK.js → linear-4rMK0UAe.js} +1 -1
  51. package/dist/worker/console/static/assets/main-CBjwyx0a.js +654 -0
  52. package/dist/worker/console/static/assets/main-CGnkpKqw.css +1 -0
  53. package/dist/worker/console/static/assets/{mermaid.core-DRY-520_.js → mermaid.core-CIeuqFlz.js} +4 -4
  54. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CYtRHYwj.js → mindmap-definition-FAOFIHXS-isklXv_u.js} +1 -1
  55. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CK_Sgiks.js → pegDiagram-VL7TDLO6-DufJ3B32.js} +1 -1
  56. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BeOsa7QB.js → pieDiagram-7S7Q4E2Y-e-dscJOX.js} +1 -1
  57. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-D4D9CRa0.js → quadrantDiagram-CIZ2JOQS-BMXdwlfZ.js} +1 -1
  58. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-4GuuCKY5.js → railroadDiagram-AXF67PYL-BkLHnA2m.js} +1 -1
  59. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BkIuekzP.js → requirementDiagram-LRYGKXZP-BzXmvm6l.js} +1 -1
  60. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-uX7nPf0J.js → sankeyDiagram-W5VNT64P-BZuur-BM.js} +1 -1
  61. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-CnP16DIz.js → sequenceDiagram-SI44F4Z6-DbZxmtRn.js} +1 -1
  62. package/dist/worker/console/static/assets/{sheet-workbook-BpM2xbR-.js → sheet-workbook-D_6Enbgn.js} +1 -1
  63. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-Bjm5OhZY.js → sizeCapture-X5ZJPWSS-BHbP5ADt.js} +1 -1
  64. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-DXZ2RYku.js → stateDiagram-OKZ733FA-CGNrvQQV.js} +1 -1
  65. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Oa0mw2RA.js +1 -0
  66. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-B2mW_ryg.js → swimlanes-SLNWSIFB-BWNaMfHj.js} +2 -2
  67. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CylkK52a.js +8 -0
  68. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-eLhaZ_6G.js → timeline-definition-Z64GVDOM-BhI167N4.js} +1 -1
  69. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-tJh-1pOO.js → vennDiagram-T6HMQDX7-BFHqLPNk.js} +1 -1
  70. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-oQI6fAHm.js → wardleyDiagram-T6FBY63Y-D-ThxcCm.js} +1 -1
  71. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Bpg-EQfm.js → xychartDiagram-ELKLHX3M-CeUzoGed.js} +1 -1
  72. package/dist/worker/console/static/index.html +2 -2
  73. package/dist/worker/console/static-src/operator-chat/custom-background-store.js +374 -0
  74. package/dist/worker/console/static-src/operator-chat/custom-background.js +266 -0
  75. package/dist/worker/console/static-src/operator-chat/session-attention.js +34 -0
  76. package/dist/worker/console/static-src/operator-chat/tasks-model.js +24 -0
  77. package/dist/worker/console/workspace-context.js +19 -2
  78. package/dist/worker/observe/static/console-theme.css +22 -3
  79. package/dist/worker/observe/static/console-theme.js +2 -0
  80. package/package.json +9 -10
  81. package/scripts/patch-pi-sdk-windows-hide.mjs +4 -4
  82. package/dist/worker/console/static/assets/channel-vEMQugvb.js +0 -1
  83. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-Dk4zlu_w.js +0 -1
  84. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-Dk4zlu_w.js +0 -1
  85. package/dist/worker/console/static/assets/main-B3dqMT9t.css +0 -1
  86. package/dist/worker/console/static/assets/main-BxLSZyxc.js +0 -654
  87. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BYPZczKU.js +0 -1
  88. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-_6bzI4ly.js +0 -8
package/CHANGELOG.md CHANGED
@@ -4,6 +4,46 @@
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ### 改进
8
+
9
+ - 模型调用工具时,数字或开关值写成字符串也能通过校验;MCP 工具的单个值会自动包成数组
10
+
11
+ ## [0.54.0-next.2] - 2026-11-08
12
+
13
+ 本预发布快照记录构建时已整理的待发布变化,不表示相对上一构建全部新增。
14
+
15
+ ### 改进
16
+
17
+ - 模型调用工具时,数字或开关值写成字符串也能通过校验;MCP 工具的单个值会自动包成数组
18
+
19
+ ## [0.54.0] - 2026-11-08
20
+
21
+ ### 重点更新
22
+
23
+ - 外观新增「自定义」主题:上传本地图片或粘贴图片链接即可铺满整个应用,并可调节不透明度、可读性遮罩、面板透明度、毛玻璃模糊和壁纸模糊
24
+ - 自定义背景支持自动从壁纸取色或手动选择强调色,侧栏、输入框、消息卡片与右侧栏会一起换色
25
+ - 支持浅色/深色底色,深色下遮罩、玻璃亮度与文字对比度自动适配
26
+
27
+ ### 新增
28
+
29
+ - 设置里的背景预览可按窗口比例显示,拖动滑块即时预览、松手自动保存,刷新后保留图片与设置
30
+ - 背景预览支持拖动取景、方向键微调和双击回中,铺满模式下可调整画面位置
31
+ - 打开多个标签页时,背景设置会在标签页之间同步
32
+
33
+ ### 改进
34
+
35
+ - 右侧栏的会话上下文、仓库目录与打开的文件预览跟随自定义主题,不再出现突兀的白底
36
+ - 侧栏、顶栏与右侧栏之间的分割线在壁纸模式下隐藏,侧栏改用淡玻璃保留层级
37
+ - 任务管理在没有子代理时只显示「暂无子代理」和说明,不再混入本工作区其它会话的任务列表
38
+ - 后台任务抽屉按运行中优先排序,已结束的任务按最新在前
39
+
40
+ ### 修复
41
+
42
+ - 修复图片扩展名与内容不一致时仍会被接受的问题,现在会提示「文件扩展名与图片内容不一致」
43
+ - 修复自定义主题选择深色底色后壁纸不可见的问题
44
+ - 修复深色自定义底色下强调色不生效的问题
45
+ - 修复从部分壁纸自动取色时可能得到异常颜色的问题
46
+
7
47
  ## [0.53.0] - 2026-11-02
8
48
 
9
49
  ### 重点更新
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "version": "0.53.0",
4
- "gitSha": "788f2fc502120eb347a6ef8c10a80d60200b36f8",
5
- "builtAt": "2026-11-02T04:25:51.747Z"
3
+ "version": "0.54.0-next.2",
4
+ "gitSha": "b43e01f3de0db3fceda2060f272645281acadc09",
5
+ "builtAt": "2026-11-08T11:22:56.603Z"
6
6
  }
@@ -136,7 +136,7 @@ export function setPiSdkImportOverrideForTests(fn) {
136
136
  export function setPiSdkModuleOverrideForTests(fn) {
137
137
  sdkModuleOverrideForTests = fn;
138
138
  }
139
- /** Check whether the Pi SDK runtime dependency satisfies the 1.3.0 runtime contract. */
139
+ /** Check whether the Pi SDK runtime dependency satisfies the 1.5.0 runtime contract. */
140
140
  export async function checkPiSdkAvailability(_repoRoot) {
141
141
  if (sdkSessionFactoryOverride) {
142
142
  return { ok: true, detail: "pi SDK session factory override active" };
@@ -154,10 +154,10 @@ export async function checkPiSdkAvailability(_repoRoot) {
154
154
  !hasModelRuntime) {
155
155
  return {
156
156
  ok: false,
157
- detail: "pi SDK incompatible: requires createAgentSession, getAgentDir, and ModelRuntime.create (1.3.0 contract)",
157
+ detail: "pi SDK incompatible: requires createAgentSession, getAgentDir, and ModelRuntime.create (1.5.0 contract)",
158
158
  };
159
159
  }
160
- return { ok: true, detail: "pi SDK 1.3.0 contract available" };
160
+ return { ok: true, detail: "pi SDK 1.5.0 contract available" };
161
161
  }
162
162
  catch (error) {
163
163
  const message = error instanceof Error ? error.message : String(error);
@@ -37,9 +37,25 @@ export function legacyPlatformConsoleAppDataRoot(env = process.env) {
37
37
  const xdg = env.XDG_DATA_HOME || path.join(os.homedir(), ".local", "share");
38
38
  return path.join(xdg, APP_DATA_PRODUCT);
39
39
  }
40
+ /*
41
+ * Memoise the resolved paths and their directory creation.
42
+ *
43
+ * This runs on every workspace operation — listing, creating a session, opening a
44
+ * panel — and each call used to create seventeen directories for the workspace's
45
+ * namespace. Those calls are pure: the same repoRoot and appDataRoot always resolve to
46
+ * the same paths, and the directories are idempotent. Caching them per process turns
47
+ * N × 17 syscalls into 17 for the lifetime of the process.
48
+ *
49
+ * Keyed by resolved root plus fingerprint so two different data roots cannot collide.
50
+ */
51
+ const appDataCache = new Map();
40
52
  export function openConsoleAppData(options) {
41
53
  const fingerprint = repoFingerprintV1(options.repoRoot);
42
54
  const root = path.resolve(options.appDataRoot ?? defaultConsoleAppDataRoot());
55
+ const cacheKey = `${root}\u0000${fingerprint}`;
56
+ const cached = appDataCache.get(cacheKey);
57
+ if (cached !== undefined)
58
+ return cached;
43
59
  const repoNamespace = path.join(root, "repos", fingerprint);
44
60
  assertNotUnderRepoHarness(options.repoRoot, repoNamespace);
45
61
  const paths = {
@@ -87,6 +103,7 @@ export function openConsoleAppData(options) {
87
103
  ]) {
88
104
  ensureSecureDir(dir);
89
105
  }
106
+ appDataCache.set(cacheKey, paths);
90
107
  return paths;
91
108
  }
92
109
  function assertNotUnderRepoHarness(repoRoot, candidate) {
@@ -102,6 +102,38 @@ export function computeBinarySha256(filePath) {
102
102
  return undefined;
103
103
  }
104
104
  }
105
+ /**
106
+ * Content-hash memo for package files.
107
+ *
108
+ * `computePackageFingerprint` hashes every file under bin/, dist/, skills/,
109
+ * docs/templates/ and resources/ — about 1,500 files in this package. The console
110
+ * calls it once per workspace context (identity resolution) and again before
111
+ * every controller spawn (drift check), so reading every byte again costs
112
+ * ~230 ms each time on a local SSD and far more on a network install.
113
+ *
114
+ * The memo is keyed by `(path, mtimeNs, size)`. Nanosecond mtime is used on
115
+ * purpose: a same-size rewrite within the same millisecond must still produce a
116
+ * different identity, otherwise a rapid edit could serve a stale hash. Only the
117
+ * hashing work is skipped; the directory walk still runs, so added or removed
118
+ * files are always seen.
119
+ */
120
+ const packageFileHashCache = new Map();
121
+ const PACKAGE_FILE_HASH_CACHE_LIMIT = 8192;
122
+ function contentHashOf(absolutePath) {
123
+ const stats = statSync(absolutePath, { bigint: true });
124
+ const identity = `${stats.mtimeNs}:${stats.size}`;
125
+ const cached = packageFileHashCache.get(absolutePath);
126
+ if (cached && cached.identity === identity)
127
+ return cached.hash;
128
+ const hash = createHash("sha256").update(readFileSync(absolutePath)).digest("hex");
129
+ if (packageFileHashCache.size >= PACKAGE_FILE_HASH_CACHE_LIMIT) {
130
+ const oldest = packageFileHashCache.keys().next().value;
131
+ if (oldest !== undefined)
132
+ packageFileHashCache.delete(oldest);
133
+ }
134
+ packageFileHashCache.set(absolutePath, { identity, hash });
135
+ return hash;
136
+ }
105
137
  /**
106
138
  * Compute a portable, deterministic content fingerprint for the installed
107
139
  * package rooted at `packageRoot`.
@@ -316,8 +348,7 @@ export function expandPathext(bin, pathext) {
316
348
  // Internal helpers
317
349
  // ---------------------------------------------------------------------------
318
350
  function addRequiredFile(entries, absolutePath, relativeDir) {
319
- const buffer = readFileSync(absolutePath);
320
- const contentHash = createHash("sha256").update(buffer).digest("hex");
351
+ const contentHash = contentHashOf(absolutePath);
321
352
  const relativePath = relativeDir
322
353
  ? path.posix.join(relativeDir, path.basename(absolutePath))
323
354
  : path.basename(absolutePath);
@@ -1,3 +1,5 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
1
3
  import path from "node:path";
2
4
  export class PiModelServicesError extends Error {
3
5
  code;
@@ -43,8 +45,99 @@ async function defaultLoadSdk() {
43
45
  /**
44
46
  * Create the same cwd-bound model surface used by real Pi sessions. Extensions
45
47
  * stay enabled so their pending provider registrations reach ModelRuntime.
48
+ *
49
+ * Process-wide memo for the result:
50
+ *
51
+ * Building it costs ~250 ms warm and >2 s on the first call (SDK import plus
52
+ * extension resolution), and the console builds one for every workspace whose
53
+ * readiness it probes. Everything it reads — auth.json, models.json, the
54
+ * extension packages that register providers — belongs to the user's agentDir,
55
+ * not to a repository. Repositories without project-level Pi configuration
56
+ * therefore share one entry; a repository that adds `.pi/settings.json` or
57
+ * `.pi/extensions` gets its own entry keyed by its root, because those can add
58
+ * packages or providers relative to that root.
59
+ *
60
+ * Global settings and credential writes call
61
+ * `invalidatePiModelServicesInspection()`; the TTL is a backstop.
46
62
  */
63
+ const inspectionCache = new Map();
64
+ const INSPECTION_TTL_MS = 60_000;
65
+ const INSPECTION_CACHE_LIMIT = 64;
66
+ export function invalidatePiModelServicesInspection() {
67
+ inspectionCache.clear();
68
+ }
69
+ /**
70
+ * Distinct loaders must never share a cached inspection: tests inject SDK
71
+ * doubles, and a later production call in the same process must not receive a
72
+ * fixture. Identity mapping keeps each loader's entries separate while still
73
+ * letting one loader benefit from the cache.
74
+ */
75
+ const loaderCacheKeys = new WeakMap();
76
+ let nextLoaderCacheKey = 0;
77
+ function loaderCacheKey(loadSdk) {
78
+ if (!loadSdk)
79
+ return "default";
80
+ let key = loaderCacheKeys.get(loadSdk);
81
+ if (key === undefined) {
82
+ key = ++nextLoaderCacheKey;
83
+ loaderCacheKeys.set(loadSdk, key);
84
+ }
85
+ return `loader:${key}`;
86
+ }
87
+ /**
88
+ * Empty when the repository contributes nothing to the model plane — the case
89
+ * where one shared model plane is provably equivalent. Only `packages` (npm
90
+ * extension packages that can register providers) and `extensions` (autoload
91
+ * paths) in project settings can change provider registration; retry/compaction
92
+ * settings do not. A project `.pi/extensions` directory also forces a separate
93
+ * entry. Re-used roots keep the resolved path so relative sources never cross
94
+ * repositories.
95
+ */
96
+ function projectPiSignature(repoRoot) {
97
+ const root = path.resolve(repoRoot);
98
+ const extensionsDir = path.join(root, ".pi", "extensions");
99
+ const hasExtensionsDir = existsSync(extensionsDir);
100
+ let packages = [];
101
+ let extensions = [];
102
+ try {
103
+ const parsed = JSON.parse(readFileSync(path.join(root, ".pi", "settings.json"), "utf8"));
104
+ packages = Array.isArray(parsed.packages)
105
+ ? parsed.packages.filter((value) => typeof value === "string")
106
+ : [];
107
+ extensions = Array.isArray(parsed.extensions)
108
+ ? parsed.extensions.filter((value) => typeof value === "string")
109
+ : [];
110
+ }
111
+ catch (error) {
112
+ if (error?.code !== "ENOENT") {
113
+ return `unreadable|extdir=${hasExtensionsDir ? "1" : "0"}|root=${root}`;
114
+ }
115
+ }
116
+ if (packages.length === 0 && extensions.length === 0 && !hasExtensionsDir)
117
+ return "";
118
+ const digest = createHash("sha256")
119
+ .update(JSON.stringify({ packages, extensions }))
120
+ .digest("hex");
121
+ return `cfg:${digest}|extdir=${hasExtensionsDir ? "1" : "0"}|root=${root}`;
122
+ }
47
123
  export async function createPiModelServicesInspection(options) {
124
+ const key = `${loaderCacheKey(options.loadSdk)}\u0000${options.agentDir ? path.resolve(options.agentDir) : "<default>"}\u0000${projectPiSignature(options.cwd)}`;
125
+ const now = Date.now();
126
+ const cached = inspectionCache.get(key);
127
+ if (cached && now - cached.computedAt < INSPECTION_TTL_MS) {
128
+ return cached.inspection;
129
+ }
130
+ const inspection = await createPiModelServicesInspectionUncached(options);
131
+ if (inspectionCache.size >= INSPECTION_CACHE_LIMIT) {
132
+ for (const [entryKey, entry] of inspectionCache) {
133
+ if (now - entry.computedAt >= INSPECTION_TTL_MS)
134
+ inspectionCache.delete(entryKey);
135
+ }
136
+ }
137
+ inspectionCache.set(key, { inspection, computedAt: now });
138
+ return inspection;
139
+ }
140
+ async function createPiModelServicesInspectionUncached(options) {
48
141
  const sdk = await (options.loadSdk ?? defaultLoadSdk)();
49
142
  const agentDir = options.agentDir ??
50
143
  (() => {
@@ -833,9 +833,24 @@ export class ConsolePiRuntime {
833
833
  async refreshSkillPrefsCache() {
834
834
  const prefs = await this.loadSkillAutoInvocationPreferences();
835
835
  this.cachedSkillPrefs = prefs;
836
- this.invalidateWorkspaceInspection();
836
+ // Skill preferences only change the projected skill inventory. Clearing
837
+ // the model runtime and inspection services here made every new session
838
+ // rebuild them, so the composer's model list had to wait behind a full
839
+ // ResourceLoader build — and that build shares the same synchronous
840
+ // stretch as the extension handshake.
841
+ this.invalidateWorkspaceSnapshotTemplates();
837
842
  return prefs;
838
843
  }
844
+ /**
845
+ * Drop only the derived snapshot templates (skills/extensions view). Model
846
+ * services and the model runtime stay warm; `getWorkspaceInspectionServices`
847
+ * already revalidates its own prefs mtime before reuse.
848
+ */
849
+ invalidateWorkspaceSnapshotTemplates() {
850
+ this.workspaceInspectionGeneration += 1;
851
+ this.workspaceSnapshotTemplates.clear();
852
+ this.workspaceSnapshotInFlight.clear();
853
+ }
839
854
  getCompactionController(sessionId) {
840
855
  let controller = this.compactionControllers.get(sessionId);
841
856
  if (!controller) {
@@ -1926,6 +1941,10 @@ export class ConsolePiRuntime {
1926
1941
  * conversation JSONL so the picker is not blocked on cold reopen.
1927
1942
  */
1928
1943
  workspaceModelRuntime;
1944
+ /** models.json identity that produced `workspaceModelRuntime`. */
1945
+ workspaceModelRuntimeVersion;
1946
+ workspaceModelRuntimeCachedAt = 0;
1947
+ static WORKSPACE_MODEL_RUNTIME_TTL_MS = 60_000;
1929
1948
  static WORKSPACE_INSPECTION_TTL_MS = 45_000;
1930
1949
  workspaceInspectionServices;
1931
1950
  workspaceInspectionCachedAt = 0;
@@ -1949,21 +1968,33 @@ export class ConsolePiRuntime {
1949
1968
  this.workspaceModelRuntime = undefined;
1950
1969
  }
1951
1970
  async getWorkspaceModelRuntime() {
1952
- if (!this.workspaceModelRuntime) {
1953
- this.workspaceModelRuntime = (async () => {
1954
- const agentDir = await safeGetAgentDir(this.bindings);
1955
- const { services } = await this.bindings.createServices({
1956
- cwd: this.options.cwd,
1957
- agentDir,
1958
- resourceLoaderOptions: { ...CATALOG_RESOURCE_LOADER_OPTIONS },
1959
- });
1960
- return services.modelRuntime;
1961
- })().catch((error) => {
1962
- this.workspaceModelRuntime = undefined;
1963
- throw error;
1964
- });
1971
+ const agentDir = await safeGetAgentDir(this.bindings);
1972
+ const modelsPath = path.join(agentDir, "models.json");
1973
+ const currentVersion = await readModelConfigFileVersion(modelsPath);
1974
+ if (this.workspaceModelRuntime &&
1975
+ this.workspaceModelRuntimeVersion &&
1976
+ sameModelConfigFileVersion(this.workspaceModelRuntimeVersion, currentVersion) &&
1977
+ Date.now() - this.workspaceModelRuntimeCachedAt <
1978
+ ConsolePiRuntime.WORKSPACE_MODEL_RUNTIME_TTL_MS) {
1979
+ return this.workspaceModelRuntime;
1965
1980
  }
1966
- return this.workspaceModelRuntime;
1981
+ this.workspaceModelRuntime = undefined;
1982
+ this.workspaceModelRuntimeVersion = undefined;
1983
+ const created = (async () => {
1984
+ const { services } = await this.bindings.createServices({
1985
+ cwd: this.options.cwd,
1986
+ agentDir,
1987
+ resourceLoaderOptions: { ...CATALOG_RESOURCE_LOADER_OPTIONS },
1988
+ });
1989
+ return services.modelRuntime;
1990
+ })().catch((error) => {
1991
+ this.workspaceModelRuntime = undefined;
1992
+ throw error;
1993
+ });
1994
+ this.workspaceModelRuntime = created;
1995
+ this.workspaceModelRuntimeVersion = currentVersion;
1996
+ this.workspaceModelRuntimeCachedAt = Date.now();
1997
+ return created;
1967
1998
  }
1968
1999
  /**
1969
2000
  * Full OPEN-surface services for inspect UIs. No SessionManager / JSONL.
@@ -2055,6 +2086,23 @@ export class ConsolePiRuntime {
2055
2086
  const modelRuntime = await this.getWorkspaceModelRuntime();
2056
2087
  return this.bindings.listAvailableModels({ modelRuntime });
2057
2088
  }
2089
+ /**
2090
+ * Warm the workspace model catalog before the composer asks for it.
2091
+ *
2092
+ * Opening a workspace already pays for the runtime context; running the
2093
+ * catalog build in that window means the first new conversation's model
2094
+ * selector paints from cache instead of waiting for a `createServices`
2095
+ * stretch that would otherwise share the event loop with the session's
2096
+ * extension handshake. Failures stay silent: readiness routes report them.
2097
+ */
2098
+ async prewarmModelCatalog() {
2099
+ try {
2100
+ await this.getWorkspaceModelRuntime();
2101
+ }
2102
+ catch {
2103
+ // Keep the lazy path authoritative; a failed warm-up is retried on use.
2104
+ }
2105
+ }
2058
2106
  async applyModel(sessionId, model) {
2059
2107
  await this.ensureSessionReady(sessionId);
2060
2108
  const session = this.sessions.get(sessionId);
@@ -2388,6 +2388,14 @@ export async function listChatSessionSummaries(deps, ownerWorkspaceId) {
2388
2388
  return Promise.all(sessions.map(async (session) => {
2389
2389
  const active = deps.events?.getActiveTurn(session.sessionId);
2390
2390
  const workspaceId = ownerWorkspaceId ?? session.workspaceId;
2391
+ /*
2392
+ * A pending question is a live, blocked Turn: only a Turn the event ring
2393
+ * still accounts for can be waiting on an answer. Gating on `active`
2394
+ * keeps the list from reading every session's question file.
2395
+ */
2396
+ const pendingQuestion = active && deps.questionRegistry
2397
+ ? await deps.questionRegistry.get(session.sessionId).catch(() => undefined)
2398
+ : undefined;
2391
2399
  let subagentSummary;
2392
2400
  if (deps.events || deps.runtime || deps.subagents) {
2393
2401
  const catalog = await subagentCatalogFor(deps, session.sessionId, session.messages, groupedChildren,
@@ -2424,6 +2432,7 @@ export async function listChatSessionSummaries(deps, ownerWorkspaceId) {
2424
2432
  deferredTurn: projectDeferredTurnSummary(session.deferredTurns?.[0]),
2425
2433
  deferredTurns: projectDeferredTurnSummaries(session.deferredTurns ?? []),
2426
2434
  isBlank: isBlankChatSession(session) && !active,
2435
+ ...(pendingQuestion ? { pendingInteraction: "question" } : {}),
2427
2436
  ...(subagentSummary ? { subagentSummary } : {}),
2428
2437
  };
2429
2438
  }));
@@ -1,7 +1,7 @@
1
1
  import { isBlankChatSession } from "./session-store.js";
2
2
  import { projectDeferredTurnSummaries, projectDeferredTurnSummary, } from "./deferred-turn.js";
3
3
  /** Sidebar / global GET /chat/sessions projection. Must include sessionMode. */
4
- export function projectChatSessionCatalogListItem(entry, active) {
4
+ export function projectChatSessionCatalogListItem(entry, active, pendingInteraction) {
5
5
  return {
6
6
  sessionId: entry.sessionId,
7
7
  ...(entry.workspaceId ? { workspaceId: entry.workspaceId } : {}),
@@ -29,6 +29,7 @@ export function projectChatSessionCatalogListItem(entry, active) {
29
29
  deferredTurn: entry.deferredTurn,
30
30
  deferredTurns: entry.deferredTurns,
31
31
  isBlank: entry.isBlank && !active,
32
+ ...(pendingInteraction ? { pendingInteraction } : {}),
32
33
  };
33
34
  }
34
35
  /**
@@ -18,7 +18,7 @@ import { captureCommandOutput, readCommandOutput, removeCommandOutputs } from ".
18
18
  import { isSdkCancelledResult } from "./tool-presentation-projection.js";
19
19
  import { isShellTool } from "./tool-preview.js";
20
20
  import { randomUUID } from "node:crypto";
21
- import { copyFile, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
21
+ import { copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
22
22
  import { readJsonIfExists, writeSecureJson, } from "../../../infrastructure/console/app-data.js";
23
23
  import { dispatchOperatorAction } from "../operator-actions.js";
24
24
  import { authorizeOperatorChatTool } from "./tools.js";
@@ -83,6 +83,31 @@ export function isConsoleOwnedSessionFile(appData, sessionFile) {
83
83
  const relative = path.relative(root, target);
84
84
  return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
85
85
  }
86
+ /**
87
+ * How many session files are read at once during a listing.
88
+ *
89
+ * A workspace can hold hundreds of sessions, and each read parses a few hundred
90
+ * kilobytes. Unbounded `Promise.all` issues them all at once, which is slower than a
91
+ * bounded queue once the files are on a network share — the case this console runs in
92
+ * on an intranet — and can exhaust file handles. Eight keeps a local SSD saturated while
93
+ * staying polite to a share.
94
+ */
95
+ const LIST_READ_CONCURRENCY = 8;
96
+ /** Run `task` over `items` with at most `limit` in flight, preserving order. */
97
+ async function mapWithConcurrency(items, limit, task) {
98
+ const results = new Array(items.length);
99
+ let next = 0;
100
+ const workers = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
101
+ for (;;) {
102
+ const index = next++;
103
+ if (index >= items.length)
104
+ return;
105
+ results[index] = await task(items[index]);
106
+ }
107
+ });
108
+ await Promise.all(workers);
109
+ return results;
110
+ }
86
111
  export class ChatSessionStore {
87
112
  appData;
88
113
  options;
@@ -92,6 +117,20 @@ export class ChatSessionStore {
92
117
  * via last-write-wins on the same JSON record.
93
118
  */
94
119
  writeChains = new Map();
120
+ /*
121
+ * Parsed-record cache keyed by the file identity that produced it.
122
+ *
123
+ * `list()` reads every session's full JSON to build rows, and the row projection needs
124
+ * `messages` (the subagent summary is derived from the Agent tool results they carry),
125
+ * so a header-only read is not available without changing what the list can say.
126
+ * What is available is not re-parsing a file that has not changed: `stat` is two
127
+ * orders of magnitude cheaper than reading and parsing a few hundred kilobytes, and a
128
+ * workspace is re-listed every time its panel opens.
129
+ *
130
+ * Identity is `mtimeMs + size`, which changes on every write; a stale entry is
131
+ * therefore impossible to serve. Entries are dropped on persist/remove below.
132
+ */
133
+ recordCache = new Map();
95
134
  constructor(appData, options = {}) {
96
135
  this.appData = appData;
97
136
  this.options = options;
@@ -101,8 +140,35 @@ export class ChatSessionStore {
101
140
  // Ordinary chats keep their existing IO cost until their first inbox delivery.
102
141
  const durable = record.messages.some(message => message.id.startsWith("automation-") || message.id.startsWith("scheduled-goal-"));
103
142
  await writeSecureJson(recordPath(this.appData, record.sessionId), record, { durable });
143
+ // Drop the listing cache explicitly rather than trusting timestamp granularity.
144
+ this.recordCache.delete(record.sessionId);
104
145
  this.options.onRecordChange?.(record.sessionId, record);
105
146
  }
147
+ /**
148
+ * Read one record for a listing row, reusing the parse when the file is unchanged.
149
+ *
150
+ * The identity check is `mtimeMs + size`: every write moves the mtime, so a cache hit
151
+ * cannot serve a stale record. A miss falls through to the ordinary read, which also
152
+ * performs the legacy migration — so a hit and a miss return the same shape.
153
+ */
154
+ async readForList(sessionId) {
155
+ let identity;
156
+ try {
157
+ const info = await stat(recordPath(this.appData, sessionId));
158
+ identity = { mtimeMs: info.mtimeMs, size: info.size };
159
+ }
160
+ catch {
161
+ return undefined;
162
+ }
163
+ const cached = this.recordCache.get(sessionId);
164
+ if (cached && cached.mtimeMs === identity.mtimeMs && cached.size === identity.size) {
165
+ return cached.record;
166
+ }
167
+ const record = await this.get(sessionId);
168
+ if (record !== undefined)
169
+ this.recordCache.set(sessionId, { ...identity, record });
170
+ return record;
171
+ }
106
172
  /** Read + migrate legacy V1 records into the V2 in-memory shape. */
107
173
  async get(sessionId) {
108
174
  const raw = await readJsonIfExists(recordPath(this.appData, sessionId));
@@ -172,11 +238,10 @@ export class ChatSessionStore {
172
238
  catch {
173
239
  return [];
174
240
  }
175
- const records = await Promise.all(names
176
- .filter((name) => name.endsWith(".json"))
177
- .map(async (name) => {
241
+ const files = names.filter((name) => name.endsWith(".json"));
242
+ const records = await mapWithConcurrency(files, LIST_READ_CONCURRENCY, async (name) => {
178
243
  try {
179
- return await this.get(name.slice(0, -".json".length));
244
+ return await this.readForList(name.slice(0, -".json".length));
180
245
  }
181
246
  catch (error) {
182
247
  // Skip corrupt records (e.g. unknown sessionMode) but stay
@@ -184,7 +249,7 @@ export class ChatSessionStore {
184
249
  process.stderr.write(`[console] chat session record skipped in list: ${name.slice(0, -".json".length)}: ${error instanceof Error ? error.message : String(error)}\n`);
185
250
  return undefined;
186
251
  }
187
- }));
252
+ });
188
253
  return records
189
254
  .filter((record) => Boolean(record) && (options?.includeArchived || record.state === "active"))
190
255
  .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
@@ -404,6 +469,7 @@ export class ChatSessionStore {
404
469
  }
405
470
  async removeSessionArtifacts(sessionId, sessionFile) {
406
471
  await rm(recordPath(this.appData, sessionId), { force: true });
472
+ this.recordCache.delete(sessionId);
407
473
  await this.removeAttachmentFiles(sessionId).catch(() => undefined);
408
474
  await removeCommandOutputs(this.appData.chats, sessionId).catch(() => undefined);
409
475
  this.options.onRecordChange?.(sessionId, undefined);
@@ -21,7 +21,7 @@ import { open as openFile, readFile, rm, stat, unlink } from "node:fs/promises";
21
21
  import os from "node:os";
22
22
  import path from "node:path";
23
23
  import { writeSecureJson } from "../../infrastructure/console/app-data.js";
24
- import { createPiModelServicesInspection, providerHasUsableAuth, } from "../../shared/pi-model-services.js";
24
+ import { createPiModelServicesInspection, invalidatePiModelServicesInspection, providerHasUsableAuth, } from "../../shared/pi-model-services.js";
25
25
  /** provider 名允许的字符集(与 route 校验共用语义)。 */
26
26
  const PROVIDER_PATTERN = /^[A-Za-z0-9._-]+$/;
27
27
  /** 输入非法(provider 名 / apiKey 形状)——路由映射为 400 INVALID_INPUT。 */
@@ -520,6 +520,7 @@ export async function writePiProviderConfig(input, deps) {
520
520
  },
521
521
  });
522
522
  });
523
+ invalidatePiModelServicesInspection();
523
524
  if (input.apiKey !== undefined) {
524
525
  await writePiCredential({ provider: input.provider, apiKey: input.apiKey }, deps);
525
526
  }
@@ -546,5 +547,6 @@ export async function writePiCredential(input, deps) {
546
547
  };
547
548
  await writeSecureJson(authPath, next);
548
549
  });
550
+ invalidatePiModelServicesInspection();
549
551
  return { provider: input.provider };
550
552
  }
@@ -129,7 +129,6 @@ export async function discoverPiReadinessProbe(options) {
129
129
  try {
130
130
  inspection = await createPiModelServicesInspection({
131
131
  cwd: repoRoot,
132
- loadSdk: async () => sdk,
133
132
  });
134
133
  }
135
134
  catch (error) {
@@ -1756,27 +1756,40 @@ export async function handleWorkspaceRoutes(req, res, registry, deps, url, pathn
1756
1756
  }
1757
1757
  : undefined,
1758
1758
  });
1759
- void Promise.all(records.map(async (record) => {
1760
- const cached = readinessCache.get(record.repoRoot);
1761
- if (cached && isCacheFresh(cached, Date.now()))
1762
- return;
1763
- let state;
1764
- try {
1765
- const report = await probePiReadiness({
1766
- override: deps.piReadinessProbe,
1767
- repoRoot: record.repoRoot,
1768
- appDataRoot: deps.appDataRoot,
1759
+ /*
1760
+ * One probe at a time, not `Promise.all`.
1761
+ *
1762
+ * `probePiReadiness` builds Pi services, and that construction is
1763
+ * synchronous: a `Promise.all` over N workspaces still executes N sync
1764
+ * stretches back-to-back on the event loop, so the page that just loaded
1765
+ * could not process a click until all of them finished (measured: 1.27 s
1766
+ * of lag for four workspaces). Serializing lets the loop breathe between
1767
+ * workspaces; the process-wide model-plane cache makes repeat probes
1768
+ * single-digit milliseconds, so this is not slower overall.
1769
+ */
1770
+ void (async () => {
1771
+ for (const record of records) {
1772
+ const cached = readinessCache.get(record.repoRoot);
1773
+ if (cached && isCacheFresh(cached, Date.now()))
1774
+ continue;
1775
+ let state;
1776
+ try {
1777
+ const report = await probePiReadiness({
1778
+ override: deps.piReadinessProbe,
1779
+ repoRoot: record.repoRoot,
1780
+ appDataRoot: deps.appDataRoot,
1781
+ });
1782
+ state = report.state;
1783
+ }
1784
+ catch {
1785
+ state = "setup-required";
1786
+ }
1787
+ readinessCache.set(record.repoRoot, {
1788
+ state,
1789
+ probedAt: Date.now(),
1769
1790
  });
1770
- state = report.state;
1771
1791
  }
1772
- catch {
1773
- state = "setup-required";
1774
- }
1775
- readinessCache.set(record.repoRoot, {
1776
- state,
1777
- probedAt: Date.now(),
1778
- });
1779
- })).catch(() => undefined);
1792
+ })().catch(() => undefined);
1780
1793
  return;
1781
1794
  }
1782
1795
  if (method === "POST" && pathname === "/api/operator/v1/workspaces/pick") {