pi-web-ui 0.115.0 → 0.116.0

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 (117) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/bin/pi-web-ui.mjs +21 -1
  3. package/dist/gh-comment-781.md +5 -0
  4. package/dist/server/agent-service-daemon.js +84 -2
  5. package/dist/server/agent-service.js +107 -26
  6. package/dist/server/client-state.js +17 -2
  7. package/dist/server/device-center/bot-execution.js +29 -1
  8. package/dist/server/device-center/collab-service.js +36 -5
  9. package/dist/server/device-center/collab-tool.js +90 -5
  10. package/dist/server/device-center/execution-guides.js +2 -2
  11. package/dist/server/device-center/execution-instructions.js +2 -1
  12. package/dist/server/device-center/execution-settings.js +138 -25
  13. package/dist/server/device-center/executor.js +4 -1
  14. package/dist/server/device-center/file-sync.js +14 -13
  15. package/dist/server/device-center/group-context-message.js +3 -1
  16. package/dist/server/device-center/group-context.js +73 -3
  17. package/dist/server/device-center/hub-conversations.js +58 -3
  18. package/dist/server/device-center/hub-locks.js +320 -0
  19. package/dist/server/device-center/hub-page.js +13 -33
  20. package/dist/server/device-center/hub-webhooks.js +165 -0
  21. package/dist/server/device-center/hub.js +872 -64
  22. package/dist/server/device-center/local-hub.js +2 -1
  23. package/dist/server/device-center/local-page.js +17 -0
  24. package/dist/server/device-center/local.js +74 -1
  25. package/dist/server/device-center/partition-log.js +293 -0
  26. package/dist/server/device-center/runtime.js +49 -0
  27. package/dist/server/device-center/smoke-preview.js +3 -0
  28. package/dist/server/device-center/store.js +163 -64
  29. package/dist/server/device-center/task-scheduler.js +48 -3
  30. package/dist/server/device-center/transfers.js +41 -15
  31. package/dist/server/dispatch-domain-handlers.js +14 -3
  32. package/dist/server/durable/durable-capabilities.js +11 -0
  33. package/dist/server/engine-probe.js +112 -1
  34. package/dist/server/global-loader.js +119 -19
  35. package/dist/server/index.js +133 -16
  36. package/dist/server/managed.js +2 -0
  37. package/dist/server/markers/builtins/services.js +123 -0
  38. package/dist/server/markers/builtins/todo.js +189 -0
  39. package/dist/server/markers-list-tool.js +34 -0
  40. package/dist/server/model-admin.js +48 -6
  41. package/dist/server/model-enrich.js +10 -1
  42. package/dist/server/orchestrator.js +109 -0
  43. package/dist/server/plugins.js +64 -7
  44. package/dist/server/prompt-composer.js +39 -0
  45. package/dist/server/protocol-version.js +1 -1
  46. package/dist/server/reasoning-registry.js +207 -0
  47. package/dist/server/startup-banner.js +35 -0
  48. package/dist/server/subagents.js +2 -1
  49. package/dist/server/system-prompt-soul.js +41 -0
  50. package/dist/server/tool-manager.js +17 -9
  51. package/dist/server/unauthorized-page.js +319 -0
  52. package/dist/server/univer-service.js +448 -0
  53. package/dist/server/universal/drivers/dsh-driver.js +379 -0
  54. package/dist/test-artifact.md +9 -0
  55. package/dist/test-preview-modal.md +11 -0
  56. package/dist/test-report.html +20 -0
  57. package/docs/architecture-plugins.md +946 -0
  58. package/docs/device-center.md +6 -0
  59. package/package.json +2 -1
  60. package/web/dist/.build-assets.json +1 -1
  61. package/web/dist/assets/{BgTasksModal-BYzPgmoq.js → BgTasksModal-BDoOpj-F.js} +1 -1
  62. package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0i3O1FT.js} +1 -1
  63. package/web/dist/assets/{CanvasStudio-BCUeEf25.js → CanvasStudio-B8thymBN.js} +3 -3
  64. package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-zSxyIx1R.js} +3 -3
  65. package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
  66. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
  67. package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
  68. package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
  69. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
  70. package/web/dist/assets/{Dropdown-CGXD0DfT.js → Dropdown-C4LIhshN.js} +1 -1
  71. package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
  72. package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
  73. package/web/dist/assets/{GlobalSearchModal-mevF-ySi.js → GlobalSearchModal-BWgU8yPd.js} +1 -1
  74. package/web/dist/assets/{GlobalSearchModal-qL99FN_F.js → GlobalSearchModal-F7fNimKk.js} +1 -1
  75. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
  76. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
  77. package/web/dist/assets/{HintTip-LHwkS2jV.js → HintTip-c6d0TJoh.js} +1 -1
  78. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
  79. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
  80. package/web/dist/assets/{PiSetupModal-DE5-gEtI.js → PiSetupModal-BmMrrgB9.js} +1 -1
  81. package/web/dist/assets/{ProviderOAuthControls-6UMARucA.js → ProviderOAuthControls-BGSBIKD7.js} +1 -1
  82. package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
  83. package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
  84. package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
  85. package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
  86. package/web/dist/assets/{TerminalPanel-CTp_BZ4S.js → TerminalPanel-0CYvD72B.js} +2 -2
  87. package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-DDavKvFr.js} +2 -2
  88. package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-BsA-QTvN.js} +1 -1
  89. package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-DzoVQBuG.js} +1 -1
  90. package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
  91. package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-CUnXlQYX.js} +1 -1
  92. package/web/dist/assets/{desktop-kjBoE3Nu.js → desktop-aAKpvKJV.js} +1 -1
  93. package/web/dist/assets/index-C6DwztqE.css +1 -0
  94. package/web/dist/assets/index-CuN802Sj.js +93 -0
  95. package/web/dist/assets/index-EH5Fw9fa.js +93 -0
  96. package/web/dist/assets/{plugin-host-C8mNgghx.js → plugin-host-BRWib9DF.js} +1 -1
  97. package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-CfYSMEZg.js} +1 -1
  98. package/web/dist/assets/{theme-BXGpyTMh.js → theme-D2l_mLNo.js} +1 -1
  99. package/web/dist/index.html +10 -10
  100. package/web/dist/sw.js +1 -1
  101. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +0 -3
  102. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +0 -3
  103. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +0 -1
  104. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +0 -1
  105. package/web/dist/assets/FilePreview-B8iqnBjy.js +0 -2
  106. package/web/dist/assets/FilePreview-BqviZKCN.js +0 -2
  107. package/web/dist/assets/GroupConversation-B88Yy-lt.js +0 -3
  108. package/web/dist/assets/GroupConversation-BwP5NVOE.js +0 -3
  109. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +0 -2
  110. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +0 -2
  111. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +0 -2
  112. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +0 -20
  113. package/web/dist/assets/SettingsModal-CF-7MwqS.js +0 -20
  114. package/web/dist/assets/app-globals-DZNa9v8u.js +0 -325
  115. package/web/dist/assets/index-CsFs_HMb.css +0 -1
  116. package/web/dist/assets/index-DHeeHS_l.js +0 -85
  117. package/web/dist/assets/index-DTZch8uz.js +0 -85
