pi-web-ui 0.114.1 → 0.114.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 (130) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +187 -187
  3. package/README.zh-CN.md +227 -227
  4. package/README.zh-TW.md +227 -227
  5. package/bin/device-hub-cli.mjs +577 -577
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -9
  8. package/bin/pi-web-ui.mjs +4081 -4081
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service.js +88 -15
  12. package/dist/server/attachments.js +6 -6
  13. package/dist/server/canvas/canvas-orchestrator.js +3 -3
  14. package/dist/server/communicate-tool.js +37 -11
  15. package/dist/server/compaction-instructions.js +8 -8
  16. package/dist/server/context-usage.js +105 -0
  17. package/dist/server/device-center/desktop-page.js +228 -228
  18. package/dist/server/device-center/hub-page.js +64 -64
  19. package/dist/server/device-center/native-desktop/macos.js +190 -190
  20. package/dist/server/device-center/native-desktop/windows.js +116 -116
  21. package/dist/server/dsh/runtime/cordis.yml +1 -1
  22. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  23. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  24. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  25. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  26. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  27. package/dist/server/durable/durable-event-projector.js +19 -3
  28. package/dist/server/durable/durable-models.js +134 -65
  29. package/dist/server/eval-tool.js +135 -135
  30. package/dist/server/model-resolver.js +4 -1
  31. package/dist/server/patch-bash-process.js +89 -89
  32. package/dist/server/patch-tool.js +9 -9
  33. package/dist/server/patch-turn-end-boundary.js +3 -3
  34. package/dist/server/persona-chain.js +8 -8
  35. package/dist/server/protocol-version.js +1 -1
  36. package/dist/server/remote-ssh-service.js +39 -39
  37. package/dist/server/schedule-agent-tool.js +11 -6
  38. package/dist/server/scheduler-tasks.js +84 -2
  39. package/dist/server/scm-commitmsg.js +10 -10
  40. package/dist/server/setup-page.js +620 -620
  41. package/dist/server/universal/universal-session.js +19 -18
  42. package/dist/server/vision-bridge.js +18 -18
  43. package/docs/device-center.md +148 -148
  44. package/docs/device-desktop.md +48 -48
  45. package/docs/dsh-engine.md +493 -493
  46. package/extensions/webui.ts +335 -335
  47. package/package.json +1 -1
  48. package/plugin-sdk/README.md +174 -174
  49. package/plugin-sdk/client-utils.mjs +279 -279
  50. package/plugin-sdk/import-check.mjs +210 -210
  51. package/plugin-sdk/index.d.ts +698 -698
  52. package/plugin-sdk/index.mjs +696 -696
  53. package/plugin-sdk/package.json +13 -13
  54. package/plugin-sdk/ssh-host-trust.mjs +225 -225
  55. package/themes/aetheris.css +501 -501
  56. package/themes/ayu-light.css +116 -116
  57. package/themes/bases/flow-base.css +1357 -1357
  58. package/themes/bases/obsidian-base.css +895 -895
  59. package/themes/bases/statusbar-flat-base.css +112 -112
  60. package/themes/bases/zhujian-base.css +688 -688
  61. package/themes/bases/zhupi-base.css +660 -660
  62. package/themes/catppuccin-latte.css +119 -119
  63. package/themes/catppuccin.css +116 -116
  64. package/themes/claude-code-dark.css +147 -147
  65. package/themes/codex.css +114 -114
  66. package/themes/cyberpunk.css +50 -50
  67. package/themes/dark-teal.css +264 -264
  68. package/themes/dazzle.css +38 -38
  69. package/themes/everforest-light.css +115 -115
  70. package/themes/flow-light.css +164 -164
  71. package/themes/flow.css +161 -161
  72. package/themes/geist.css +114 -114
  73. package/themes/gruvbox-light.css +115 -115
  74. package/themes/kanagawa-lotus.css +115 -115
  75. package/themes/md-preview.css +24 -24
  76. package/themes/mist.css +166 -166
  77. package/themes/nord.css +107 -107
  78. package/themes/one-dark.css +106 -106
  79. package/themes/paper.css +174 -174
  80. package/themes/rose-pine-dawn.css +114 -114
  81. package/themes/sakura.css +166 -166
  82. package/themes/solarized-light.css +114 -114
  83. package/themes/tokyo-night.css +115 -115
  84. package/themes/translucent.css +85 -85
  85. package/themes/transparent.css +116 -116
  86. package/themes/vs-code-dark.css +147 -147
  87. package/themes/wallpaper-flow.css +382 -382
  88. package/themes/wallpaper-obsidian.css +74 -74
  89. package/themes/white.css +164 -164
  90. package/themes/zhujian-dark.css +115 -115
  91. package/themes/zhujian.css +114 -114
  92. package/themes/zhupi-dark.css +115 -115
  93. package/themes/zhupi.css +114 -114
  94. package/web/dist/.build-assets.json +1 -1
  95. package/web/dist/assets/{BgTasksModal-BcXJ20RO.js → BgTasksModal-BvnUHjFe.js} +1 -1
  96. package/web/dist/assets/{BgTasksModal-DjQmiKnE.js → BgTasksModal-DSC8ncW3.js} +1 -1
  97. package/web/dist/assets/{CanvasStudio-PI9pid0Y.js → CanvasStudio-BSg9ghPV.js} +2 -2
  98. package/web/dist/assets/{CanvasStudio-nf5-HxLM.js → CanvasStudio-DxW7C3Sz.js} +2 -2
  99. package/web/dist/assets/{DeviceCenter-CYttJw2a.js → DeviceCenter-Bmgr-Bwm.js} +1 -1
  100. package/web/dist/assets/{DeviceCenter-DPe4sz74.js → DeviceCenter-Cl9MBXaH.js} +1 -1
  101. package/web/dist/assets/{DeviceGroups-D2rogxEN.js → DeviceGroups-aeLD2msl.js} +1 -1
  102. package/web/dist/assets/{Dropdown-ZLS04O8p.js → Dropdown-D1Jl35dw.js} +1 -1
  103. package/web/dist/assets/{FilePreview-C9Ut4Lq6.js → FilePreview-6CqoDF_P.js} +1 -1
  104. package/web/dist/assets/{FilePreview-CvK3ZzX5.js → FilePreview-CJa27G_Q.js} +1 -1
  105. package/web/dist/assets/{GlobalSearchModal-C5e-OCw2.js → GlobalSearchModal-CJX35rZL.js} +1 -1
  106. package/web/dist/assets/{GlobalSearchModal-H7pFK2UC.js → GlobalSearchModal-CMW0xz0P.js} +1 -1
  107. package/web/dist/assets/{GroupConversation-C2wNM0dQ.js → GroupConversation-Cq4daBFb.js} +1 -1
  108. package/web/dist/assets/{GroupConversation-ChN3TWQK.js → GroupConversation-DoELa83U.js} +1 -1
  109. package/web/dist/assets/{ModelConfigModal-DDZccDYt.js → ModelConfigModal-Bp7tfKYh.js} +1 -1
  110. package/web/dist/assets/{PiSetupModal-DHbqfx8T.js → PiSetupModal-DD8srwBJ.js} +1 -1
  111. package/web/dist/assets/{ProviderOAuthControls-C-MK36Dk.js → ProviderOAuthControls-C6tfXb88.js} +1 -1
  112. package/web/dist/assets/{SCMPanel-kx-SCL2s.js → SCMPanel-CghgsyBN.js} +1 -1
  113. package/web/dist/assets/{SCMPanel-buTGziDB.js → SCMPanel-D8-8aqwC.js} +1 -1
  114. package/web/dist/assets/{SettingsModal-BsUF8jqr.js → SettingsModal-BbBe2rYo.js} +1 -1
  115. package/web/dist/assets/{SettingsModal-D357Ky7P.js → SettingsModal-qETiVPKj.js} +1 -1
  116. package/web/dist/assets/{TerminalPanel-BBuM_Sez.js → TerminalPanel-Da-Xs4Wk.js} +1 -1
  117. package/web/dist/assets/{TerminalPanel-D6x6xz8Q.js → TerminalPanel-DnS4tFQO.js} +1 -1
  118. package/web/dist/assets/{TuiOverlayModal-CdbGV3Za.js → TuiOverlayModal-CGyGkKYl.js} +1 -1
  119. package/web/dist/assets/{TuiOverlayModal-d6x9u25n.js → TuiOverlayModal-CpBKjG6x.js} +1 -1
  120. package/web/dist/assets/{desktop-YguLbrX1.js → desktop-7EvUHhKQ.js} +1 -1
  121. package/web/dist/assets/{fi-DaSO0Q-m.js → fi-NyN-ZrgD.js} +2 -2
  122. package/web/dist/assets/{index-D6u8xH0o.js → index-DK3F5ZJo.js} +50 -50
  123. package/web/dist/assets/{index-BPvpea8t.js → index-DQMii2he.js} +50 -50
  124. package/web/dist/assets/index-vwBnwzkr.css +1 -0
  125. package/web/dist/assets/{plugin-host-BRBg6zmQ.js → plugin-host-BCnX3P8U.js} +1 -1
  126. package/web/dist/assets/{theme-DDl-Oy1b.js → theme-D2DMH6tH.js} +1 -1
  127. package/web/dist/index.html +35 -35
  128. package/web/dist/sw.js +179 -179
  129. package/web/public/sw.js +179 -179
  130. package/web/dist/assets/index-DDZMv6LO.css +0 -1
