@pi-chamber/web 0.9.4 → 0.9.6
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.
- package/README.md +15 -0
- package/dist/assets/DiagramView-0Iq1ak1I.js +1 -0
- package/dist/assets/{DiffView-CBOrV4hS.js → DiffView-DD1AFRi3.js} +2 -2
- package/dist/assets/FileSaveConflictDialog-CoKwDovb.js +3 -0
- package/dist/assets/FilesView-B_BF39ef.js +6 -0
- package/dist/assets/GitView-LFEpCasf.js +8 -0
- package/dist/assets/{JsonTreeView-CKWGm5MS.js → JsonTreeView-Cwjgvh4g.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-_7kV1yNw.js +12 -0
- package/dist/assets/PatchDiff-DG43C1HW.js +1 -0
- package/dist/assets/{SessionSwitcherContent-z9VYCXrT.js → SessionSwitcherContent-DCFXPY3d.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-QY7FKuEQ.js +2 -0
- package/dist/assets/SessionUnreadDot-DGT31A3z.js +1 -0
- package/dist/assets/SettingsView-eG-wN-yY.js +2 -0
- package/dist/assets/SettingsWindow-Dvnp8YrA.js +1 -0
- package/dist/assets/ToolOutputDialog-IlCrS6BR.js +8 -0
- package/dist/assets/ToolPartDiffPreview-D68JV0rR.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-DfaXovGB.js → VirtualizedFileDiff-Bl-rAYeh.js} +3 -3
- package/dist/assets/collapsible-BjniCdZ5.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-FSOm2VrW.js +3 -0
- package/dist/assets/contextFileOpenGuard-Bxb6AIPa.js +1 -0
- package/dist/assets/gitStatusPredicates-DxolDpMd.js +134 -0
- package/dist/assets/index-BpmGBboM.css +1 -0
- package/dist/assets/index-DZnzXhTs.js +8 -0
- package/dist/assets/index-Dh58uD3I.js +1 -0
- package/dist/assets/isDiffPlainText-D3_04XCh.js +1 -0
- package/dist/assets/isFilePlainText-CHouYQhH.js +1 -0
- package/dist/assets/{main-DG1oZ0Wj.js → main-CH3EqGJI.js} +2 -2
- package/dist/assets/main-HzTrVvbB.js +135 -0
- package/dist/assets/{markdownCore-DUjQU2i0.js → markdownCore-DJU4KvHP.js} +2 -2
- package/dist/assets/{miniChat-BEAtOkr9.js → miniChat-Ca3TpaaA.js} +2 -2
- package/dist/assets/{mobile-DOFBBQg2.js → mobile-lj4gpGsO.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-rUFfaD-T.js +2 -0
- package/dist/assets/renderMobileApp-CcWQ1sCf.js +11 -0
- package/dist/assets/runtimeEndpointReset-D2MmSbDk.js +53 -0
- package/dist/assets/{runtimeSurface-CySRuLbN.js → runtimeSurface-CE_VNjdH.js} +1 -1
- package/dist/assets/{useAppFontEffects-C4JL1x7k.js → useAppFontEffects-BvFAP9zG.js} +102 -103
- package/dist/assets/useFilesViewSearch-BD79p3A2.js +7 -0
- package/dist/assets/usePushVisibilityBeacon-CWg0j-Wg.js +10 -0
- package/dist/assets/useSwitcherItems-CazJ6Yox.js +1 -0
- package/dist/assets/{vendor-base-ui-vkqQ2P9o.js → vendor-base-ui-CdaWtC7e.js} +1 -1
- package/dist/assets/vendor-beautiful-mermaid-D3YCkKz7.js +111 -0
- package/dist/assets/{vendor-codemirror-commands-DYppkHEk.js → vendor-codemirror-commands-CNlncqrr.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-C493X_9w.js → vendor-codemirror-language-data-CP3j3-xu.js} +2 -2
- package/dist/assets/{vendor-replit-codemirror-vim-CGHHNQxC.js → vendor-replit-codemirror-vim-DaSwPsXt.js} +1 -1
- package/dist/assets/{web-components-B2Rw__yK.js → web-components-DWuadqra.js} +3 -3
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -2
- package/server/lib/fs/DOCUMENTATION.md +15 -3
- package/server/lib/fs/routes.js +369 -51
- package/server/lib/fs/routes.test.js +565 -3
- package/server/lib/fs/search.js +74 -29
- package/server/lib/pi/routes.js +56 -3
- package/server/lib/pi/routes.test.js +165 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +19 -6
- package/server/lib/pi/session-daemon/prompt-operations.test.js +151 -3
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
- package/server/lib/pi/session-daemon/sdk-upgrade.test.js +157 -0
- package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
- package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
- package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
- package/server/lib/pi/session-daemon/session-daemon.js +514 -107
- package/server/lib/pi/session-daemon/session-daemon.test.js +37 -13
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +749 -0
- package/server/lib/pi/session-daemon/session-replay.js +98 -0
- package/server/lib/pi/session-daemon/session-replay.test.js +628 -0
- package/server/lib/pi/ui-settings-store.js +16 -10
- package/server/lib/pi/ui-settings-store.test.js +91 -0
- package/server/lib/server/cors.js +6 -0
- package/server/lib/server/cors.test.js +3 -0
- package/server/lib/stt/DOCUMENTATION.md +1 -1
- package/server/lib/stt/local/worker-client.js +11 -3
- package/server/lib/stt/local/worker-client.test.js +255 -0
- package/server/lib/workspace/host.js +6 -2
- package/server/lib/workspace/host.test.js +15 -0
- package/dist/assets/DiagramEditor-DuGmiPZ5.js +0 -1
- package/dist/assets/DiagramView-CHy1Glsl.js +0 -1
- package/dist/assets/FilesView-CK2YVs_W.js +0 -6
- package/dist/assets/GitView-BEFLOv_7.js +0 -8
- package/dist/assets/MarkdownRendererImpl-hE_nmSqe.js +0 -12
- package/dist/assets/PatchDiff-BagRxMON.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-icxJk_lT.js +0 -2
- package/dist/assets/SessionUnreadDot-Bv-5KguB.js +0 -1
- package/dist/assets/SettingsView-Ck0qxtKP.js +0 -2
- package/dist/assets/SettingsWindow-GQRL2CdD.js +0 -1
- package/dist/assets/ToolOutputDialog-CxJUXVZW.js +0 -8
- package/dist/assets/ToolPartDiffPreview-BXuLRWHT.js +0 -1
- package/dist/assets/collapsible-szfZ0Syc.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-DG_E6iaN.js +0 -3
- package/dist/assets/contextFileOpenGuard-DPBE3ELv.js +0 -1
- package/dist/assets/gitStatusPredicates-OljV4Bb2.js +0 -134
- package/dist/assets/index-DNoEeZ2U.css +0 -1
- package/dist/assets/index-DmexVlTQ.js +0 -1
- package/dist/assets/index-KIdiBFJs.js +0 -8
- package/dist/assets/isDiffPlainText-aikgiqLb.js +0 -1
- package/dist/assets/isFilePlainText-D-Dl6LqX.js +0 -1
- package/dist/assets/main-BXdraZTZ.js +0 -135
- package/dist/assets/renderElectronMiniChatApp-B0K72YnS.js +0 -2
- package/dist/assets/renderMobileApp-Ca_BO_s4.js +0 -11
- package/dist/assets/runtimeEndpointReset-Cx2tsgTo.js +0 -54
- package/dist/assets/useFilesViewSearch-Du0DnmKs.js +0 -7
- package/dist/assets/usePushVisibilityBeacon-BnHxIv4r.js +0 -10
- package/dist/assets/useSwitcherItems-C91mwPJD.js +0 -1
- package/dist/assets/vendor-beautiful-mermaid-DneUawHp.js +0 -119
package/server/lib/fs/search.js
CHANGED
|
@@ -95,9 +95,20 @@ const fuzzyMatchScoreNormalized = (normalizedQuery, candidate) => {
|
|
|
95
95
|
return score;
|
|
96
96
|
};
|
|
97
97
|
|
|
98
|
-
export const createFsSearchRuntime = ({
|
|
98
|
+
export const createFsSearchRuntime = ({
|
|
99
|
+
fsPromises,
|
|
100
|
+
path,
|
|
101
|
+
spawn,
|
|
102
|
+
resolveGitBinaryForSpawn,
|
|
103
|
+
gitCheckIgnoreTimeoutMs = 2500,
|
|
104
|
+
}) => {
|
|
105
|
+
const effectiveGitCheckIgnoreTimeoutMs = Number.isFinite(gitCheckIgnoreTimeoutMs) && gitCheckIgnoreTimeoutMs > 0
|
|
106
|
+
? gitCheckIgnoreTimeoutMs
|
|
107
|
+
: 2500;
|
|
108
|
+
const inFlightGitignoreChecks = new Map();
|
|
109
|
+
|
|
99
110
|
const searchFilesystemFiles = async (rootPath, options) => {
|
|
100
|
-
const { limit, query, includeHidden, respectGitignore } = options;
|
|
111
|
+
const { limit, query, includeHidden, respectGitignore, type } = options;
|
|
101
112
|
const includeHiddenEntries = Boolean(includeHidden);
|
|
102
113
|
const normalizedQuery = query.trim().toLowerCase();
|
|
103
114
|
const matchAll = normalizedQuery.length === 0;
|
|
@@ -123,18 +134,47 @@ export const createFsSearchRuntime = ({ fsPromises, path, spawn, resolveGitBinar
|
|
|
123
134
|
return { dir, dirents, ignoredPaths: new Set() };
|
|
124
135
|
}
|
|
125
136
|
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
137
|
+
const checkKey = `${dir}\0${pathsToCheck.join('\0')}`;
|
|
138
|
+
let check = inFlightGitignoreChecks.get(checkKey);
|
|
139
|
+
if (!check) {
|
|
140
|
+
check = new Promise((resolve, reject) => {
|
|
141
|
+
const child = spawn(resolveGitBinaryForSpawn(), ['check-ignore', '--', ...pathsToCheck], {
|
|
142
|
+
cwd: dir,
|
|
143
|
+
windowsHide: true,
|
|
144
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
let stdout = '';
|
|
148
|
+
let settled = false;
|
|
149
|
+
let timeout = null;
|
|
150
|
+
const finish = (callback) => {
|
|
151
|
+
if (settled) return;
|
|
152
|
+
settled = true;
|
|
153
|
+
if (timeout) clearTimeout(timeout);
|
|
154
|
+
callback();
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
timeout = setTimeout(() => {
|
|
158
|
+
try {
|
|
159
|
+
child.kill('SIGKILL');
|
|
160
|
+
} catch {
|
|
161
|
+
}
|
|
162
|
+
finish(() => reject(new Error('Timed out while checking gitignore rules')));
|
|
163
|
+
}, effectiveGitCheckIgnoreTimeoutMs);
|
|
164
|
+
|
|
165
|
+
child.stdout?.on('data', (data) => { stdout += data.toString(); });
|
|
166
|
+
child.on('close', () => finish(() => resolve(stdout)));
|
|
167
|
+
child.on('error', (error) => finish(() => reject(error)));
|
|
131
168
|
});
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
169
|
+
inFlightGitignoreChecks.set(checkKey, check);
|
|
170
|
+
const clearCheck = () => {
|
|
171
|
+
if (inFlightGitignoreChecks.get(checkKey) === check) {
|
|
172
|
+
inFlightGitignoreChecks.delete(checkKey);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
check.then(clearCheck, clearCheck);
|
|
176
|
+
}
|
|
177
|
+
const result = await check;
|
|
138
178
|
|
|
139
179
|
const ignoredNames = new Set(
|
|
140
180
|
String(result)
|
|
@@ -144,8 +184,8 @@ export const createFsSearchRuntime = ({ fsPromises, path, spawn, resolveGitBinar
|
|
|
144
184
|
);
|
|
145
185
|
|
|
146
186
|
return { dir, dirents, ignoredPaths: ignoredNames };
|
|
147
|
-
} catch {
|
|
148
|
-
|
|
187
|
+
} catch (error) {
|
|
188
|
+
throw new Error(`Failed to apply gitignore rules in ${dir}`, { cause: error });
|
|
149
189
|
}
|
|
150
190
|
})
|
|
151
191
|
);
|
|
@@ -167,6 +207,21 @@ export const createFsSearchRuntime = ({ fsPromises, path, spawn, resolveGitBinar
|
|
|
167
207
|
if (shouldSkipSearchDirectory(entryName, includeHiddenEntries)) {
|
|
168
208
|
continue;
|
|
169
209
|
}
|
|
210
|
+
|
|
211
|
+
if (type === 'directory') {
|
|
212
|
+
const relativePath = normalizeRelativeSearchPath(rootPath, entryPath, path);
|
|
213
|
+
const score = matchAll ? 0 : fuzzyMatchScoreNormalized(normalizedQuery, relativePath);
|
|
214
|
+
if (score !== null) {
|
|
215
|
+
candidates.push({
|
|
216
|
+
name: entryName,
|
|
217
|
+
path: entryPath,
|
|
218
|
+
relativePath,
|
|
219
|
+
extension: undefined,
|
|
220
|
+
score,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
170
225
|
if (!visited.has(entryPath)) {
|
|
171
226
|
visited.add(entryPath);
|
|
172
227
|
queue.push(entryPath);
|
|
@@ -174,32 +229,22 @@ export const createFsSearchRuntime = ({ fsPromises, path, spawn, resolveGitBinar
|
|
|
174
229
|
continue;
|
|
175
230
|
}
|
|
176
231
|
|
|
177
|
-
if (!dirent.isFile()) {
|
|
232
|
+
if (!dirent.isFile() || type === 'directory') {
|
|
178
233
|
continue;
|
|
179
234
|
}
|
|
180
235
|
|
|
181
236
|
const relativePath = normalizeRelativeSearchPath(rootPath, entryPath, path);
|
|
182
237
|
const extension = entryName.includes('.') ? entryName.split('.').pop()?.toLowerCase() : undefined;
|
|
238
|
+
const score = matchAll ? 0 : fuzzyMatchScoreNormalized(normalizedQuery, relativePath);
|
|
183
239
|
|
|
184
|
-
if (
|
|
240
|
+
if (score !== null) {
|
|
185
241
|
candidates.push({
|
|
186
242
|
name: entryName,
|
|
187
243
|
path: entryPath,
|
|
188
244
|
relativePath,
|
|
189
245
|
extension,
|
|
190
|
-
score
|
|
246
|
+
score,
|
|
191
247
|
});
|
|
192
|
-
} else {
|
|
193
|
-
const score = fuzzyMatchScoreNormalized(normalizedQuery, relativePath);
|
|
194
|
-
if (score !== null) {
|
|
195
|
-
candidates.push({
|
|
196
|
-
name: entryName,
|
|
197
|
-
path: entryPath,
|
|
198
|
-
relativePath,
|
|
199
|
-
extension,
|
|
200
|
-
score,
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
248
|
}
|
|
204
249
|
|
|
205
250
|
if (candidates.length >= collectLimit) {
|
package/server/lib/pi/routes.js
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
} from './extension-protocol.js';
|
|
21
21
|
import { createPiUiSettingsStore } from './ui-settings-store.js';
|
|
22
22
|
import { createPiSnippetsStore } from './snippets-store.js';
|
|
23
|
+
import { isValidSendOperationId } from './session-daemon/send-operation-registry.js';
|
|
23
24
|
|
|
24
25
|
const UNAVAILABLE_CODES = new Set([
|
|
25
26
|
'DAEMON_UNAVAILABLE',
|
|
@@ -58,9 +59,11 @@ const writeDaemonError = (res, error) => {
|
|
|
58
59
|
? 502
|
|
59
60
|
: code === 'INVALID_SESSION'
|
|
60
61
|
? 404
|
|
61
|
-
: code === 'SESSION_IN_USE'
|
|
62
|
+
: code === 'SESSION_IN_USE' || code === 'OPERATION_PAYLOAD_MISMATCH'
|
|
62
63
|
? 409
|
|
63
|
-
: code === '
|
|
64
|
+
: code === 'OPERATION_EXPIRED'
|
|
65
|
+
? 410
|
|
66
|
+
: code === 'ATTACHMENT_TOO_LARGE'
|
|
64
67
|
? 413
|
|
65
68
|
: code === 'ATTACHMENT_LIMIT_REACHED'
|
|
66
69
|
? 429
|
|
@@ -1645,11 +1648,22 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1645
1648
|
for (const [suffix, command] of [['prompt', 'sessions.prompt'], ['steer', 'sessions.steer'], ['follow-up', 'sessions.followUp']]) {
|
|
1646
1649
|
app.post(`/api/pi/sessions/:sessionId/${suffix}`, async (req, res) => {
|
|
1647
1650
|
let payload = req.body && typeof req.body === 'object' ? req.body : {};
|
|
1651
|
+
if (payload.operationId !== undefined && !isValidSendOperationId(payload.operationId)) {
|
|
1652
|
+
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
1653
|
+
return;
|
|
1654
|
+
}
|
|
1655
|
+
if (payload.messageId !== undefined && (typeof payload.messageId !== 'string' || payload.messageId.length === 0 || payload.messageId.length > 512)) {
|
|
1656
|
+
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
1657
|
+
return;
|
|
1658
|
+
}
|
|
1648
1659
|
let attachmentIds = [];
|
|
1649
1660
|
try {
|
|
1650
1661
|
if (payload.attachments !== undefined) {
|
|
1651
1662
|
if (!Array.isArray(payload.attachments) || payload.attachments.some((attachment) => !attachment || typeof attachment.id !== 'string')) throw protocolMismatch();
|
|
1652
1663
|
attachmentIds = payload.attachments.map((attachment) => attachment.id);
|
|
1664
|
+
// Resolve happens before the daemon call; consume below is
|
|
1665
|
+
// idempotent (retired entries resolve), so a deduplicated replay
|
|
1666
|
+
// of an already-consumed attachment still returns the receipt.
|
|
1653
1667
|
const attachments = await attachmentStore.resolve(attachmentIds);
|
|
1654
1668
|
payload = { ...payload, attachments };
|
|
1655
1669
|
}
|
|
@@ -1664,11 +1678,50 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1664
1678
|
return;
|
|
1665
1679
|
}
|
|
1666
1680
|
await attachmentStore.consume?.(attachmentIds);
|
|
1667
|
-
res.status(202).json({
|
|
1681
|
+
res.status(202).json({
|
|
1682
|
+
accepted: true,
|
|
1683
|
+
messageId: result.messageId,
|
|
1684
|
+
...(result.deduplicated === true ? { deduplicated: true } : {}),
|
|
1685
|
+
});
|
|
1668
1686
|
}
|
|
1669
1687
|
});
|
|
1670
1688
|
}
|
|
1671
1689
|
|
|
1690
|
+
// Exact read-only receipt lookup for an uncertain send. The client passes
|
|
1691
|
+
// the full `kind + sessionId + operationId` identity; the daemon never
|
|
1692
|
+
// invokes Pi and never mutates the registry except bounded expiry
|
|
1693
|
+
// eviction. No epoch is required in this split (see stream-epoch branch).
|
|
1694
|
+
app.post('/api/pi/sessions/:sessionId/send-receipt', async (req, res) => {
|
|
1695
|
+
const sessionId = sessionIdFrom(req);
|
|
1696
|
+
if (!sessionId) {
|
|
1697
|
+
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
1698
|
+
return;
|
|
1699
|
+
}
|
|
1700
|
+
const body = req.body && typeof req.body === 'object' ? req.body : {};
|
|
1701
|
+
const kind = body.kind;
|
|
1702
|
+
const operationId = body.operationId;
|
|
1703
|
+
if ((kind !== 'prompt' && kind !== 'steer' && kind !== 'followUp') || !isValidSendOperationId(operationId)) {
|
|
1704
|
+
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
try {
|
|
1708
|
+
const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('sessions.sendReceipt', {
|
|
1709
|
+
kind,
|
|
1710
|
+
sessionId,
|
|
1711
|
+
operationId,
|
|
1712
|
+
});
|
|
1713
|
+
if (!result || typeof result !== 'object' || !['accepted', 'pending', 'expired', 'unknown'].includes(result.status)) {
|
|
1714
|
+
throw protocolMismatch();
|
|
1715
|
+
}
|
|
1716
|
+
res.json({
|
|
1717
|
+
status: result.status,
|
|
1718
|
+
...(result.status === 'accepted' && result.receipt && typeof result.receipt === 'object' ? { receipt: result.receipt } : {}),
|
|
1719
|
+
});
|
|
1720
|
+
} catch (error) {
|
|
1721
|
+
writeDaemonError(res, error);
|
|
1722
|
+
}
|
|
1723
|
+
});
|
|
1724
|
+
|
|
1672
1725
|
for (const [suffix, command] of [['abort', 'sessions.abort'], ['model', 'sessions.setModel'], ['thinking', 'sessions.setThinking']]) {
|
|
1673
1726
|
app.post(`/api/pi/sessions/:sessionId/${suffix}`, async (req, res) => {
|
|
1674
1727
|
const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, command, req.body && typeof req.body === 'object' ? req.body : {});
|
|
@@ -438,6 +438,171 @@ describe('Pi runtime route', () => {
|
|
|
438
438
|
expect(calls).toEqual([{ command: 'sessions.prompt', payload: { sessionId: 'session-1', text: 'read this', attachments: [{ id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, path: '/private/upload' }] } }]);
|
|
439
439
|
});
|
|
440
440
|
|
|
441
|
+
it('forwards the send operation id and reports a deduplicated receipt with consumed attachments', async () => {
|
|
442
|
+
const calls = [];
|
|
443
|
+
const consumed = [];
|
|
444
|
+
const attachmentStore = {
|
|
445
|
+
resolve: async (ids) => ids.map((id) => ({ id, name: 'note.txt', mime: 'text/plain', size: 3, path: '/private/upload' })),
|
|
446
|
+
consume: async (ids) => consumed.push(...ids),
|
|
447
|
+
};
|
|
448
|
+
const runtime = {
|
|
449
|
+
request: async (command, payload) => {
|
|
450
|
+
calls.push({ command, payload });
|
|
451
|
+
// The daemon deduplicates: the second identical send returns the
|
|
452
|
+
// original receipt with deduplicated: true and never executes.
|
|
453
|
+
return { accepted: true, messageId: 'message-1', ...(calls.length > 1 ? { deduplicated: true } : {}) };
|
|
454
|
+
},
|
|
455
|
+
};
|
|
456
|
+
const app = express();
|
|
457
|
+
app.use(express.json());
|
|
458
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, attachmentStore });
|
|
459
|
+
server = await listen(app);
|
|
460
|
+
const base = `http://127.0.0.1:${server.address().port}/api/pi`;
|
|
461
|
+
|
|
462
|
+
const send = () => fetch(`${base}/sessions/session-1/prompt`, {
|
|
463
|
+
method: 'POST',
|
|
464
|
+
headers: { 'Content-Type': 'application/json' },
|
|
465
|
+
body: JSON.stringify({ text: 'one intent', operationId: 'op-1', attachments: [{ id: 'attachment-1' }] }),
|
|
466
|
+
});
|
|
467
|
+
const first = await send();
|
|
468
|
+
expect(first.status).toBe(202);
|
|
469
|
+
await expect(first.json()).resolves.toEqual({ accepted: true, messageId: 'message-1' });
|
|
470
|
+
const duplicate = await send();
|
|
471
|
+
expect(duplicate.status).toBe(202);
|
|
472
|
+
await expect(duplicate.json()).resolves.toEqual({ accepted: true, messageId: 'message-1', deduplicated: true });
|
|
473
|
+
// Attachments resolve on both sends (retired entries resolve) and
|
|
474
|
+
// consumption stays idempotent.
|
|
475
|
+
expect(consumed).toEqual(['attachment-1', 'attachment-1']);
|
|
476
|
+
expect(calls).toHaveLength(2);
|
|
477
|
+
expect(calls[1].payload.operationId).toBe('op-1');
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
it('rejects invalid send ids and maps payload mismatch (409) and expiry (410)', async () => {
|
|
481
|
+
const runtime = {
|
|
482
|
+
request: async (_command, payload) => {
|
|
483
|
+
if (payload.operationId === 'op-mismatch') {
|
|
484
|
+
const error = new Error('mismatch');
|
|
485
|
+
error.code = 'OPERATION_PAYLOAD_MISMATCH';
|
|
486
|
+
throw error;
|
|
487
|
+
}
|
|
488
|
+
if (payload.operationId === 'op-expired') {
|
|
489
|
+
const error = new Error('expired');
|
|
490
|
+
error.code = 'OPERATION_EXPIRED';
|
|
491
|
+
throw error;
|
|
492
|
+
}
|
|
493
|
+
return { accepted: true, messageId: 'message-1' };
|
|
494
|
+
},
|
|
495
|
+
};
|
|
496
|
+
const app = express();
|
|
497
|
+
app.use(express.json());
|
|
498
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
|
|
499
|
+
server = await listen(app);
|
|
500
|
+
const base = `http://127.0.0.1:${server.address().port}/api/pi`;
|
|
501
|
+
|
|
502
|
+
const invalid = await fetch(`${base}/sessions/session-1/prompt`, {
|
|
503
|
+
method: 'POST',
|
|
504
|
+
headers: { 'Content-Type': 'application/json' },
|
|
505
|
+
body: JSON.stringify({ text: 'hello', operationId: 'bad id with spaces' }),
|
|
506
|
+
});
|
|
507
|
+
expect(invalid.status).toBe(400);
|
|
508
|
+
await expect(invalid.json()).resolves.toEqual({ error: { code: 'INVALID_ARGUMENT' } });
|
|
509
|
+
|
|
510
|
+
const invalidMessage = await fetch(`${base}/sessions/session-1/prompt`, {
|
|
511
|
+
method: 'POST',
|
|
512
|
+
headers: { 'Content-Type': 'application/json' },
|
|
513
|
+
body: JSON.stringify({ text: 'hello', messageId: '' }),
|
|
514
|
+
});
|
|
515
|
+
expect(invalidMessage.status).toBe(400);
|
|
516
|
+
await expect(invalidMessage.json()).resolves.toEqual({ error: { code: 'INVALID_ARGUMENT' } });
|
|
517
|
+
|
|
518
|
+
const mismatch = await fetch(`${base}/sessions/session-1/prompt`, {
|
|
519
|
+
method: 'POST',
|
|
520
|
+
headers: { 'Content-Type': 'application/json' },
|
|
521
|
+
body: JSON.stringify({ text: 'hello', operationId: 'op-mismatch' }),
|
|
522
|
+
});
|
|
523
|
+
expect(mismatch.status).toBe(409);
|
|
524
|
+
await expect(mismatch.json()).resolves.toEqual({ error: { code: 'OPERATION_PAYLOAD_MISMATCH' } });
|
|
525
|
+
|
|
526
|
+
const expired = await fetch(`${base}/sessions/session-1/prompt`, {
|
|
527
|
+
method: 'POST',
|
|
528
|
+
headers: { 'Content-Type': 'application/json' },
|
|
529
|
+
body: JSON.stringify({ text: 'hello', operationId: 'op-expired' }),
|
|
530
|
+
});
|
|
531
|
+
expect(expired.status).toBe(410);
|
|
532
|
+
await expect(expired.json()).resolves.toEqual({ error: { code: 'OPERATION_EXPIRED' } });
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
it('exposes an exact send-receipt lookup without invoking Pi', async () => {
|
|
536
|
+
const calls = [];
|
|
537
|
+
const runtime = {
|
|
538
|
+
request: async (command, payload) => {
|
|
539
|
+
calls.push({ command, payload });
|
|
540
|
+
if (command === 'sessions.sendReceipt') {
|
|
541
|
+
if (payload.operationId === 'op-accepted') {
|
|
542
|
+
return { status: 'accepted', receipt: { accepted: true, messageId: 'message-1' } };
|
|
543
|
+
}
|
|
544
|
+
return { status: payload.operationId === 'op-pending' ? 'pending' : payload.operationId === 'op-expired' ? 'expired' : 'unknown' };
|
|
545
|
+
}
|
|
546
|
+
return { accepted: true, messageId: 'message-1' };
|
|
547
|
+
},
|
|
548
|
+
};
|
|
549
|
+
const app = express();
|
|
550
|
+
app.use(express.json());
|
|
551
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
|
|
552
|
+
server = await listen(app);
|
|
553
|
+
const base = `http://127.0.0.1:${server.address().port}/api/pi/sessions/session-1/send-receipt`;
|
|
554
|
+
|
|
555
|
+
const accepted = await fetch(base, {
|
|
556
|
+
method: 'POST',
|
|
557
|
+
headers: { 'Content-Type': 'application/json' },
|
|
558
|
+
body: JSON.stringify({ kind: 'prompt', operationId: 'op-accepted' }),
|
|
559
|
+
});
|
|
560
|
+
expect(accepted.status).toBe(200);
|
|
561
|
+
await expect(accepted.json()).resolves.toEqual({ status: 'accepted', receipt: { accepted: true, messageId: 'message-1' } });
|
|
562
|
+
|
|
563
|
+
const pending = await fetch(base, {
|
|
564
|
+
method: 'POST',
|
|
565
|
+
headers: { 'Content-Type': 'application/json' },
|
|
566
|
+
body: JSON.stringify({ kind: 'steer', operationId: 'op-pending' }),
|
|
567
|
+
});
|
|
568
|
+
expect(pending.status).toBe(200);
|
|
569
|
+
// Pending carries no receipt: the outcome is still being accepted.
|
|
570
|
+
await expect(pending.json()).resolves.toEqual({ status: 'pending' });
|
|
571
|
+
|
|
572
|
+
const expired = await fetch(base, {
|
|
573
|
+
method: 'POST',
|
|
574
|
+
headers: { 'Content-Type': 'application/json' },
|
|
575
|
+
body: JSON.stringify({ kind: 'prompt', operationId: 'op-expired' }),
|
|
576
|
+
});
|
|
577
|
+
expect(expired.status).toBe(200);
|
|
578
|
+
await expect(expired.json()).resolves.toEqual({ status: 'expired' });
|
|
579
|
+
|
|
580
|
+
const unknown = await fetch(base, {
|
|
581
|
+
method: 'POST',
|
|
582
|
+
headers: { 'Content-Type': 'application/json' },
|
|
583
|
+
body: JSON.stringify({ kind: 'followUp', operationId: 'op-unknown' }),
|
|
584
|
+
});
|
|
585
|
+
expect(unknown.status).toBe(200);
|
|
586
|
+
await expect(unknown.json()).resolves.toEqual({ status: 'unknown' });
|
|
587
|
+
|
|
588
|
+
expect(calls.filter((call) => call.command === 'sessions.sendReceipt')).toHaveLength(4);
|
|
589
|
+
expect(calls[0].payload).toEqual({ kind: 'prompt', sessionId: 'session-1', operationId: 'op-accepted' });
|
|
590
|
+
|
|
591
|
+
const invalidKind = await fetch(base, {
|
|
592
|
+
method: 'POST',
|
|
593
|
+
headers: { 'Content-Type': 'application/json' },
|
|
594
|
+
body: JSON.stringify({ kind: 'promptx', operationId: 'op-accepted' }),
|
|
595
|
+
});
|
|
596
|
+
expect(invalidKind.status).toBe(400);
|
|
597
|
+
|
|
598
|
+
const invalidId = await fetch(base, {
|
|
599
|
+
method: 'POST',
|
|
600
|
+
headers: { 'Content-Type': 'application/json' },
|
|
601
|
+
body: JSON.stringify({ kind: 'prompt', operationId: 'bad id' }),
|
|
602
|
+
});
|
|
603
|
+
expect(invalidId.status).toBe(400);
|
|
604
|
+
});
|
|
605
|
+
|
|
441
606
|
it('streams binary attachments with bounded metadata and deletes unused uploads', async () => {
|
|
442
607
|
const calls = [];
|
|
443
608
|
const attachmentStore = {
|
|
@@ -11,7 +11,8 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
|
|
|
11
11
|
- `session-daemon.js`
|
|
12
12
|
- `createPiSessionRuntime({ cwd, agentDir })` creates a persistent Pi runtime using the selected server-side cwd and Pi agent directory. It uses Pi's normal settings, credentials, models, sessions, skills, prompts, context discovery, and native extensions. Every runtime creation binds extensions through `session.bindExtensions()` in rpc-like mode with a daemon-owned UI bridge, so pi extensions load exactly as they do under the Pi CLI's RPC mode. Sessions created outside PiChamber (Pi CLI or any other writer of the cwd-scoped JSONL directory) are the same records: `sessions.list`/`open` hydrate from `getEntries()`, then overlay the live `session.messages` / `state.streamingMessage` turn while `isStreaming` is true, including an unpersisted user prompt that has not flushed to JSONL yet. A later prompt must overlay live turns onto that log rather than replace it. An unmatched `toolCall` projects as `running` only while `isStreaming` is authoritative; the same unmatched call in an idle persisted turn projects as a timestamped interruption error instead of malformed `completed` state. `getSession` also reports `isStreaming` and `lifecycle` so a restarted UI can restore the working/tooling state without waiting for the next token.
|
|
13
13
|
- Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus the PiChamber-specific `ctx.ui.form` which resolves with a values object keyed by field id) publish an `extension.dialog` event and stay pending until answered by the `extensions.respond` private command; every answer, timeout, abort, session close, or daemon stop publishes an authoritative `extension.dialog.dismiss` event before resolving the extension so every connected client removes the modal (timeouts resolve defaults, abort resolves cancellation, form answers travel as a sanitized `values` record and are rejected unless required fields, number bounds, select options, and checkbox values match the pending form); fire-and-forget calls publish `extension.notify`, `extension.status`, `extension.widget`, session-scoped `extension.editor`, and `extension.title`; extension errors publish `extension.error`; appended custom entries and displayed custom messages publish `extension.entry` / `extension.message`. `pichamber.ui` entries with a stable `id` are additionally mirrored into normalized `extension.ui` panel events (latest wins per id, `removed: true` unregisters) and `pichamber.app` entries into sandboxed `extension.app` app surfaces; extension live state is kept in per-session maps and included in both `sessions.open` and `session.snapshot`. The open response must cover every extension event at or below its `lastSequence`, so first attach cannot skip one-time startup statuses before the browser stream connects; reconnect snapshots rebuild the same live panels. TUI-only component replacement, footers, and themes remain intentional no-ops; standard RPC editor replacement and window titles are projected to the focused browser session. Pending dialogs are cancelled when the owning runtime hits idle disposal or daemon stop so no extension thread blocks forever. Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
|
|
14
|
-
- `createSessionDaemon(options)` starts/stops the authenticated local socket daemon and validates its endpoint and setup inputs.
|
|
14
|
+
- `createSessionDaemon(options)` starts/stops the authenticated local socket daemon and validates its endpoint and setup inputs. Test seams inject `createRuntime` for resident runtimes and `createServices` (default `createAgentSessionServices`) for transient per-mutation prompt services.
|
|
15
|
+
- `session-replay.js` owns the byte- and count-bounded contiguous replay suffix (`MAX_REPLAY_EVENTS`, `MAX_REPLAY_BYTES`, `createSessionReplayLog`). It caches one serialized line per event for broadcast/replay reuse and reports contiguity (`canReplay`) without trusting filtered delivery.
|
|
15
16
|
- `daemon-process.js` is the detached private-process entrypoint. It reads the daemon credential from its owner-only sidecar, starts the socket, writes non-secret identity state only after readiness, persists an accepted ownership claim before acknowledging it over IPC, and removes only its own state on signal shutdown.
|
|
16
17
|
- `ipc-client.js` is the server-only authenticated request client. It owns JSONL framing and never exposes endpoint or credential values to callers.
|
|
17
18
|
- `runtime-registry.js` owns active runtime identities and session-local subscriptions. It rebinds the subscription after an SDK session replacement, rejects identity conflicts rather than displacing another runtime, and attempts every tracked disposal even when another disposal fails.
|
|
@@ -34,11 +35,12 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
|
|
|
34
35
|
- The public health route deliberately whitelists its response fields. It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
|
|
35
36
|
- A client must send an `authenticate` frame carrying the host-private daemon credential before it can issue a request. Credentials are never logged or returned.
|
|
36
37
|
- Frames are LF-delimited JSON. One frame has a 16 MiB maximum. Complete frames are parsed before the client bounds the remaining incomplete frame. Invalid JSON reports `MALFORMED_DAEMON_RESPONSE`; an oversized response reports `DAEMON_RESPONSE_TOO_LARGE`. A malformed, oversized, unauthenticated, or invalid request closes the connection.
|
|
37
|
-
- The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
|
|
38
|
-
- Each event and reconnect snapshot has a monotonic sequence. A reconnect
|
|
39
|
-
- Prompt, steer, and follow-up requests acknowledge acceptance
|
|
38
|
+
- The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/sendReceipt/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts from transient per-mutation services (never retained; Pi 0.84.1 exposes no dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager — file reads plus a cleared create-time timeout, no watchers/intervals/listeners, so dropping the reference lets GC reclaim it) with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. `providers.refresh` touches only live runtimes; the returned catalog always comes from the active runtime via `providers.list`. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
|
|
39
|
+
- Each event and reconnect snapshot has a monotonic sequence. A reconnect replays the retained contiguous suffix after its cursor when available, otherwise it receives an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions. The suffix lives in `session-replay.js` and is bounded by both count (1,024 events) and encoded wire bytes (8 MiB): eviction removes whole oldest events first and never truncates content, each event is serialized once and the cached line is reused for live broadcast and replay, and live delivery stays full-fidelity even for events too large to retain. The byte budget counts encoded wire bytes, not heap, and snapshots assign sequence numbers without replay insertion so numeric gaps from private snapshots are intentional. A single oversized event clears the retained suffix without being retained, an empty ring never replays, and a cursor beyond the latest sequence resynchronizes from a snapshot; contiguity is judged on the global suffix while delivery stays session-filtered, so a filtered client never replays through a gap. A missed suffix recovers through `session.snapshot` plus `sessions.open` hydrate, which re-reads persisted entries for tool finals and lifecycle.
|
|
40
|
+
- Prompt, steer, and follow-up requests acknowledge acceptance only after the Pi SDK preflight signal (session.prompt with preflightResult(true)); the daemon owns the still-running turn promise and publishes any asynchronous rejection as `session.error`. A preflight rejection (preflightResult(false)) propagates as the request rejection so dedup never caches it as accepted and the operation id stays reusable. Plain text uses prompt() with expandPromptTemplates:false and source:extension plus images; slash input keeps source:rpc. Pi can emit the live user-message start before that message is branch-readable, so the daemon queues each accepted prompt's path-free file metadata per delivery kind (`prompt`/`steer`/`followUp`) and adds it to the matching user start. SDK `queue_update` shrink is the authoritative owner of the next user start (steering drains before followUp regardless of send order); direct starts emit no shrink and fall back to oldest-by-generation. Requested `steer`/`followUp` always travels as SDK `streamingBehavior` (ignored while idle) so an idle arrival that races another sender still queues. Retention is decided at resolution from authoritative runtime state (`isStreaming` or SDK queue non-empty, never for handled extension commands); only queued resolutions keep metadata until their per-delivery start, all other completions clean a still-pending entry (an extension command that never emits a user start). The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
|
|
41
|
+
- Send-intent deduplication (`send-operation-registry.js`) owns the authoritative execution boundary for prompt/steer/followUp: the client labels each intent with a stable `operationId`, the daemon claims `kind + sessionId + operationId` BEFORE Pi activation, and an identical retry returns the original acceptance receipt (`{ accepted, messageId, deduplicated: true }`) without invoking Pi again. A concurrent duplicate of a still-pending intent shares the original outcome; the same `kind + sessionId + operationId` with a different payload (text, model, thinking, message id, or attachments) fails as `OPERATION_PAYLOAD_MISMATCH` (HTTP 409). The same id on a different kind or session is a different intent and executes independently, never a mismatch. Only acceptances are retained: request-path rejections happen before Pi runs (nothing executed, id reusable) while pending duplicates still share the original rejection, and every claim settles so pending duplicates never hang. Retention is bounded: receipts expire after `sendOperationTtlMs` (default ten minutes) and at most 1,024 accepted receipts are retained (oldest evicted to a bounded expired tombstone); pending claims are bounded separately (256 entries, never expired while active, new distinct pending past the bound fails as `SESSION_BUSY`). An expired or evicted id reports `expired` and a retry with the same id fails as `OPERATION_EXPIRED` (HTTP 410), never an automatic re-execution — callers must use a new operation id. `sessions.sendReceipt` is the exact read-only receipt lookup for an uncertain send: it requires the full `kind + sessionId + operationId` identity, never invokes Pi, and returns `accepted` (retained receipt), `pending`, `expired` (seen but retention gone, outcome unknown, never assume success), or `unknown` (never seen in this retention window, tombstone pressure, post-restart, or rejected before Pi ran). The registry is in-memory per daemon process with bounded tombstones (`expired` degrades to `unknown` under pressure): there is no lifetime at-most-once guarantee, only within the retention window; a restart loses receipts (documented crash window, replay re-executes). This split performs no stream-epoch guard and no per-session send/config lock; see the stream-epoch branch for the restart epoch guard.
|
|
40
42
|
- Registry keys combine the SDK session ID with its cwd. A replacement subscription is rebound to the replacement session so old-session events cannot be published under the new identity. A collision is a visible error; it never replaces or disposes an unrelated runtime.
|
|
41
|
-
- After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt. Agent and compaction starts cancel pending disposal, and
|
|
43
|
+
- After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). View-only access (`sessions.open`, `sessions.messages`, `sessions.tree`, plus navigate/fork/clone/abort/model/thinking/rename settlement) arms the same lifetime through `touchIdleDisposal`, so browsing old sessions without prompting cannot grow the registry unboundedly while the UI keeps only a bounded transcript cache. Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt or open. The touch clears first and re-arms only when the session is resident and idle-safe, so a read cannot race a pending operation and a repeated open extends the deadline. Agent and compaction starts cancel pending disposal, and prompt/compact entry clears it before activation. The timer refuses to dispose a session while `isStreaming` or `isCompacting` is authoritative, while a send is in flight (`activeSessionInputs`), while a resource reload is pending or running, while a provider retry is scheduled, or while compaction is running/retrying; pending extension dialogs are instead cancelled with an authoritative dismiss event. A read or prompt that arrives during an in-flight disposal waits for it and reopens from JSONL instead of adopting a dying runtime. There is deliberately no acquisition-path eviction: capacity pressure alone never disposes entries that are actively mounting.
|
|
42
44
|
- A startup validation failure writes only a stable failure code to the owner-only non-secret state sidecar. It never records a transcript, session path, or credential. The supervisor surfaces that code as unavailable instead of claiming an empty or idle session.
|
|
43
45
|
- After a forced crash, the next health, request, or subscription probe re-runs supervised startup. Each private health probe uses the supervisor's five-second operation budget; it must not inherit the general 30-second command timeout and hold every browser request until the browser aborts. Daemon readiness has its own 15-second bounded budget, separate from the shorter probe, lock, and shutdown budget, because loading Pi settings and provider/model catalogs can legitimately exceed five seconds. The supervisor removes an existing POSIX socket only when its recorded daemon PID is dead, the endpoint is a socket, and authenticated IPC deterministically refuses or times out. An endpoint that responds, authenticates incorrectly, returns malformed protocol data, or cannot be classified remains `DAEMON_ENDPOINT_UNVERIFIED`.
|
|
44
46
|
- The web server creates its supervisor after HTTP listen so the profile key uses the bound port, then warms it without awaiting Pi provider/model initialization. A first request arriving during that warmup shares the supervisor's `startPromise`. The bound profile key travels back over the `pichamber:ready` IPC message and into the CLI instance file; `pichamber logs` uses that key to include the matching private daemon log, while `--json` and `--quiet` serve output still carries only the port.
|
|
@@ -48,4 +50,15 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
|
|
|
48
50
|
|
|
49
51
|
This module defines the authenticated session API boundary consumed by the Pi-native session UI. Session leases coordinate PiChamber daemons only: the standalone `pi` CLI runs its own foreground runtime and does not honor these leases, so concurrently editing the same session through PiChamber and `pi` remains unsupported until Pi provides compatible upstream locking. Resource configuration and richer attachment extraction remain owned by their dedicated workstreams. The session event stream is SSE over the existing authenticated runtime transport; WebSocket callers fall back to it, preserving direct and relay behavior without a second daemon listener. The public route emits named heartbeat events so native `EventSource` clients can detect a silent foreground connection, reconnect, and resume from their last accepted sequence.
|
|
50
52
|
|
|
51
|
-
The Pi SDK is pinned exactly at `0.
|
|
53
|
+
The Pi SDK is pinned exactly at `0.85.1`. Any Pi 0.x minor upgrade requires a deliberate SDK/release-note review and repeat of this module's disposable-runtime smoke validation.
|
|
54
|
+
|
|
55
|
+
## SDK upgrade validation
|
|
56
|
+
|
|
57
|
+
The 0.84.1 → 0.85.1 upgrade retains the public session runtime/services API and v3 JSONL format. No PiChamber data migration or cache deletion is required. The SDK repairs a missing trailing newline when opening an existing session; subsequent entries remain separate JSONL records. Existing settings, custom model definitions, labels, and extension entries remain intact.
|
|
58
|
+
|
|
59
|
+
- `sdk-upgrade.test.js` exercises the installed SDK with disposable directories: cached OpenCode models, user model additions and overrides, forced HTTP refresh, ETag/304, failed refresh preserving the last catalog, restart restoration, and opening/appending a pre-upgrade v3 session.
|
|
60
|
+
- `session-daemon-extensions.e2e.test.js` exercises real extension loading, commands, dialogs, GUI projection, reload, and session disposal.
|
|
61
|
+
- `supervisor.test.js` covers authenticated replacement of a daemon from an older PiChamber build. Normal versioned releases must retain that replacement behavior. Same-version, same-path manual dependency replacement is not a release upgrade and requires stopping the old server/daemon before restarting.
|
|
62
|
+
- The SDK CLI bin moved to `dist/bundle/cli.js`; the detached daemon already resolves `package.json`'s `bin.pi` rather than hardcoding the old location.
|
|
63
|
+
|
|
64
|
+
The new bundled OpenCode catalog removes `deepseek-v4-flash-free`. SDK remote catalogs still merge additively with bundled models, so this upgrade fixes that stale entry, not general upstream deletion propagation. Explicit user-defined models with the same ID remain supported. Do not clear users' `models.json` or `models-store.json` to apply an upgrade.
|