@@ -1,5 +1,6 @@
1
1
  import { mkdir, readFile, open, rename, unlink } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { PartitionedAppendLog } from "./partition-log.js";
3
4
  import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
4
5
  import { projectConversationState, reconcileConversationState, } from "./task-state.js";
5
6
  export const taskPending = (task) => !isTerminal(task.status) || !!(task.cancelRequested && !task.stopConfirmed);
@@ -18,7 +19,135 @@ export function publicTask(task) {
18
19
  const { leaseToken: _token, ...visible } = task;
19
20
  return visible;
20
21
  }
21
- /** A single process owns a data directory. Transactions publish only after atomic replacement. */
22
+ /** Rows kept per room when replaying append logs; mirrors the group retention the Hub enforces. */
23
+ export const HUB_LOG_RETENTION = 500;
24
+ function createHubLogs(dataDir) {
25
+ const root = join(dataDir, "hub-log");
26
+ return {
27
+ messages: new PartitionedAppendLog({
28
+ dir: join(root, "messages"),
29
+ partition: (message) => message.roomId,
30
+ id: (message) => message.id,
31
+ retention: HUB_LOG_RETENTION,
32
+ }),
33
+ tasks: new PartitionedAppendLog({
34
+ dir: join(root, "tasks"),
35
+ partition: (task) => task.roomId,
36
+ id: (task) => task.id,
37
+ retention: HUB_LOG_RETENTION,
38
+ // Load-time retention must never drop work that is still queued, running or awaiting a stop.
39
+ protect: (task) => taskPending(task),
40
+ }),
41
+ conversationMessages: new PartitionedAppendLog({
42
+ dir: join(root, "conversation-messages"),
43
+ partition: (message) => message.conversationId,
44
+ id: (message) => message.id,
45
+ }),
46
+ };
47
+ }
48
+ function emptyHubState() {
49
+ return {
50
+ version: 2,
51
+ conversations: [],
52
+ conversationMessages: [],
53
+ deliveries: [],
54
+ reviews: [],
55
+ deliveryReceipts: [],
56
+ integrations: [],
57
+ accounts: [],
58
+ devices: [],
59
+ bots: [],
60
+ sessions: [],
61
+ rooms: [],
62
+ messages: [],
63
+ tasks: [],
64
+ receipts: [],
65
+ };
66
+ }
67
+ /** Tasks/messages are partitioned by room; conversations may reference a room row that no longer exists. */
68
+ function roomPartitionsOf(state) {
69
+ return new Set([
70
+ ...state.rooms.map((room) => room.id),
71
+ ...state.conversations.map((conversation) => conversation.roomId),
72
+ ]);
73
+ }
74
+ /** Merge log rows with rows still inlined by an older Hub; inline rows win (they are the older baseline). */
75
+ function mergeRows(stored, inline) {
76
+ if (!inline.length)
77
+ return [...stored];
78
+ if (!stored.length)
79
+ return [...inline];
80
+ const merged = new Map();
81
+ for (const row of inline)
82
+ merged.set(row.id, row);
83
+ for (const row of stored)
84
+ if (!merged.has(row.id))
85
+ merged.set(row.id, row);
86
+ return [...merged.values()];
87
+ }
88
+ async function loadHubFiles(dataDir, options = {}) {
89
+ await mkdir(dataDir, { recursive: true, mode: 0o700 });
90
+ let state;
91
+ try {
92
+ state = JSON.parse(await readFile(join(dataDir, "device-hub.json"), "utf8"));
93
+ if (state.version !== 2 ||
94
+ ![
95
+ state.accounts,
96
+ state.devices,
97
+ state.bots,
98
+ state.sessions,
99
+ state.rooms,
100
+ state.messages,
101
+ state.tasks,
102
+ state.receipts,
103
+ ].every(Array.isArray)) {
104
+ throw new Error("Invalid device hub store");
105
+ }
106
+ }
107
+ catch (error) {
108
+ if (error.code !== "ENOENT")
109
+ throw error;
110
+ state = emptyHubState();
111
+ }
112
+ state.conversations ??= [];
113
+ state.conversationMessages ??= [];
114
+ state.deliveries ??= [];
115
+ state.reviews ??= [];
116
+ state.deliveryReceipts ??= [];
117
+ state.integrations ??= [];
118
+ if (![
119
+ state.conversations,
120
+ state.conversationMessages,
121
+ state.deliveries,
122
+ state.reviews,
123
+ state.deliveryReceipts,
124
+ state.integrations,
125
+ ].every(Array.isArray))
126
+ throw new Error("Invalid conversation store");
127
+ const logs = createHubLogs(dataDir);
128
+ const roomPartitions = roomPartitionsOf(state);
129
+ const conversations = new Set(state.conversations.map((conversation) => conversation.id));
130
+ // Logs are the authority; inline rows only exist in files written before the split (or by an older Hub).
131
+ const storedMessages = await logs.messages.load(roomPartitions, options);
132
+ const storedTasks = await logs.tasks.load(roomPartitions, options);
133
+ const storedConversationMessages = await logs.conversationMessages.load(conversations, options);
134
+ const legacy = state.messages.length > 0 || state.tasks.length > 0 || state.conversationMessages.length > 0;
135
+ state.messages = mergeRows(storedMessages, state.messages);
136
+ state.tasks = mergeRows(storedTasks, state.tasks);
137
+ state.conversationMessages = mergeRows(storedConversationMessages, state.conversationMessages);
138
+ // Legacy state is a baseline, not evidence that historical transitions were observed.
139
+ for (const conversation of state.conversations) {
140
+ conversation.taskState = projectConversationState(state, conversation);
141
+ conversation.events ??= [];
142
+ }
143
+ return { state, logs, legacy };
144
+ }
145
+ /** Read the durable state without open() side effects (no interrupt marking); used by tests and tooling. */
146
+ export async function readPersistedHub(dataDir) {
147
+ // Read-only: never sweep orphan files or repair tails from an inspection path.
148
+ return (await loadHubFiles(dataDir, { sweep: false })).state;
149
+ }
150
+ /** A single process owns a data directory. Transactions publish only after the index replacement. */
22
151
  export class DeviceHubStore {
23
152
  state;
24
153
  listeners = new Set();
@@ -30,71 +159,21 @@ export class DeviceHubStore {
30
159
  }
31
160
  tail = Promise.resolve();
32
161
  path;
33
- constructor(dataDir, state) {
162
+ logs;
163
+ logDir;
164
+ constructor(dataDir, state, logs) {
34
165
  this.path = join(dataDir, "device-hub.json");
166
+ this.logDir = join(dataDir, "hub-log");
35
167
  this.state = state;
168
+ this.logs = logs;
36
169
  }
37
170
  static async open(dataDir) {
38
- await mkdir(dataDir, { recursive: true, mode: 0o700 });
39
- let state;
40
- try {
41
- state = JSON.parse(await readFile(join(dataDir, "device-hub.json"), "utf8"));
42
- if (state.version !== 2 ||
43
- ![
44
- state.accounts,
45
- state.devices,
46
- state.bots,
47
- state.sessions,
48
- state.rooms,
49
- state.messages,
50
- state.tasks,
51
- state.receipts,
52
- ].every(Array.isArray)) {
53
- throw new Error("Invalid device hub store");
54
- }
55
- }
56
- catch (error) {
57
- if (error.code !== "ENOENT")
58
- throw error;
59
- state = {
60
- version: 2,
61
- conversations: [],
62
- conversationMessages: [],
63
- deliveries: [],
64
- reviews: [],
65
- deliveryReceipts: [],
66
- integrations: [],
67
- accounts: [],
68
- devices: [],
69
- bots: [],
70
- sessions: [],
71
- rooms: [],
72
- messages: [],
73
- tasks: [],
74
- receipts: [],
75
- };
76
- }
77
- state.conversations ??= [];
78
- state.conversationMessages ??= [];
79
- state.deliveries ??= [];
80
- state.reviews ??= [];
81
- state.deliveryReceipts ??= [];
82
- state.integrations ??= [];
83
- if (![
84
- state.conversations,
85
- state.conversationMessages,
86
- state.deliveries,
87
- state.reviews,
88
- state.deliveryReceipts,
89
- state.integrations,
90
- ].every(Array.isArray))
91
- throw new Error("Invalid conversation store");
92
- // Legacy state is a baseline, not evidence that historical transitions were observed.
93
- for (const conversation of state.conversations) {
94
- conversation.taskState = projectConversationState(state, conversation);
95
- conversation.events ??= [];
96
- }
97
- const store = new DeviceHubStore(dataDir, state);
171
+ const { state, logs, legacy } = await loadHubFiles(dataDir);
172
+ const store = new DeviceHubStore(dataDir, state, logs);
173
+ // Move collections that older Hubs kept inline into their append logs. Logs are written first so
174
+ // an interrupted migration can be retried from the still-inline index without losing rows.
175
+ if (legacy)
176
+ await store.migrateInlineCollections();
98
177
  if (state.tasks.some((task) => !isTerminal(task.status))) {
99
178
  const now = Date.now();
100
179
  const recoveryGraceMs = 60_000;
@@ -158,13 +237,33 @@ export class DeviceHubStore {
158
237
  this.tail = operation.catch(() => { });
159
238
  return operation;
160
239
  }
161
- /** Kept as a method so I/O failures can be injected without replacing transaction semantics. */
240
+ /**
241
+ * Kept as a method so I/O failures can be injected without replacing transaction semantics.
242
+ * The index is replaced first, then the append logs: a log row always describes durable index state.
243
+ */
162
244
  async persist(state) {
245
+ await this.persistIndex(state);
246
+ await this.commitLogs(state);
247
+ }
248
+ async commitLogs(state) {
249
+ const rooms = roomPartitionsOf(state);
250
+ const conversations = new Set(state.conversations.map((conversation) => conversation.id));
251
+ await this.logs.messages.commit(state.messages, rooms);
252
+ await this.logs.tasks.commit(state.tasks, rooms);
253
+ await this.logs.conversationMessages.commit(state.conversationMessages, conversations);
254
+ }
255
+ /** One-time upgrade from Hubs that inlined messages/tasks/transcripts in the index file. */
256
+ async migrateInlineCollections() {
257
+ await this.commitLogs(this.state);
258
+ await this.persistIndex(this.state);
259
+ }
260
+ async persistIndex(state) {
163
261
  const temporary = `${this.path}.${randomUUID()}.tmp`;
262
+ const index = { ...state, messages: [], tasks: [], conversationMessages: [] };
164
263
  try {
165
264
  const file = await open(temporary, "wx", 0o600);
166
265
  try {
167
- await file.writeFile(JSON.stringify(state));
266
+ await file.writeFile(JSON.stringify(index));
168
267
  await file.sync();
169
268
  }
170
269
  finally {
@@ -6,14 +6,55 @@ export class DeviceTaskScheduler {
6
6
  settings;
7
7
  starvationThresholdMs;
8
8
  maxSkipsBeforeStarvation;
9
+ onChange;
9
10
  queue = [];
10
11
  active = new Set();
11
12
  roomDispatchHistory = new Map();
12
13
  constructor(options) {
13
14
  const validated = validateExecutionSettings(options?.initialSettings);
14
15
  this.settings = validated.valid ? { ...validated.value } : { ...DEFAULT_EXECUTION_SETTINGS };
15
- this.starvationThresholdMs = options?.starvationThresholdMs ?? 8000;
16
- this.maxSkipsBeforeStarvation = options?.maxSkipsBeforeStarvation ?? 3;
16
+ this.starvationThresholdMs = options?.starvationThresholdMs ?? this.settings.starvationThresholdMs ?? 8000;
17
+ this.maxSkipsBeforeStarvation = options?.maxSkipsBeforeStarvation ?? this.settings.maxSkipsBeforeStarvation ?? 3;
18
+ this.onChange = options?.onChange;
19
+ this.restoreState(options?.persistedState);
20
+ }
21
+ /** Fairness history is in-memory scheduling state; persist it so a restart cannot reset room fairness. */
22
+ snapshotState() {
23
+ return {
24
+ version: 1,
25
+ rooms: [...this.roomDispatchHistory].map(([roomId, history]) => ({
26
+ roomId,
27
+ lastDispatchedAt: history.lastDispatchedAt,
28
+ count: history.count,
29
+ })),
30
+ };
31
+ }
32
+ restoreState(value) {
33
+ if (!value || typeof value !== "object" || Array.isArray(value))
34
+ return;
35
+ const state = value;
36
+ if (state.version !== 1 || !Array.isArray(state.rooms))
37
+ return;
38
+ for (const entry of state.rooms.slice(0, DeviceTaskScheduler.MAX_ROOM_HISTORY)) {
39
+ if (!entry || typeof entry !== "object")
40
+ continue;
41
+ const { roomId, lastDispatchedAt, count } = entry;
42
+ if (typeof roomId !== "string" || !roomId || roomId.length > 128)
43
+ continue;
44
+ if (!Number.isSafeInteger(lastDispatchedAt) || lastDispatchedAt < 0)
45
+ continue;
46
+ if (!Number.isSafeInteger(count) || count < 0)
47
+ continue;
48
+ this.roomDispatchHistory.set(roomId, { lastDispatchedAt, count });
49
+ }
50
+ }
51
+ changed() {
52
+ try {
53
+ this.onChange?.();
54
+ }
55
+ catch {
56
+ /* persistence scheduling must never break dispatch */
57
+ }
17
58
  }
18
59
  getSettings() {
19
60
  return { ...this.settings };
@@ -24,6 +65,8 @@ export class DeviceTaskScheduler {
24
65
  throw new Error(validation.error);
25
66
  }
26
67
  this.settings = { ...validation.value };
68
+ this.starvationThresholdMs = this.settings.starvationThresholdMs ?? 8000;
69
+ this.maxSkipsBeforeStarvation = this.settings.maxSkipsBeforeStarvation ?? 3;
27
70
  this.drain();
28
71
  return { ...this.settings };
29
72
  }
@@ -69,9 +112,11 @@ export class DeviceTaskScheduler {
69
112
  history.lastDispatchedAt = Date.now();
70
113
  history.count++;
71
114
  this.roomDispatchHistory.set(roomId, history);
115
+ this.changed();
72
116
  }
73
117
  clearRoomHistory(roomId) {
74
- this.roomDispatchHistory.delete(roomId);
118
+ if (this.roomDispatchHistory.delete(roomId))
119
+ this.changed();
75
120
  }
76
121
  enqueue(task, callbacks, signal) {
77
122
  const canonicalRoot = executionRoot(task.root);
@@ -606,6 +606,7 @@ export async function installDeviceTransfers(options) {
606
606
  targetBotRevision: row.targetBotRevision,
607
607
  manifestHash: row.job?.manifestHash,
608
608
  status: row.job?.status ?? (row.applyStarted ? "applied" : "interrupted"),
609
+ applyStarted: !!row.applyStarted,
609
610
  error: row.job?.error,
610
611
  };
611
612
  }
@@ -1032,9 +1033,9 @@ export async function installDeviceTransfers(options) {
1032
1033
  let row;
1033
1034
  try {
1034
1035
  row = findUser(req);
1035
- if (!row.job || row.applyStarted)
1036
+ if (row.applyStarted || row.job?.status === "applying" || row.job?.status === "applied")
1036
1037
  fail(409, "Cannot abort an applied or applying transfer");
1037
- if (row.job.status === "cancelled")
1038
+ if (row.job?.status === "cancelled")
1038
1039
  return res.json(view(row));
1039
1040
  if (aborting.has(row.id))
1040
1041
  fail(409, "Transfer cancellation already running");
@@ -1042,19 +1043,44 @@ export async function installDeviceTransfers(options) {
1042
1043
  ownsAbort = true;
1043
1044
  await confirmStopped(row);
1044
1045
  authorize(row);
1045
- const active = running.get(row.id);
1046
- row = await updateJob(row.id, (j) => {
1047
- j.status = "cancelling";
1048
- });
1049
- authorize(row);
1050
- active?.controller.abort(new Error("Transfer cancelled"));
1051
- if (active)
1052
- await active.done;
1053
- if (active?.blocked)
1054
- fail(409, "Sender stop unconfirmed; device recovery required");
1055
- authorize(row);
1056
- if (active && running.get(row.id) === active)
1057
- releaseSlot(row.id);
1046
+ if (!row.job) {
1047
+ const id = row.id;
1048
+ row = await transact((draft) => {
1049
+ const current = draft.find((r) => r.id === id);
1050
+ if (current.applyStarted || current.job?.status === "applying" || current.job?.status === "applied")
1051
+ fail(409, "Cannot abort an applied or applying transfer");
1052
+ if (!current.job) {
1053
+ current.job = {
1054
+ idempotencyKey: `agent:${id}`,
1055
+ fingerprint: id,
1056
+ paths: [],
1057
+ recursive: false,
1058
+ status: "cancelling",
1059
+ summary: {},
1060
+ };
1061
+ }
1062
+ else {
1063
+ current.job.status = "cancelling";
1064
+ }
1065
+ return current;
1066
+ });
1067
+ authorize(row);
1068
+ }
1069
+ else {
1070
+ const active = running.get(row.id);
1071
+ row = await updateJob(row.id, (j) => {
1072
+ j.status = "cancelling";
1073
+ });
1074
+ authorize(row);
1075
+ active?.controller.abort(new Error("Transfer cancelled"));
1076
+ if (active)
1077
+ await active.done;
1078
+ if (active?.blocked)
1079
+ fail(409, "Sender stop unconfirmed; device recovery required");
1080
+ authorize(row);
1081
+ if (active && running.get(row.id) === active)
1082
+ releaseSlot(row.id);
1083
+ }
1058
1084
  slot = reserve(row);
1059
1085
  const activeRow = row;
1060
1086
  slot.done = (async () => {
@@ -1,4 +1,5 @@
1
1
  import { SchedulerValidationError } from "./scheduler-tasks.js";
2
+ import { normalizePathKey } from "./client-state.js";
2
3
  /** 文件与工作区相关操作 */
3
4
  export function handleFileMessage(msg, cs) {
4
5
  switch (msg.type) {
@@ -407,7 +408,7 @@ export function handleTerminalMessage(msg, cs) {
407
408
  }
408
409
  }
409
410
  /** 会话生命周期与分支管理相关操作 */
410
- export function handleSessionLifecycleMessage(msg, cs, send) {
411
+ export function handleSessionLifecycleMessage(msg, cs, send, daemon, clientId) {
411
412
  switch (msg.type) {
412
413
  case "new_chat": {
413
414
  let acknowledged = false;
@@ -449,7 +450,12 @@ export function handleSessionLifecycleMessage(msg, cs, send) {
449
450
  void cs.rollbackSession?.(msg.messageId, msg.conversationId, msg.restoreWorkspace);
450
451
  return true;
451
452
  case "list_sessions":
452
- void cs.refreshSessions();
453
+ if (msg.path && normalizePathKey(msg.path) !== normalizePathKey(cs.cwd)) {
454
+ void cs.pushSessionsForCwd?.(msg.path);
455
+ }
456
+ else {
457
+ void cs.refreshSessions();
458
+ }
453
459
  return true;
454
460
  case "list_projects":
455
461
  void cs.pushProjects();
@@ -467,7 +473,12 @@ export function handleSessionLifecycleMessage(msg, cs, send) {
467
473
  void cs.renameConversation(msg.id, msg.name);
468
474
  return true;
469
475
  case "dismiss_conversation":
470
- void cs.dismissConversation(msg.id, msg.withFinishedSubagents, msg.force);
476
+ if (clientId && daemon?.dismissConversation) {
477
+ void daemon.dismissConversation(clientId, msg);
478
+ }
479
+ else {
480
+ void cs.dismissConversation(msg.id, msg.withFinishedSubagents, msg.force);
481
+ }
471
482
  return true;
472
483
  case "persist_conversation":
473
484
  void cs.persistConversation?.(msg.id);
@@ -0,0 +1,11 @@
1
+ /**
2
+ * durable-capabilities.ts — Pi Durable 引擎的能力事实源。
3
+ */
4
+ import { DEFAULT_DURABLE_CAPABILITIES } from "../engine-capabilities.js";
5
+ export { DEFAULT_DURABLE_CAPABILITIES };
6
+ export function resolveDurableCapabilities(caps) {
7
+ return {
8
+ ...DEFAULT_DURABLE_CAPABILITIES,
9
+ ...caps,
10
+ };
11
+ }
@@ -40,7 +40,7 @@ const CACHE_TTL_MS = 5000;
40
40
  /** 远端 npm registry 查询缓存:5 分钟 */
41
41
  const REGISTRY_CACHE_TTL_MS = 5 * 60 * 1000;
42
42
  const registryCache = new Map();
43
- /** 引擎状态原子字典:单一事实源,收敛 status / probedAt / updating 三元组,杜绝独立状态撕裂 */
43
+ /** 引擎状态原子字典:单一事实源,收敛 status / probedAt / updating / uninstalling,杜绝独立状态撕裂 */
44
44
  const engineRegistry = new Map([
45
45
  [
46
46
  "pi",
@@ -48,6 +48,7 @@ const engineRegistry = new Map([
48
48
  status: { id: "pi", installed: true, packageName: ENGINE_PACKAGES.pi.packageName, version: VERSION },
49
49
  probedAt: 0,
50
50
  updating: false,
51
+ uninstalling: false,
51
52
  },
52
53
  ],
53
54
  [
@@ -56,6 +57,7 @@ const engineRegistry = new Map([
56
57
  status: { id: "dsh", installed: false, packageName: ENGINE_PACKAGES.dsh.packageName },
57
58
  probedAt: 0,
58
59
  updating: false,
60
+ uninstalling: false,
59
61
  },
60
62
  ],
61
63
  [
@@ -64,6 +66,7 @@ const engineRegistry = new Map([
64
66
  status: { id: "claude", installed: false, packageName: ENGINE_PACKAGES.claude.packageName },
65
67
  probedAt: 0,
66
68
  updating: false,
69
+ uninstalling: false,
67
70
  },
68
71
  ],
69
72
  [
@@ -72,6 +75,7 @@ const engineRegistry = new Map([
72
75
  status: { id: "codex", installed: false, packageName: ENGINE_PACKAGES.codex.packageName },
73
76
  probedAt: 0,
74
77
  updating: false,
78
+ uninstalling: false,
75
79
  },
76
80
  ],
77
81
  [
@@ -80,6 +84,7 @@ const engineRegistry = new Map([
80
84
  status: { id: "durable", installed: false, packageName: ENGINE_PACKAGES.durable.packageName },
81
85
  probedAt: 0,
82
86
  updating: false,
87
+ uninstalling: false,
83
88
  },
84
89
  ],
85
90
  ]);
@@ -87,6 +92,7 @@ function toPublicStatus(entry) {
87
92
  return {
88
93
  ...entry.status,
89
94
  ...(entry.updating ? { updating: true } : {}),
95
+ ...(entry.uninstalling ? { uninstalling: true } : {}),
90
96
  };
91
97
  }
92
98
  /**
@@ -313,6 +319,7 @@ export async function probeEngine(id, force = false) {
313
319
  status: result,
314
320
  probedAt: Date.now(),
315
321
  updating: entry?.updating ?? false,
322
+ uninstalling: entry?.uninstalling ?? false,
316
323
  };
317
324
  engineRegistry.set(id, updatedEntry);
318
325
  return toPublicStatus(updatedEntry);
@@ -354,6 +361,7 @@ export async function probeAllEngines(force = false) {
354
361
  status: res,
355
362
  probedAt: timestamp,
356
363
  updating: existing?.updating ?? false,
364
+ uninstalling: existing?.uninstalling ?? false,
357
365
  });
358
366
  }
359
367
  return Array.from(engineRegistry.values()).map(toPublicStatus);
@@ -370,6 +378,109 @@ export function getCachedEngineStatuses() {
370
378
  export function isEngineUpdating(engineId) {
371
379
  return engineRegistry.get(engineId)?.updating ?? false;
372
380
  }
381
+ /**
382
+ * 查询指定引擎是否正在执行后台卸载子进程。
383
+ */
384
+ export function isEngineUninstalling(engineId) {
385
+ return engineRegistry.get(engineId)?.uninstalling ?? false;
386
+ }
387
+ /**
388
+ * 在后台子进程中执行引擎全局包卸载(npm uninstall -g <pkg>)。
389
+ */
390
+ export async function uninstallEngineBackground(engineId, options) {
391
+ if (engineId === "pi") {
392
+ return { ok: false, error: "Pi 为内置核心引擎,不支持卸载" };
393
+ }
394
+ const meta = ENGINE_PACKAGES[engineId];
395
+ if (!meta || !meta.packageName) {
396
+ return { ok: false, error: `不支持或未知的引擎「${engineId}」` };
397
+ }
398
+ const currentEntry = engineRegistry.get(engineId);
399
+ if (currentEntry?.uninstalling) {
400
+ return { ok: false, error: `引擎「${engineId}」正在后台卸载中,请勿重复操作` };
401
+ }
402
+ if (currentEntry?.updating) {
403
+ return { ok: false, error: `引擎「${engineId}」正在后台更新中,请稍候再试` };
404
+ }
405
+ if (currentEntry)
406
+ currentEntry.uninstalling = true;
407
+ const pkg = meta.packageName;
408
+ const timeoutMs = Math.max(10_000, Number(options?.timeoutMs ?? 180_000));
409
+ const isWin = process.platform === "win32";
410
+ const spawnCmd = isWin ? process.env.ComSpec || "cmd.exe" : "npm";
411
+ const spawnArgs = isWin ? ["/d", "/s", "/c", "npm", "uninstall", "-g", pkg] : ["uninstall", "-g", pkg];
412
+ try {
413
+ const child = spawn(spawnCmd, spawnArgs, {
414
+ windowsHide: true,
415
+ detached: !isWin,
416
+ stdio: ["ignore", "pipe", "pipe"],
417
+ env: {
418
+ ...process.env,
419
+ NO_COLOR: "1",
420
+ },
421
+ });
422
+ let out = "";
423
+ const appendOut = (chunk) => {
424
+ out = (out + chunk.toString()).slice(-8000);
425
+ };
426
+ child.stdout?.on("data", appendOut);
427
+ child.stderr?.on("data", appendOut);
428
+ const res = await new Promise((resolve) => {
429
+ let done = false;
430
+ const timer = setTimeout(() => {
431
+ if (done)
432
+ return;
433
+ done = true;
434
+ if (child.pid)
435
+ void killPidTree(child.pid);
436
+ resolve({ ok: false, code: null, error: `卸载超时(超过 ${Math.round(timeoutMs / 1000)} 秒)` });
437
+ }, timeoutMs);
438
+ child.on("error", (err) => {
439
+ if (done)
440
+ return;
441
+ done = true;
442
+ clearTimeout(timer);
443
+ resolve({ ok: false, code: null, error: err.message });
444
+ });
445
+ child.on("close", (code) => {
446
+ if (done)
447
+ return;
448
+ done = true;
449
+ clearTimeout(timer);
450
+ resolve({
451
+ ok: code === 0,
452
+ code,
453
+ error: code === 0 ? undefined : `npm 退出码 ${code}`,
454
+ });
455
+ });
456
+ });
457
+ if (res.ok) {
458
+ registryCache.delete(pkg);
459
+ try {
460
+ await probeAllEngines(true);
461
+ }
462
+ catch {
463
+ /* best effort */
464
+ }
465
+ }
466
+ return {
467
+ ok: res.ok,
468
+ error: res.error,
469
+ output: out.trim(),
470
+ };
471
+ }
472
+ catch (err) {
473
+ return {
474
+ ok: false,
475
+ error: err.message,
476
+ };
477
+ }
478
+ finally {
479
+ const finalEntry = engineRegistry.get(engineId);
480
+ if (finalEntry)
481
+ finalEntry.uninstalling = false;
482
+ }
483
+ }
373
484
  /**
374
485
  * 在后台子进程中执行引擎全局包更新(npm i -g <pkg>@latest)。
375
486
  * 避免在可见终端中通过 PTY 模拟输入导致命令首字母丢失或输入不全的问题。