@@ -1,100 +1,100 @@
1
- # pi-web-ui behind nginx at a sub-path: http://<host>:83/pi/
2
- # Backend app: http://127.0.0.1:8787 (default PI_WEB_PORT env)
3
- #
4
- # IMPORTANT: pi-web-ui 0.23+ checks the WebSocket Origin against the request
5
- # Host (hostname AND port). Every proxied location MUST forward the original
6
- # Host with $http_host (keeps the port). Using $host (drops the port) or
7
- # leaving Host unset (defaults to 127.0.0.1:8787) makes the upgrade fail with
8
- # 403 — the page loads but chat/terminal keep reconnecting.
9
- #
10
- # Topology (two listeners on one port: frp + LAN coexist):
11
- # frp (public) -> <PUBLIC_IP>:<PUBLIC_PORT> -> 127.0.0.1:83 (PROXY protocol v2)
12
- # LAN users -> http://<LAN_IP>:83/pi/ (plain HTTP listener)
13
- #
14
- # frpc sends PROXY v2 to nginx (transport.proxyProtocolVersion = "v2"):
15
- # * 127.0.0.1:83 proxy_protocol — only the local frp client connects
16
- # here (it speaks PROXY v2; nginx then sees the real visitor IP).
17
- # * <LAN_IP>:83 plain HTTP — LAN browsers, no PROXY header needed.
18
- #
19
- # Simpler alternative (no real client IPs): drop proxy_protocol entirely and
20
- # use a single `listen 83;` — then frpc must NOT set proxyProtocolVersion.
21
- #
22
- # The frontend uses absolute paths (/ws WebSocket, /assets/*, /favicon.svg,
23
- # /api/file…) so those get their own proxied locations next to /pi/.
24
-
25
- # Reuse for Upgrade/Connection headers (WebSocket).
26
- map $http_upgrade $connection_upgrade {
27
- default upgrade;
28
- '' close;
29
- }
30
-
31
- server {
32
- listen 127.0.0.1:83 proxy_protocol;
33
- listen <LAN_IP>:83;
34
-
35
- server_name _;
36
-
37
- # Trust PROXY-protocol headers only from the local frp client; plain
38
- # (LAN) connections keep their real $remote_addr untouched.
39
- set_real_ip_from 127.0.0.1;
40
- real_ip_header proxy_protocol;
41
-
42
- # ---- main entry: strip /pi/ and forward to the app root ----
43
- location /pi/ {
44
- proxy_pass http://127.0.0.1:8787/;
45
- proxy_http_version 1.1;
46
- # $http_host keeps the port — origin check compares hostname AND port.
47
- proxy_set_header Host $http_host;
48
- proxy_set_header X-Real-IP $remote_addr;
49
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
50
- proxy_set_header X-Forwarded-Proto $scheme;
51
- proxy_set_header Upgrade $http_upgrade;
52
- proxy_set_header Connection $connection_upgrade;
53
- proxy_read_timeout 3600s;
54
- proxy_send_timeout 3600s;
55
- }
56
-
57
- # ---- subpath WebSocket (frontend connects to ws://<host>/pi/ws under /pi/ base) ----
58
- location /pi/ws {
59
- proxy_pass http://127.0.0.1:8787/ws;
60
- proxy_http_version 1.1;
61
- proxy_set_header Host $http_host;
62
- proxy_set_header Upgrade $http_upgrade;
63
- proxy_set_header Connection $connection_upgrade;
64
- proxy_read_timeout 3600s;
65
- proxy_send_timeout 3600s;
66
- proxy_set_header X-Real-IP $remote_addr;
67
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
68
- }
69
-
70
- # ---- root WebSocket fallback (for direct ws://<host>/ws connections) ----
71
- location /ws {
72
- proxy_pass http://127.0.0.1:8787;
73
- proxy_http_version 1.1;
74
- proxy_set_header Host $http_host;
75
- proxy_set_header Upgrade $http_upgrade;
76
- proxy_set_header Connection $connection_upgrade;
77
- proxy_read_timeout 3600s;
78
- proxy_send_timeout 3600s;
79
- proxy_set_header X-Real-IP $remote_addr;
80
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
81
- }
82
-
83
- # ---- absolute asset paths baked into index.html ----
84
- location /assets/ {
85
- proxy_pass http://127.0.0.1:8787;
86
- }
87
- location = /favicon.svg {
88
- proxy_pass http://127.0.0.1:8787;
89
- }
90
-
91
- # ---- media preview / download / health API ----
92
- location /api/ {
93
- proxy_pass http://127.0.0.1:8787;
94
- }
95
-
96
- # bare root → app entry
97
- location = / {
98
- return 302 /pi/;
99
- }
100
- }
1
+ # pi-web-ui behind nginx at a sub-path: http://<host>:83/pi/
2
+ # Backend app: http://127.0.0.1:8787 (default PI_WEB_PORT env)
3
+ #
4
+ # IMPORTANT: pi-web-ui 0.23+ checks the WebSocket Origin against the request
5
+ # Host (hostname AND port). Every proxied location MUST forward the original
6
+ # Host with $http_host (keeps the port). Using $host (drops the port) or
7
+ # leaving Host unset (defaults to 127.0.0.1:8787) makes the upgrade fail with
8
+ # 403 — the page loads but chat/terminal keep reconnecting.
9
+ #
10
+ # Topology (two listeners on one port: frp + LAN coexist):
11
+ # frp (public) -> <PUBLIC_IP>:<PUBLIC_PORT> -> 127.0.0.1:83 (PROXY protocol v2)
12
+ # LAN users -> http://<LAN_IP>:83/pi/ (plain HTTP listener)
13
+ #
14
+ # frpc sends PROXY v2 to nginx (transport.proxyProtocolVersion = "v2"):
15
+ # * 127.0.0.1:83 proxy_protocol — only the local frp client connects
16
+ # here (it speaks PROXY v2; nginx then sees the real visitor IP).
17
+ # * <LAN_IP>:83 plain HTTP — LAN browsers, no PROXY header needed.
18
+ #
19
+ # Simpler alternative (no real client IPs): drop proxy_protocol entirely and
20
+ # use a single `listen 83;` — then frpc must NOT set proxyProtocolVersion.
21
+ #
22
+ # The frontend uses absolute paths (/ws WebSocket, /assets/*, /favicon.svg,
23
+ # /api/file…) so those get their own proxied locations next to /pi/.
24
+
25
+ # Reuse for Upgrade/Connection headers (WebSocket).
26
+ map $http_upgrade $connection_upgrade {
27
+ default upgrade;
28
+ '' close;
29
+ }
30
+
31
+ server {
32
+ listen 127.0.0.1:83 proxy_protocol;
33
+ listen <LAN_IP>:83;
34
+
35
+ server_name _;
36
+
37
+ # Trust PROXY-protocol headers only from the local frp client; plain
38
+ # (LAN) connections keep their real $remote_addr untouched.
39
+ set_real_ip_from 127.0.0.1;
40
+ real_ip_header proxy_protocol;
41
+
42
+ # ---- main entry: strip /pi/ and forward to the app root ----
43
+ location /pi/ {
44
+ proxy_pass http://127.0.0.1:8787/;
45
+ proxy_http_version 1.1;
46
+ # $http_host keeps the port — origin check compares hostname AND port.
47
+ proxy_set_header Host $http_host;
48
+ proxy_set_header X-Real-IP $remote_addr;
49
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
50
+ proxy_set_header X-Forwarded-Proto $scheme;
51
+ proxy_set_header Upgrade $http_upgrade;
52
+ proxy_set_header Connection $connection_upgrade;
53
+ proxy_read_timeout 3600s;
54
+ proxy_send_timeout 3600s;
55
+ }
56
+
57
+ # ---- subpath WebSocket (frontend connects to ws://<host>/pi/ws under /pi/ base) ----
58
+ location /pi/ws {
59
+ proxy_pass http://127.0.0.1:8787/ws;
60
+ proxy_http_version 1.1;
61
+ proxy_set_header Host $http_host;
62
+ proxy_set_header Upgrade $http_upgrade;
63
+ proxy_set_header Connection $connection_upgrade;
64
+ proxy_read_timeout 3600s;
65
+ proxy_send_timeout 3600s;
66
+ proxy_set_header X-Real-IP $remote_addr;
67
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
68
+ }
69
+
70
+ # ---- root WebSocket fallback (for direct ws://<host>/ws connections) ----
71
+ location /ws {
72
+ proxy_pass http://127.0.0.1:8787;
73
+ proxy_http_version 1.1;
74
+ proxy_set_header Host $http_host;
75
+ proxy_set_header Upgrade $http_upgrade;
76
+ proxy_set_header Connection $connection_upgrade;
77
+ proxy_read_timeout 3600s;
78
+ proxy_send_timeout 3600s;
79
+ proxy_set_header X-Real-IP $remote_addr;
80
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
81
+ }
82
+
83
+ # ---- absolute asset paths baked into index.html ----
84
+ location /assets/ {
85
+ proxy_pass http://127.0.0.1:8787;
86
+ }
87
+ location = /favicon.svg {
88
+ proxy_pass http://127.0.0.1:8787;
89
+ }
90
+
91
+ # ---- media preview / download / health API ----
92
+ location /api/ {
93
+ proxy_pass http://127.0.0.1:8787;
94
+ }
95
+
96
+ # bare root → app entry
97
+ location = / {
98
+ return 302 /pi/;
99
+ }
100
+ }
@@ -1,36 +1,36 @@
1
- # pi-web-ui systemd unit — Linux auto-start on boot.
2
- #
3
- # Install (adjust User/WorkingDirectory/Environment to taste):
4
- # sudo npm i -g pi-web-ui
5
- # sudo cp deploy/pi-web-ui.service /etc/systemd/system/
6
- # sudo systemctl daemon-reload
7
- # sudo systemctl enable --now pi-web-ui
8
- # sudo systemctl status pi-web-ui
9
- #
10
- # Logs: journalctl -u pi-web-ui -f
11
-
12
- [Unit]
13
- Description=pi-web-ui — web chat for the pi coding agent
14
- After=network.target
15
-
16
- [Service]
17
- Type=simple
18
- # Run as an unprivileged user (change to your user, e.g. yourname)
19
- User=YOUR_USER
20
- # The workspace the agent operates in (read/edit/bash/write)
21
- WorkingDirectory=/home/YOUR_USER
22
- Environment=PI_WEB_PORT=8787
23
- # For privileged ports (1-1023, e.g. 80/443), uncomment both lines:
24
- #CapabilityBoundingSet=CAP_NET_BIND_SERVICE
25
- #AmbientCapabilities=CAP_NET_BIND_SERVICE
26
- # Optional authentication; protect this file if you store a token here.
27
- #Environment="PI_WEB_TOKEN=replace-with-your-token"
28
- # Point at your pi config dir if it's not the default ~/.pi/agent
29
- #Environment=PI_CODING_AGENT_DIR=/home/YOUR_USER/.pi/agent
30
- ExecStart=/usr/bin/pi-web-ui
31
- Restart=on-failure
32
- RestartSec=5
33
- # npm global bin may live elsewhere (nvm, etc.) — find with: which pi-web-ui
34
-
35
- [Install]
36
- WantedBy=multi-user.target
1
+ # pi-web-ui systemd unit — Linux auto-start on boot.
2
+ #
3
+ # Install (adjust User/WorkingDirectory/Environment to taste):
4
+ # sudo npm i -g pi-web-ui
5
+ # sudo cp deploy/pi-web-ui.service /etc/systemd/system/
6
+ # sudo systemctl daemon-reload
7
+ # sudo systemctl enable --now pi-web-ui
8
+ # sudo systemctl status pi-web-ui
9
+ #
10
+ # Logs: journalctl -u pi-web-ui -f
11
+
12
+ [Unit]
13
+ Description=pi-web-ui — web chat for the pi coding agent
14
+ After=network.target
15
+
16
+ [Service]
17
+ Type=simple
18
+ # Run as an unprivileged user (change to your user, e.g. yourname)
19
+ User=YOUR_USER
20
+ # The workspace the agent operates in (read/edit/bash/write)
21
+ WorkingDirectory=/home/YOUR_USER
22
+ Environment=PI_WEB_PORT=8787
23
+ # For privileged ports (1-1023, e.g. 80/443), uncomment both lines:
24
+ #CapabilityBoundingSet=CAP_NET_BIND_SERVICE
25
+ #AmbientCapabilities=CAP_NET_BIND_SERVICE
26
+ # Optional authentication; protect this file if you store a token here.
27
+ #Environment="PI_WEB_TOKEN=replace-with-your-token"
28
+ # Point at your pi config dir if it's not the default ~/.pi/agent
29
+ #Environment=PI_CODING_AGENT_DIR=/home/YOUR_USER/.pi/agent
30
+ ExecStart=/usr/bin/pi-web-ui
31
+ Restart=on-failure
32
+ RestartSec=5
33
+ # npm global bin may live elsewhere (nvm, etc.) — find with: which pi-web-ui
34
+
35
+ [Install]
36
+ WantedBy=multi-user.target
@@ -141,7 +141,8 @@ import { scanAtMentions } from "./universal/universal-attachments.js";
141
141
  import { extractStreamingPayload, formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt, } from "./text-quote.js";
142
142
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
143
143
  import { generateScmCommitMessage } from "./scm-commitmsg.js";
144
- import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, estimatePromptTokens, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
144
+ import { estimateBaseContext, estimateContextWeights, reconcileContextCategories, } from "./context-usage.js";
145
+ import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
145
146
  import { listAllMcpServers, checkMcpServer, installMcpServer, saveMcpServer as saveMcpServerFile, deleteMcpServer as deleteMcpServerFile, toggleMcpServer as toggleMcpServerFile, } from "./mcp-manager.js";
146
147
  import { fetchRemoteMcpMarket, fetchRemoteSkillMarket, fetchRemoteSkillContent } from "./market-service.js";
147
148
  import { McpOAuthUi } from "./mcp-oauth-ui.js";
@@ -2090,6 +2091,8 @@ export class ClientSession {
2090
2091
  }
2091
2092
  /** 会话级 Base Tokens 缓存(避免在节流快照热路径上重复计算正则)。 */
2092
2093
  cachedBaseTokens = null;
2094
+ cachedContextWeights = null;
2095
+ contextMessageWeights = new WeakMap();
2093
2096
  /** 指定会话(缺省 = 活跃会话)系统提示词 + 工具 schema 的基础 token 开销
2094
2097
  * (与设置面板中的「合计」完全一致)。会话未就绪返回 null——调用方必须区分
2095
2098
  * null 与 0:把 0 写进 lastTurnBaseTokens 会让后续轮次双计全额 base。 */
@@ -2106,12 +2109,30 @@ export class ClientSession {
2106
2109
  const snap = this.sessionPromptSnapshot(conv);
2107
2110
  if (!snap)
2108
2111
  return null;
2109
- const prompt = estimatePromptTokens(snap.full);
2110
- const schema = estimatePromptTokens(snap.toolsSchema);
2111
- const tokens = prompt + schema;
2112
- this.cachedBaseTokens = { at: now, convId: conv.id, tokens };
2112
+ const { tokens, weights } = estimateBaseContext(snap, this.settingsSvc.current);
2113
+ this.cachedBaseTokens = { at: now, convId: conv.id, tokens, weights };
2113
2114
  return tokens;
2114
2115
  }
2116
+ /** Classification is best-effort and must never affect totals or compaction. */
2117
+ contextCategories(conv, tokens) {
2118
+ try {
2119
+ const base = this.cachedBaseTokens;
2120
+ if (!base || base.convId !== conv.id)
2121
+ return undefined;
2122
+ const now = Date.now();
2123
+ if (!this.cachedContextWeights ||
2124
+ this.cachedContextWeights.base !== base.weights ||
2125
+ now - this.cachedContextWeights.at >= STATS_CACHE_MS) {
2126
+ const state = conv.session.agent.state;
2127
+ const weights = estimateContextWeights(base.weights, state.messages, state.streamingMessage, this.contextMessageWeights);
2128
+ this.cachedContextWeights = { base: base.weights, at: now, weights };
2129
+ }
2130
+ return reconcileContextCategories(this.cachedContextWeights.weights, tokens);
2131
+ }
2132
+ catch {
2133
+ return undefined;
2134
+ }
2135
+ }
2115
2136
  /** 判断会话中是否已有大模型返回过有效 usage(input/output/totalTokens > 0)的定稿助手消息。 */
2116
2137
  hasSettledAssistantUsage(conv) {
2117
2138
  try {
@@ -2268,13 +2289,27 @@ export class ClientSession {
2268
2289
  },
2269
2290
  };
2270
2291
  /** schedule_* 工具的数据宿主:全局调度存储+创建时刻 live 的 cwd/活动对话。 */
2271
- scheduleToolHost() {
2272
- return createScheduleToolHost({
2292
+ scheduleToolHost(anchor) {
2293
+ const source = () => {
2294
+ const home = anchor?.session ? this.toolConversationHome(anchor.session) : undefined;
2295
+ if (!home)
2296
+ throw new Error("Scheduled-task source session is no longer available");
2297
+ return home;
2298
+ };
2299
+ const host = createScheduleToolHost({
2273
2300
  getSchedulerStore: () => this.schedulerStore,
2274
2301
  getCwd: () => this.cwd,
2275
2302
  getActiveId: () => this.activeId,
2276
2303
  getConversation: (id) => this.convs.get(id),
2277
2304
  });
2305
+ if (anchor) {
2306
+ host.store = () => source().client.schedulerStore;
2307
+ host.executionSource = () => {
2308
+ const { conv } = source();
2309
+ return { cwd: conv.cwd, conversationId: conv.id, sessionFile: conv.session.sessionFile ?? "" };
2310
+ };
2311
+ }
2312
+ return host;
2278
2313
  }
2279
2314
  /** conversation_read 工具的数据宿主 */
2280
2315
  conversationReadHost() {
@@ -3499,7 +3534,7 @@ export class ClientSession {
3499
3534
  // 发起对话(ownerId,无则活动对话),到期 steer 语义唤醒它;子代理
3500
3535
  // 会话同样注册(owner 即真正派发的父对话)。开关走统一工具 tab。
3501
3536
  // DSH 引擎无 customTool 注册面,不接。
3502
- makeScheduleTool(this.scheduleToolHost(), ownerId, () => this.getLang()),
3537
+ makeScheduleTool(this.scheduleToolHost(bridgeAnchor), ownerId, () => this.getLang()),
3503
3538
  // 持久代码求值沙箱(eval):开关走统一工具 tab(ActiveSet 门控,默认关)。
3504
3539
  // ownerId 绑定当前会话;DSH 引擎无 customTool 注册面,不接。
3505
3540
  makeEvalTool({
@@ -5273,6 +5308,8 @@ export class ClientSession {
5273
5308
  const cu = s.contextUsage;
5274
5309
  if (!cu || cu.contextWindow <= 0)
5275
5310
  return stats.contextUsage;
5311
+ // Refresh category weights even when compaction supplies the total directly.
5312
+ this.currentBaseTokens(conv);
5276
5313
  const effectiveTokens = this.getEffectiveContextTokens(conv);
5277
5314
  const isEstimated = cu.tokens != null &&
5278
5315
  (conv.lastTurnBaseTokens == null || !this.hasSettledAssistantUsage(conv)) &&
@@ -5283,6 +5320,7 @@ export class ClientSession {
5283
5320
  percent: (effectiveTokens / cu.contextWindow) * 100,
5284
5321
  estimated: isEstimated,
5285
5322
  softCap: this.activeSoftCap(cu.contextWindow),
5323
+ categories: this.contextCategories(conv, effectiveTokens),
5286
5324
  };
5287
5325
  })(),
5288
5326
  };
@@ -13595,13 +13633,48 @@ export class ClientSession {
13595
13633
  return;
13596
13634
  const manager = session.sessionManager;
13597
13635
  const baseEntryId = findTurnBaseEntryId(manager, entryId);
13598
- if (baseEntryId)
13599
- manager.branch(baseEntryId);
13600
- else
13601
- manager.resetLeaf();
13602
- // Persist the explicit selection: calibration must not resurrect the
13603
- // abandoned, longer history when this same JSONL file is reopened.
13604
- manager.appendCustomEntry("pi-web-ui:reask", { version: 1 });
13636
+ const commitReask = () => {
13637
+ const previousLeaf = manager.getLeafId();
13638
+ try {
13639
+ if (baseEntryId)
13640
+ manager.branch(baseEntryId);
13641
+ else
13642
+ manager.resetLeaf();
13643
+ manager.appendCustomEntry("pi-web-ui:reask", { version: 1 });
13644
+ }
13645
+ catch (err) {
13646
+ // SDK append mutates indexes before writing; discard an uncommitted marker too.
13647
+ if (sessionFile)
13648
+ manager.setSessionFile(sessionFile);
13649
+ if (previousLeaf)
13650
+ manager.branch(previousLeaf);
13651
+ else
13652
+ manager.resetLeaf();
13653
+ throw err;
13654
+ }
13655
+ };
13656
+ // Cancel only tasks proven to originate in the suffix being discarded.
13657
+ // Persist cancellation first: a failed scheduler write must leave its transcript visible.
13658
+ if (this.schedulerStore && sessionFile) {
13659
+ const discardedCalls = new Set();
13660
+ const branch = manager.getBranch();
13661
+ const baseIndex = baseEntryId ? branch.findIndex((entry) => entry.id === baseEntryId) : -1;
13662
+ if (baseEntryId && baseIndex < 0)
13663
+ throw new Error("Reask base is no longer on the current branch");
13664
+ for (const entry of branch.slice(baseIndex + 1)) {
13665
+ if (entry.type !== "message" || entry.message.role !== "assistant")
13666
+ continue;
13667
+ for (const block of entry.message.content) {
13668
+ if (block.type === "toolCall" && block.name === "schedule")
13669
+ discardedCalls.add(block.id);
13670
+ }
13671
+ }
13672
+ this.schedulerStore.cancelUnstartedFromCalls(sessionFile, discardedCalls, commitReask);
13673
+ }
13674
+ else {
13675
+ // Persist the selection so calibration cannot resurrect abandoned history.
13676
+ commitReask();
13677
+ }
13605
13678
  session.agent.state.messages = manager.buildSessionContext().messages;
13606
13679
  // reload() refreshes resources; it does not replace the manager/leaf.
13607
13680
  await session.reload();
@@ -367,9 +367,9 @@ export async function buildAttachmentMessages(ctx, attachments) {
367
367
  content: [
368
368
  {
369
369
  type: "text",
370
- text: `
371
- <canvas-ref id="${attr(graphId)}" title="${attr(title)}">
372
- The user referenced this canvas. First use canvas(action="get", graphId="${attr(graphId)}") to inspect its topology and status. Only when the user requests execution, use canvas(action="run_all", graphId="${attr(graphId)}", prompt="the user requirements"); prompt supplies the run initialPrompt. Use canvas(action="get_log", graphId="${attr(graphId)}") for logs, and action="get" for status. This reference alone does not authorize or start a run.
370
+ text: `
371
+ <canvas-ref id="${attr(graphId)}" title="${attr(title)}">
372
+ The user referenced this canvas. First use canvas(action="get", graphId="${attr(graphId)}") to inspect its topology and status. Only when the user requests execution, use canvas(action="run_all", graphId="${attr(graphId)}", prompt="the user requirements"); prompt supplies the run initialPrompt. Use canvas(action="get_log", graphId="${attr(graphId)}") for logs, and action="get" for status. This reference alone does not authorize or start a run.
373
373
  </canvas-ref>`,
374
374
  },
375
375
  ],
@@ -709,9 +709,9 @@ The user referenced this canvas. First use canvas(action="get", graphId="${attr(
709
709
  content: [
710
710
  {
711
711
  type: "text",
712
- text: `
713
- <vision-bridge>
714
- ${transcript}
712
+ text: `
713
+ <vision-bridge>
714
+ ${transcript}
715
715
  </vision-bridge>`,
716
716
  },
717
717
  ...(pathImg
@@ -494,9 +494,9 @@ export class CanvasOrchestrator {
494
494
  this.appendLog(graph.id, nodeId, "system", `AI 裁决启动(${node.engine}/${judgeModel}):${judgeAsk.slice(0, 200)}`);
495
495
  }
496
496
  else if (!isCanvasPassthroughRole(node.role) && node.role !== "transform") {
497
- prompt += `\n\n【流水线自动化执行安全公约】:
498
- 1. 自治推进:这是无人值守的自动化协同流水线,严禁停留在向用户提问或等待人工决策阶段;遇分支情况请按最佳工程实践自主裁决并推进;
499
- 2. 避免前台阻塞:如需启动服务或验证测试,严禁启动阻塞终端的前台长进程;遇到端口占用(如 3000/3001 等)先检测并释放,验证完成后务必确保退出并清理所有后台子进程;
497
+ prompt += `\n\n【流水线自动化执行安全公约】:
498
+ 1. 自治推进:这是无人值守的自动化协同流水线,严禁停留在向用户提问或等待人工决策阶段;遇分支情况请按最佳工程实践自主裁决并推进;
499
+ 2. 避免前台阻塞:如需启动服务或验证测试,严禁启动阻塞终端的前台长进程;遇到端口占用(如 3000/3001 等)先检测并释放,验证完成后务必确保退出并清理所有后台子进程;
500
500
  3. 交付明确:完成时请提供清晰的修改摘要、接口契约与当前状态,供下游节点或审查门禁接力。`;
501
501
  }
502
502
  this.appendLog(graph.id, nodeId, "prompt", prompt.slice(0, 2000));
@@ -1,4 +1,5 @@
1
1
  import { Type } from "typebox";
2
+ import { Value } from "typebox/value";
2
3
  export function makeCommunicateTool(host) {
3
4
  const option = Type.Object({
4
5
  label: Type.String({ minLength: 1 }),
@@ -21,7 +22,29 @@ export function makeCommunicateTool(host) {
21
22
  optionsMap: Type.Optional(Type.Record(Type.String(), options)),
22
23
  });
23
24
  const target = Type.String({ minLength: 1, description: "parent, root, or a stable execution ID" });
24
- const parameters = Type.Union([
25
+ const questions = Type.Array(question, { minItems: 1, maxItems: 3 });
26
+ const message = Type.String({ description: "Message to send (nonempty for send), or optional context for request" });
27
+ const timeoutSeconds = Type.Number({ minimum: 0, maximum: 86400 });
28
+ const requestId = Type.String({ minLength: 1 });
29
+ const answers = Type.Array(Type.Object({
30
+ id: Type.String(),
31
+ selected: Type.Array(Type.String()),
32
+ custom: Type.Optional(Type.String()),
33
+ }), { minItems: 1, maxItems: 3 });
34
+ // Providers need root properties; action-specific requirements are enforced at execution.
35
+ const parameters = Type.Object({
36
+ action: Type.Union([
37
+ Type.Literal("read"),
38
+ Type.Literal("send"),
39
+ Type.Literal("request"),
40
+ Type.Literal("reply"),
41
+ Type.Literal("escalate"),
42
+ ], {
43
+ description: "read: inbox; send: requires to/message; request: to/questions; reply: requestId/answers; escalate: requestId",
44
+ }),
45
+ ...Type.Partial(Type.Object({ to: target, message, questions, timeoutSeconds, requestId, answers })).properties,
46
+ });
47
+ const actionParameters = Type.Union([
25
48
  Type.Object({ action: Type.Literal("read") }),
26
49
  Type.Object({
27
50
  action: Type.Literal("send"),
@@ -31,22 +54,18 @@ export function makeCommunicateTool(host) {
31
54
  Type.Object({
32
55
  action: Type.Literal("request"),
33
56
  to: target,
34
- questions: Type.Array(question, { minItems: 1, maxItems: 3 }),
35
- message: Type.Optional(Type.String({ description: "Optional context for the questions" })),
36
- timeoutSeconds: Type.Optional(Type.Number({ minimum: 0, maximum: 86400 })),
57
+ questions,
58
+ message: Type.Optional(message),
59
+ timeoutSeconds: Type.Optional(timeoutSeconds),
37
60
  }),
38
61
  Type.Object({
39
62
  action: Type.Literal("reply"),
40
- requestId: Type.String({ minLength: 1 }),
41
- answers: Type.Array(Type.Object({
42
- id: Type.String(),
43
- selected: Type.Array(Type.String()),
44
- custom: Type.Optional(Type.String()),
45
- }), { minItems: 1, maxItems: 3 }),
63
+ requestId,
64
+ answers,
46
65
  }),
47
66
  Type.Object({
48
67
  action: Type.Literal("escalate"),
49
- requestId: Type.String({ minLength: 1 }),
68
+ requestId,
50
69
  }),
51
70
  ]);
52
71
  return {
@@ -64,6 +83,13 @@ export function makeCommunicateTool(host) {
64
83
  ],
65
84
  parameters,
66
85
  execute: async (_id, params, signal) => {
86
+ // Adapters may call execute directly, bypassing SDK argument validation.
87
+ for (const schema of [parameters, actionParameters]) {
88
+ const errors = Value.Errors(schema, params);
89
+ if (errors.length) {
90
+ throw new Error(`Invalid communicate arguments: ${errors.map((error) => `${error.instancePath || "/"}: ${error.message}`).join("; ")}`);
91
+ }
92
+ }
67
93
  const { action, ...args } = params;
68
94
  const result = await host.communicate(action, args, signal);
69
95
  // Host results are bounded by the service; guard adapters too (wire details <=64KB).
@@ -1,12 +1,12 @@
1
1
  /** Additional focus for Pi's existing initial/update summary prompts; never replaces their format. */
2
- export const COMPACTION_RETENTION_INSTRUCTIONS = `Preserve the SDK's default structured checkpoint format. Within its existing sections, always retain the following categories when present; mark missing information as unknown rather than inventing it:
3
- - Goal: the active user goal, scope, and completion criteria.
4
- - Constraints & Preferences: explicit user requirements, prohibitions, permissions, and corrections that still apply.
5
- - Critical Context: verified facts and their evidence (observed outputs, exact paths, symbols, errors, and relevant references). Label hypotheses, inferences, and unverified claims explicitly; never promote them to facts.
6
- - Progress / Done and In Progress: actual changes, affected files, decisions and rationale, and what remains incomplete. Distinguish proposed work from applied changes.
7
- - Progress / Critical Context: validation commands, observed results, failures, and checks not run; never infer success from a proposed command or an absent error.
8
- - Blocked / Next Steps: unresolved questions, blockers, and concrete next actions needed to continue.
9
- Preserve all context-evidence:<sha256> references verbatim, including references in earlier summaries, with their associated claim and verification status. A reference alone does not prove a claim; do not invent, rewrite, or expand its contents.
2
+ export const COMPACTION_RETENTION_INSTRUCTIONS = `Preserve the SDK's default structured checkpoint format. Within its existing sections, always retain the following categories when present; mark missing information as unknown rather than inventing it:
3
+ - Goal: the active user goal, scope, and completion criteria.
4
+ - Constraints & Preferences: explicit user requirements, prohibitions, permissions, and corrections that still apply.
5
+ - Critical Context: verified facts and their evidence (observed outputs, exact paths, symbols, errors, and relevant references). Label hypotheses, inferences, and unverified claims explicitly; never promote them to facts.
6
+ - Progress / Done and In Progress: actual changes, affected files, decisions and rationale, and what remains incomplete. Distinguish proposed work from applied changes.
7
+ - Progress / Critical Context: validation commands, observed results, failures, and checks not run; never infer success from a proposed command or an absent error.
8
+ - Blocked / Next Steps: unresolved questions, blockers, and concrete next actions needed to continue.
9
+ Preserve all context-evidence:<sha256> references verbatim, including references in earlier summaries, with their associated claim and verification status. A reference alone does not prove a claim; do not invent, rewrite, or expand its contents.
10
10
  Treat any supplied summary as candidate notes to verify against the conversation, not as authoritative evidence. Condense redundant exploration without dropping the retained categories or still-applicable user constraints.`;
11
11
  /** Append without changing caller instructions; safe when both tool and adapter apply it. */
12
12
  export function appendCompactionInstructions(instructions) {