@pi-chamber/web 0.7.2 → 0.8.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.
- package/README.md +1 -1
- package/dist/assets/{DiagramEditor-TeJ1G_NN.js → DiagramEditor-YPSKccgo.js} +1 -1
- package/dist/assets/DiagramView-C-PbBHce.js +1 -0
- package/dist/assets/DiffView-DfltyfN2.js +18 -0
- package/dist/assets/FilesView-BEjbLiK2.js +6 -0
- package/dist/assets/GitView-B_zTaXX4.js +8 -0
- package/dist/assets/JsonTreeView-9p4txyB_.js +1 -0
- package/dist/assets/MarkdownRendererImpl-CbRPLK2x.js +12 -0
- package/dist/assets/PatchDiff-rKjeUBRl.js +1 -0
- package/dist/assets/SessionSwitcherContent-C_VxKFJy.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-_k4P32o9.js +2 -0
- package/dist/assets/SessionUnreadDot-bT_0MixU.js +1 -0
- package/dist/assets/SettingsView-CqZ1ZAWG.js +2 -0
- package/dist/assets/SettingsWindow-C7vVE35-.js +1 -0
- package/dist/assets/ToolOutputDialog-GBbzATa6.js +8 -0
- package/dist/assets/ToolPartDiffPreview-Bdb9p5uS.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-sRc4lN0B.js → VirtualizedFileDiff-CA8hQyz9.js} +4 -4
- package/dist/assets/{Virtualizer-BxW2CJGB.js → Virtualizer-BSHVMKgK.js} +1 -1
- package/dist/assets/{appThemeRegistry-BK0dHKa6.js → appThemeRegistry-gegrE2dq.js} +1 -1
- package/dist/assets/collapsible-uwSKBy-K.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-9LNCLvAG.js +3 -0
- package/dist/assets/contextFileOpenGuard-CZSqdEHk.js +1 -0
- package/dist/assets/gitStatusPredicates-CRmbLl-x.js +134 -0
- package/dist/assets/index-BeJEipxi.js +1 -0
- package/dist/assets/index-CaP8oFLB.js +8 -0
- package/dist/assets/index-Dq8CnRYM.css +1 -0
- package/dist/assets/isDiffPlainText-YYyZNTdb.js +1 -0
- package/dist/assets/isFilePlainText-C70Z71bG.js +1 -0
- package/dist/assets/main-CsdVAKy_.js +135 -0
- package/dist/assets/main-GMQIZjuQ.js +2 -0
- package/dist/assets/{markdownCore-BfuFM7mg.js → markdownCore-BgVcDt0q.js} +2 -2
- package/dist/assets/miniChat-W6YsdiWR.js +2 -0
- package/dist/assets/mobile-BFR9CR5w.js +2 -0
- package/dist/assets/{permissionStore-BRcQ9Jgt.js → permissionStore-iKN1K2_x.js} +1 -1
- package/dist/assets/registerCustomTheme-DmolaWWZ.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-B8ZiW-3E.js +2 -0
- package/dist/assets/renderMobileApp-C5CdsYP6.js +11 -0
- package/dist/assets/runtimeEndpointReset-D3AZYuoF.js +54 -0
- package/dist/assets/{runtimeSurface-DF3VwUlO.js → runtimeSurface-B818u-_c.js} +1 -1
- package/dist/assets/themeResolver-yJ9XpNMI.js +1 -0
- package/dist/assets/{WindowsWindowControls-CCnU0ckO.js → useAppFontEffects-CYzYRbLp.js} +126 -499
- package/dist/assets/useFilesViewSearch-C--GWtn-.js +7 -0
- package/dist/assets/usePushVisibilityBeacon-D9lajdAc.js +10 -0
- package/dist/assets/useSwitcherItems-DOoi3x_8.js +1 -0
- package/dist/assets/vendor-base-ui-vkqQ2P9o.js +1 -0
- package/dist/assets/{vendor-beautiful-mermaid-r4GK_usS.js → vendor-beautiful-mermaid-DneUawHp.js} +1 -1
- package/dist/assets/{vendor-cmdk-BCEUzcHE.js → vendor-cmdk-zXx6sGnS.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-BS2SpSAZ.js → vendor-codemirror-autocomplete-wd6iRebq.js} +1 -1
- package/dist/assets/{vendor-codemirror-commands-RrgJ8H_6.js → vendor-codemirror-commands-DYppkHEk.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-ADhO_TUK.js → vendor-codemirror-lang-angular-DU_4KiiW.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-BGCWj7Om.js → vendor-codemirror-lang-cpp-CmIT9Z5_.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-Ba8JZ6fp.js → vendor-codemirror-lang-css-djiuoTi8.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-DyTiHXo4.js → vendor-codemirror-lang-go-COZSwZYW.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-DK27qQri.js → vendor-codemirror-lang-html-CKHqhW5R.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-CvFfnhPQ.js → vendor-codemirror-lang-java-CNMP5hyC.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-BUlYhQ3o.js → vendor-codemirror-lang-javascript-DuOEwJ3f.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-wBMtAEvT.js → vendor-codemirror-lang-jinja-DaKn_b1k.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-CqayksDf.js → vendor-codemirror-lang-json-CZ07HmNC.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-Ct3-H1PB.js → vendor-codemirror-lang-less-wJdQiDBf.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-XspREksq.js → vendor-codemirror-lang-liquid-0z48Roi8.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-CvO36Y1p.js → vendor-codemirror-lang-markdown-DtcZDGqe.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-BlUF9cCe.js → vendor-codemirror-lang-php-W8plS-JQ.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-_2bIYTiJ.js → vendor-codemirror-lang-python-DzzokVau.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-BdTYih_U.js → vendor-codemirror-lang-rust-C4ulBVpf.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-E6MhfOFk.js → vendor-codemirror-lang-sass-BkZJYEwS.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-B1BRhQSF.js → vendor-codemirror-lang-sql-HpQWHJjv.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-BYQJRa1Q.js → vendor-codemirror-lang-vue-DiBPljCc.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-D706yuyC.js → vendor-codemirror-lang-wast-DoABsogh.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml--MfWU6Dj.js → vendor-codemirror-lang-xml-BhLJhOCH.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-CRUFIbRX.js → vendor-codemirror-lang-yaml-D95i1Y5R.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-E2vgV9K3.js → vendor-codemirror-language-BByA_dGF.js} +2 -2
- package/dist/assets/{vendor-codemirror-language-data-C7_BPMCr.js → vendor-codemirror-language-data-DS_4W5G4.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-8kyQdB3f.js → vendor-codemirror-search-BV44140v.js} +1 -1
- package/dist/assets/{vendor-codemirror-view-DSzLbZiS.js → vendor-codemirror-view-Ct4T37Ue.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-accessibility-Cv52zwWT.js → vendor-dnd-kit-accessibility-DZKKhs9S.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-core-GipZW2tY.js → vendor-dnd-kit-core-CP8ck10N.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-sortable-Ct2QxIHb.js → vendor-dnd-kit-sortable-B-Icjoj4.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-utilities-CrOcp0Bp.js → vendor-dnd-kit-utilities-DTY1C6ST.js} +1 -1
- package/dist/assets/{vendor-elkjs-CRCLNXjf.js → vendor-elkjs-mzfkf0ML.js} +1 -1
- package/dist/assets/{vendor-floating-ui-dom-Bkw82kL9.js → vendor-floating-ui-dom-WyXykhNi.js} +1 -1
- package/dist/assets/{vendor-floating-ui-react-dom-sVFnuruh.js → vendor-floating-ui-react-dom-BZOGXAGe.js} +1 -1
- package/dist/assets/{vendor-framer-motion-DJASDzNt.js → vendor-framer-motion-BUygY0oN.js} +1 -1
- package/dist/assets/{vendor-heic2any-L8hyfc24.js → vendor-heic2any-BHsbokcA.js} +1 -1
- package/dist/assets/{vendor-lru_map-B-cPXHXW.js → vendor-lru_map-Cy8fTs3_.js} +1 -1
- package/dist/assets/{vendor-pierre-theming-C6Z4M5_u.js → vendor-pierre-theming-Dgp7B_O4.js} +1 -1
- package/dist/assets/{vendor-qrcode-COsmt6jn.js → vendor-qrcode-B0KNSajT.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-compose-refs-D1GnwnP9.js → vendor-radix-ui-react-compose-refs-8xy6TJML.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-context-CM4yFQ2I.js → vendor-radix-ui-react-context-CFsX-AUC.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-dialog-jX3Dld8c.js → vendor-radix-ui-react-dialog-D2yhEu2p.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js → vendor-radix-ui-react-dismissable-layer-DrorBNg9.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-focus-guards-D5MZ0nQs.js → vendor-radix-ui-react-focus-guards-BfdFmL7c.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-focus-scope-C2K7lNPv.js → vendor-radix-ui-react-focus-scope-D2BkImwt.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-id-BcxRjnbX.js → vendor-radix-ui-react-id-D2kS9K1j.js} +1 -1
- package/dist/assets/vendor-radix-ui-react-portal-YgCRIyi7.js +1 -0
- package/dist/assets/{vendor-radix-ui-react-presence-Btn-Dp7L.js → vendor-radix-ui-react-presence-D432pCMB.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-primitive-CfpW6_IT.js → vendor-radix-ui-react-primitive-DkH8dMOR.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-slot-BxUc3Pvz.js → vendor-radix-ui-react-slot-BIDFZX0-.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js → vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-use-controllable-state-C_ecoh35.js → vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js} +1 -1
- package/dist/assets/vendor-radix-ui-react-use-effect-event-D94va83M.js +1 -0
- package/dist/assets/{vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js → vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js} +1 -1
- package/dist/assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js +1 -0
- package/dist/assets/{vendor-react-DYyjh7Q0.js → vendor-react-B5Z1Mdn3.js} +1 -1
- package/dist/assets/{vendor-react-drawio-Boqanm0j.js → vendor-react-drawio-BYDptOsj.js} +1 -1
- package/dist/assets/{vendor-react-remove-scroll-bar-C9YRs2nU.js → vendor-react-remove-scroll-bar-CSAHp1YF.js} +1 -1
- package/dist/assets/{vendor-react-remove-scroll-CfeMe0DL.js → vendor-react-remove-scroll-vR1dy1aP.js} +1 -1
- package/dist/assets/{vendor-react-style-singleton-B1H4bWSG.js → vendor-react-style-singleton-Ctw6HnYx.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-BJY5fGLS.js → vendor-replit-codemirror-vim-CGHHNQxC.js} +1 -1
- package/dist/assets/{vendor-sonner-CW8w438f.js → vendor-sonner-BDtm25td.js} +1 -1
- package/dist/assets/{vendor-tanstack-react-virtual-IrbCBGJ4.js → vendor-tanstack-react-virtual-2skouoFw.js} +1 -1
- package/dist/assets/{vendor-use-callback-ref-CJB0R85I.js → vendor-use-callback-ref-CVVuCyLj.js} +1 -1
- package/dist/assets/{vendor-use-sidecar-C-AuTczP.js → vendor-use-sidecar-Vv4V8Nd1.js} +1 -1
- package/dist/assets/{vendor-use-sync-external-store-B7OScDIw.js → vendor-use-sync-external-store-D0AXkdQC.js} +1 -1
- package/dist/assets/{vendor-zustand-CnsBKjP5.js → vendor-zustand-GVb4H8HE.js} +1 -1
- package/dist/assets/{web-components-BYNCGylQ.js → web-components-C2cMNPqE.js} +2 -2
- package/dist/index.html +6 -6
- package/dist/mini-chat.html +5 -5
- package/dist/mobile.html +5 -5
- package/package.json +1 -1
- package/server/lib/git/DOCUMENTATION.md +3 -2
- package/server/lib/git/routes.js +27 -0
- package/server/lib/git/routes.test.js +41 -0
- package/server/lib/git/service.js +7 -1
- package/server/lib/git/service.test.js +23 -0
- package/server/lib/pi/routes.js +263 -6
- package/server/lib/pi/routes.test.js +314 -1
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +2 -2
- package/server/lib/pi/session-daemon/prompt-operations.test.js +318 -0
- package/server/lib/pi/session-daemon/session-daemon.js +309 -25
- package/server/lib/pi/session-daemon/session-daemon.test.js +137 -0
- package/server/lib/pi/session-daemon/supervisor.test.js +1 -1
- package/server/lib/pi/snippets-store.js +400 -0
- package/server/lib/pi/snippets-store.test.js +252 -0
- package/server/lib/relay/host-client.test.js +79 -15
- package/server/lib/server/cors.js +2 -0
- package/server/lib/server/cors.test.js +6 -5
- package/dist/assets/CommitSection-DfAlM30E.js +0 -1
- package/dist/assets/DiagramView-DKLIwNth.js +0 -1
- package/dist/assets/DiffView-CZyqSs5W.js +0 -18
- package/dist/assets/FilesView-rftA7fEL.js +0 -14
- package/dist/assets/GitView-D5LMTT2M.js +0 -6
- package/dist/assets/JsonTreeView-DMI3-Smy.js +0 -1
- package/dist/assets/MarkdownRendererImpl-gdd-5n9J.js +0 -12
- package/dist/assets/PatchDiff-GNB1NlAN.js +0 -1
- package/dist/assets/PierreDiffViewer-DmJv2AoJ.js +0 -136
- package/dist/assets/SessionSwitcherContent-CWdDPll7.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-Cx-Jfmvo.js +0 -2
- package/dist/assets/SessionUnreadDot-CKe4uVcf.js +0 -1
- package/dist/assets/SettingsView-DaxkNy5C.js +0 -4
- package/dist/assets/SettingsWindow-D1M_rRDo.js +0 -1
- package/dist/assets/ToolOutputDialog-CUKcp77A.js +0 -15
- package/dist/assets/ToolPartDiffPreview-CkzwXAC5.js +0 -8
- package/dist/assets/collapsible-B0cIItyf.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-B1uVA58l.js +0 -3
- package/dist/assets/contextFileOpenGuard-BuedQ5EQ.js +0 -1
- package/dist/assets/index-BA67uOfZ.js +0 -1
- package/dist/assets/index-CcbDTf8Q.js +0 -8
- package/dist/assets/index-Cl3XbCeC.css +0 -1
- package/dist/assets/isDiffPlainText-DLDFLL6P.js +0 -1
- package/dist/assets/isFilePlainText-B2wwrpRU.js +0 -1
- package/dist/assets/main-B5k0qpHJ.js +0 -133
- package/dist/assets/main-Bepu8Jr9.js +0 -2
- package/dist/assets/miniChat-Co0Snpgl.js +0 -2
- package/dist/assets/mobile-CSvL_Zyu.js +0 -2
- package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-DrMJ1RXX.js +0 -2
- package/dist/assets/renderMobileApp-B2toAnMW.js +0 -14
- package/dist/assets/themeResolver-BmJyTmjJ.js +0 -1
- package/dist/assets/useInlineCommentController-CxMP78jg.js +0 -2
- package/dist/assets/usePanelSlide-DUuoQt5X.js +0 -56
- package/dist/assets/usePushVisibilityBeacon-CSPdFBaA.js +0 -10
- package/dist/assets/useSwitcherItems-zOeC2Cta.js +0 -1
- package/dist/assets/vendor-base-ui-DL8r2fgQ.js +0 -1
- package/dist/assets/vendor-radix-ui-react-portal-xlJWBfDg.js +0 -1
- package/dist/assets/vendor-radix-ui-react-use-effect-event-DkJl_Rn_.js +0 -1
- package/dist/assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js +0 -1
- package/dist/assets/vendor-remixicon-react-CzPq62YO.js +0 -1
- /package/dist/assets/{usePanelSlide-BV3KOtdA.css → runtimeEndpointReset-BV3KOtdA.css} +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { createServer } from 'node:net';
|
|
3
|
-
import { chmod, mkdir, lstat, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { chmod, link, mkdir, lstat, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
4
4
|
import { createReadStream, existsSync, readFileSync } from 'node:fs';
|
|
5
5
|
import { homedir } from 'node:os';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { createInterface } from 'node:readline';
|
|
8
|
-
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
8
|
+
import { basename, dirname, isAbsolute, join, relative } from 'node:path';
|
|
9
9
|
import { hasTrustRequiringProjectResources } from '@earendil-works/pi-coding-agent';
|
|
10
10
|
import { StringDecoder } from 'node:string_decoder';
|
|
11
11
|
import {
|
|
@@ -205,6 +205,28 @@ export function createSessionDaemon({
|
|
|
205
205
|
const activeRunStartedAt = new Map();
|
|
206
206
|
const sendGenerationBySession = new Map();
|
|
207
207
|
const settledSendGenerationBySession = new Map();
|
|
208
|
+
// Pi emits each user message start before its persisted entry is readable.
|
|
209
|
+
// Keep prompt metadata in send order so queued follow-ups cannot attach the
|
|
210
|
+
// next prompt's files to an earlier user message.
|
|
211
|
+
const pendingUserStartsBySession = new Map();
|
|
212
|
+
const enqueueUserStart = (sessionId, generation, files) => {
|
|
213
|
+
const pending = pendingUserStartsBySession.get(sessionId) ?? [];
|
|
214
|
+
pending.push({ generation, files });
|
|
215
|
+
pendingUserStartsBySession.set(sessionId, pending);
|
|
216
|
+
};
|
|
217
|
+
const takeUserStart = (sessionId) => {
|
|
218
|
+
const pending = pendingUserStartsBySession.get(sessionId);
|
|
219
|
+
const next = pending?.shift();
|
|
220
|
+
if (!pending?.length) pendingUserStartsBySession.delete(sessionId);
|
|
221
|
+
return next;
|
|
222
|
+
};
|
|
223
|
+
const removeUserStart = (sessionId, generation) => {
|
|
224
|
+
const pending = pendingUserStartsBySession.get(sessionId);
|
|
225
|
+
if (!pending) return;
|
|
226
|
+
const remaining = pending.filter((entry) => entry.generation !== generation);
|
|
227
|
+
if (remaining.length > 0) pendingUserStartsBySession.set(sessionId, remaining);
|
|
228
|
+
else pendingUserStartsBySession.delete(sessionId);
|
|
229
|
+
};
|
|
208
230
|
const shutdownRequestedBySession = new Set();
|
|
209
231
|
const disposingSessionIds = new Set();
|
|
210
232
|
const streamingRedactionBuffers = new Map();
|
|
@@ -922,13 +944,48 @@ export function createSessionDaemon({
|
|
|
922
944
|
const timestamp = Date.parse(entry.timestamp);
|
|
923
945
|
const createdAt = Number.isFinite(timestamp) ? timestamp : 0;
|
|
924
946
|
if (entry.message.role === 'user') {
|
|
925
|
-
const
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
947
|
+
const userParts = [];
|
|
948
|
+
let rawText = '';
|
|
949
|
+
if (typeof entry.message.content === 'string') {
|
|
950
|
+
rawText = entry.message.content;
|
|
951
|
+
} else if (Array.isArray(entry.message.content)) {
|
|
952
|
+
for (let index = 0; index < entry.message.content.length; index += 1) {
|
|
953
|
+
const part = entry.message.content[index];
|
|
954
|
+
if (part?.type === 'text') {
|
|
955
|
+
rawText += (rawText ? '\n\n' : '') + (part.text || '');
|
|
956
|
+
} else if (part?.type === 'image' && typeof part.data === 'string') {
|
|
957
|
+
const mime = part.mimeType || 'image/png';
|
|
958
|
+
userParts.push({
|
|
959
|
+
type: 'file',
|
|
960
|
+
id: `${entry.id}:image:${index}`,
|
|
961
|
+
index,
|
|
962
|
+
mime,
|
|
963
|
+
url: `data:${mime};base64,${part.data}`,
|
|
964
|
+
filename: 'image.png',
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
const attachmentNamedRegex = /\[Attachment\s+(.+?)\s+is available at\s+([^\]]+)\]/gi;
|
|
971
|
+
let match;
|
|
972
|
+
while ((match = attachmentNamedRegex.exec(rawText)) !== null) {
|
|
973
|
+
const filename = match[1].trim();
|
|
974
|
+
userParts.push({
|
|
975
|
+
type: 'file',
|
|
976
|
+
id: `${entry.id}:attachment:${userParts.length}`,
|
|
977
|
+
index: userParts.length,
|
|
978
|
+
filename,
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
let text = rawText.replace(/(\r?\n)*\s*\[Attachment\s+.+?\s+is available at\s+[^\]]+\]/gi, '');
|
|
983
|
+
text = redactAttachmentPaths(text).trim();
|
|
930
984
|
latestUserMessageId = entry.id;
|
|
931
|
-
return [{
|
|
985
|
+
return [{
|
|
986
|
+
message: { id: entry.id, sessionId: session.sessionId, directory: targetDir, role: 'user', text, createdAt },
|
|
987
|
+
parts: userParts,
|
|
988
|
+
}];
|
|
932
989
|
}
|
|
933
990
|
if (entry.message.role !== 'assistant' || !Array.isArray(entry.message.content)) return [];
|
|
934
991
|
const text = redactAttachmentPaths(textFromContent(entry.message.content));
|
|
@@ -1492,6 +1549,11 @@ export function createSessionDaemon({
|
|
|
1492
1549
|
|
|
1493
1550
|
const resourceId = (kind, filePath) => `${kind}:${createHash('sha256').update(filePath).digest('base64url')}`;
|
|
1494
1551
|
|
|
1552
|
+
const isPathInside = (parent, candidate) => {
|
|
1553
|
+
const child = relative(parent, candidate);
|
|
1554
|
+
return child.length > 0 && !child.startsWith('..') && !isAbsolute(child);
|
|
1555
|
+
};
|
|
1556
|
+
|
|
1495
1557
|
const resourceLocation = (sourceInfo) => {
|
|
1496
1558
|
if (sourceInfo?.scope === 'project') return 'project';
|
|
1497
1559
|
if (sourceInfo?.origin === 'package') return 'package';
|
|
@@ -1553,6 +1615,13 @@ export function createSessionDaemon({
|
|
|
1553
1615
|
if (runtime?.session?.isStreaming) throw new SessionDaemonProtocolError('SESSION_BUSY', 'Resources cannot change during an active session.');
|
|
1554
1616
|
};
|
|
1555
1617
|
|
|
1618
|
+
let resourceMutation = Promise.resolve();
|
|
1619
|
+
const transactResourceMutation = (operation) => {
|
|
1620
|
+
const pending = resourceMutation.then(operation);
|
|
1621
|
+
resourceMutation = pending.catch(() => {});
|
|
1622
|
+
return pending;
|
|
1623
|
+
};
|
|
1624
|
+
|
|
1556
1625
|
const writeResourceFile = async (filePath, content) => {
|
|
1557
1626
|
const temporary = `${filePath}.${randomUUID()}.tmp`;
|
|
1558
1627
|
await mkdir(dirname(filePath), { recursive: true, mode: 0o700 });
|
|
@@ -1565,6 +1634,22 @@ export function createSessionDaemon({
|
|
|
1565
1634
|
}
|
|
1566
1635
|
};
|
|
1567
1636
|
|
|
1637
|
+
const writeNewResourceFile = async (filePath, content) => {
|
|
1638
|
+
const temporary = `${filePath}.${randomUUID()}.tmp`;
|
|
1639
|
+
await mkdir(dirname(filePath), { recursive: true, mode: 0o700 });
|
|
1640
|
+
try {
|
|
1641
|
+
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 });
|
|
1642
|
+
await link(temporary, filePath);
|
|
1643
|
+
} catch (error) {
|
|
1644
|
+
await rm(temporary, { force: true }).catch(() => {});
|
|
1645
|
+
if (error?.code === 'EEXIST') {
|
|
1646
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template already exists.');
|
|
1647
|
+
}
|
|
1648
|
+
throw error;
|
|
1649
|
+
}
|
|
1650
|
+
await rm(temporary, { force: true }).catch(() => {});
|
|
1651
|
+
};
|
|
1652
|
+
|
|
1568
1653
|
const refreshResources = async (targetDir) => {
|
|
1569
1654
|
servicesCache.delete(targetDir || activeDirectory || cwd);
|
|
1570
1655
|
if (runtime) {
|
|
@@ -1593,13 +1678,16 @@ export function createSessionDaemon({
|
|
|
1593
1678
|
return refreshResources(targetDir);
|
|
1594
1679
|
};
|
|
1595
1680
|
|
|
1596
|
-
const createPrompt = async (
|
|
1681
|
+
const createPrompt = (payload) => transactResourceMutation(async () => {
|
|
1597
1682
|
if (!payload || !['global', 'project'].includes(payload.location) || typeof payload.name !== 'string' || typeof payload.content !== 'string'
|
|
1598
1683
|
|| typeof payload.description !== 'string' || payload.content.length > 200_000 || payload.description.length > 4_000
|
|
1599
1684
|
|| !/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(payload.name)) {
|
|
1600
1685
|
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template is invalid.');
|
|
1601
1686
|
}
|
|
1602
1687
|
requireIdleResourceMutation();
|
|
1688
|
+
if (payload.location === 'project' && !payload.directory) {
|
|
1689
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'Project prompt templates require an explicit directory.');
|
|
1690
|
+
}
|
|
1603
1691
|
const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
|
|
1604
1692
|
const trust = createTrustStore(agentDir).get(targetDir);
|
|
1605
1693
|
if (payload.location === 'project' && trust !== true) throw new SessionDaemonProtocolError('PROJECT_UNTRUSTED', 'The project is not trusted.');
|
|
@@ -1610,21 +1698,152 @@ export function createSessionDaemon({
|
|
|
1610
1698
|
} catch (error) {
|
|
1611
1699
|
if (error?.code !== 'ENOENT') throw error;
|
|
1612
1700
|
}
|
|
1613
|
-
await
|
|
1701
|
+
await writeNewResourceFile(filePath, `---\ndescription: ${JSON.stringify(payload.description)}\n---\n${payload.content}`);
|
|
1614
1702
|
return refreshResources(targetDir);
|
|
1615
|
-
};
|
|
1703
|
+
});
|
|
1616
1704
|
|
|
1617
|
-
const deletePrompt = async (
|
|
1705
|
+
const deletePrompt = (payload) => transactResourceMutation(async () => {
|
|
1618
1706
|
if (!payload || typeof payload.resourceId !== 'string') throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template is invalid.');
|
|
1619
1707
|
requireIdleResourceMutation();
|
|
1620
1708
|
const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
|
|
1621
1709
|
const catalog = await resourceCatalog(targetDir);
|
|
1622
1710
|
const resource = catalog.prompts.find((item) => item.id === payload.resourceId && item.editable === true);
|
|
1623
1711
|
if (!resource?.filePath) throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi prompt template is not editable.');
|
|
1712
|
+
const expectedDeletePrefix =
|
|
1713
|
+
resource.location === 'global'
|
|
1714
|
+
? join(agentDir, 'prompts')
|
|
1715
|
+
: join(targetDir, '.pi', 'prompts');
|
|
1716
|
+
if (typeof resource.filePath !== 'string' || !isPathInside(expectedDeletePrefix, resource.filePath)) {
|
|
1717
|
+
throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi prompt template is not editable.');
|
|
1718
|
+
}
|
|
1719
|
+
if (resource.location === 'project') {
|
|
1720
|
+
if (!payload.directory) throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'Project prompt templates require an explicit directory.');
|
|
1721
|
+
const trust = createTrustStore(agentDir).get(targetDir);
|
|
1722
|
+
if (trust !== true) throw new SessionDaemonProtocolError('PROJECT_UNTRUSTED', 'The project is not trusted.');
|
|
1723
|
+
}
|
|
1624
1724
|
await rm(resource.filePath);
|
|
1625
1725
|
return refreshResources(targetDir);
|
|
1726
|
+
});
|
|
1727
|
+
|
|
1728
|
+
const PROMPT_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
|
|
1729
|
+
|
|
1730
|
+
const splitPromptFile = (raw) => {
|
|
1731
|
+
const match = typeof raw === 'string' ? raw.match(/^(---\r?\n[\s\S]*?\r?\n---\r?\n?)/) : null;
|
|
1732
|
+
if (match) {
|
|
1733
|
+
return { frontmatter: match[1], body: raw.slice(match[1].length) };
|
|
1734
|
+
}
|
|
1735
|
+
return { frontmatter: '', body: typeof raw === 'string' ? raw : '' };
|
|
1736
|
+
};
|
|
1737
|
+
|
|
1738
|
+
const withUpdatedDescription = (frontmatter, description) => {
|
|
1739
|
+
if (description === undefined) return frontmatter;
|
|
1740
|
+
const serialized = `description: ${JSON.stringify(description)}`;
|
|
1741
|
+
if (!frontmatter) {
|
|
1742
|
+
return `---\n${serialized}\n---\n`;
|
|
1743
|
+
}
|
|
1744
|
+
const lines = frontmatter.split(/\r?\n/);
|
|
1745
|
+
let replaced = false;
|
|
1746
|
+
const nextLines = lines.map((line) => {
|
|
1747
|
+
if (!replaced && /^description\s*:/.test(line)) {
|
|
1748
|
+
replaced = true;
|
|
1749
|
+
return serialized;
|
|
1750
|
+
}
|
|
1751
|
+
return line;
|
|
1752
|
+
});
|
|
1753
|
+
if (!replaced) {
|
|
1754
|
+
const closingIndex = nextLines.lastIndexOf('---');
|
|
1755
|
+
const insertAt = closingIndex > 0 ? closingIndex : 1;
|
|
1756
|
+
nextLines.splice(insertAt, 0, serialized);
|
|
1757
|
+
}
|
|
1758
|
+
return nextLines.join('\n');
|
|
1626
1759
|
};
|
|
1627
1760
|
|
|
1761
|
+
const updatePrompt = (payload) => transactResourceMutation(async () => {
|
|
1762
|
+
if (!payload || typeof payload.resourceId !== 'string') {
|
|
1763
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template update is invalid.');
|
|
1764
|
+
}
|
|
1765
|
+
const hasName = payload.name !== undefined;
|
|
1766
|
+
const hasDescription = payload.description !== undefined;
|
|
1767
|
+
const hasContent = payload.content !== undefined;
|
|
1768
|
+
const hasLocation = payload.location !== undefined;
|
|
1769
|
+
if (!hasName && !hasDescription && !hasContent && !hasLocation) {
|
|
1770
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template update is invalid.');
|
|
1771
|
+
}
|
|
1772
|
+
if (hasName && (typeof payload.name !== 'string' || !PROMPT_NAME_PATTERN.test(payload.name))) {
|
|
1773
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template name is invalid.');
|
|
1774
|
+
}
|
|
1775
|
+
if (hasDescription && (typeof payload.description !== 'string' || payload.description.length > 4_000)) {
|
|
1776
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template description is invalid.');
|
|
1777
|
+
}
|
|
1778
|
+
if (hasContent && (typeof payload.content !== 'string' || payload.content.length > 200_000)) {
|
|
1779
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template content is invalid.');
|
|
1780
|
+
}
|
|
1781
|
+
if (hasLocation && payload.location !== 'global' && payload.location !== 'project') {
|
|
1782
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template location is invalid.');
|
|
1783
|
+
}
|
|
1784
|
+
requireIdleResourceMutation();
|
|
1785
|
+
const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
|
|
1786
|
+
const catalog = await resourceCatalog(targetDir);
|
|
1787
|
+
const resource = catalog.prompts.find((item) => item.id === payload.resourceId && item.editable === true);
|
|
1788
|
+
if (!resource?.filePath) throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi prompt template is not editable.');
|
|
1789
|
+
const sourceLocation = resource.location;
|
|
1790
|
+
const expectedPrefix =
|
|
1791
|
+
sourceLocation === 'global'
|
|
1792
|
+
? join(agentDir, 'prompts')
|
|
1793
|
+
: join(targetDir, '.pi', 'prompts');
|
|
1794
|
+
const normalizedFilePath = resource.filePath;
|
|
1795
|
+
if (typeof normalizedFilePath !== 'string' || !isPathInside(expectedPrefix, normalizedFilePath)) {
|
|
1796
|
+
throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi prompt template is not editable.');
|
|
1797
|
+
}
|
|
1798
|
+
const destLocation = hasLocation ? payload.location : sourceLocation;
|
|
1799
|
+
if (destLocation !== 'global' && destLocation !== 'project') {
|
|
1800
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template location is invalid.');
|
|
1801
|
+
}
|
|
1802
|
+
const destName = hasName ? payload.name : resource.name;
|
|
1803
|
+
const isRename = destName !== resource.name;
|
|
1804
|
+
const isLocationMove = destLocation !== sourceLocation;
|
|
1805
|
+
const needsNewFile = isRename || isLocationMove;
|
|
1806
|
+
if (destLocation === 'project' || sourceLocation === 'project') {
|
|
1807
|
+
if (!payload.directory) throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'Project prompt templates require an explicit directory.');
|
|
1808
|
+
const trust = createTrustStore(agentDir).get(targetDir);
|
|
1809
|
+
if (trust !== true) throw new SessionDaemonProtocolError('PROJECT_UNTRUSTED', 'The project is not trusted.');
|
|
1810
|
+
}
|
|
1811
|
+
const previousRaw = await readFile(resource.filePath, 'utf8').catch((error) => {
|
|
1812
|
+
if (error?.code === 'ENOENT') throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi prompt template is not editable.');
|
|
1813
|
+
throw error;
|
|
1814
|
+
});
|
|
1815
|
+
const { frontmatter, body } = splitPromptFile(previousRaw);
|
|
1816
|
+
const nextFrontmatter = withUpdatedDescription(frontmatter, hasDescription ? payload.description : undefined);
|
|
1817
|
+
const nextBody = hasContent ? payload.content : body;
|
|
1818
|
+
const nextFileContent = `${nextFrontmatter}${nextBody}`;
|
|
1819
|
+
if (!needsNewFile) {
|
|
1820
|
+
await writeResourceFile(resource.filePath, nextFileContent);
|
|
1821
|
+
return refreshResources(targetDir);
|
|
1822
|
+
}
|
|
1823
|
+
if (!PROMPT_NAME_PATTERN.test(destName)) {
|
|
1824
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template name is invalid.');
|
|
1825
|
+
}
|
|
1826
|
+
const destPath = join(destLocation === 'global' ? agentDir : join(targetDir, '.pi'), 'prompts', `${destName}.md`);
|
|
1827
|
+
if (destPath === resource.filePath) {
|
|
1828
|
+
await writeResourceFile(resource.filePath, nextFileContent);
|
|
1829
|
+
return refreshResources(targetDir);
|
|
1830
|
+
}
|
|
1831
|
+
try {
|
|
1832
|
+
await readFile(destPath, 'utf8');
|
|
1833
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template already exists.');
|
|
1834
|
+
} catch (error) {
|
|
1835
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
1836
|
+
}
|
|
1837
|
+
await writeNewResourceFile(destPath, nextFileContent);
|
|
1838
|
+
try {
|
|
1839
|
+
await rm(resource.filePath);
|
|
1840
|
+
} catch (error) {
|
|
1841
|
+
await rm(destPath, { force: true }).catch(() => {});
|
|
1842
|
+
throw error;
|
|
1843
|
+
}
|
|
1844
|
+
return refreshResources(targetDir);
|
|
1845
|
+
});
|
|
1846
|
+
|
|
1628
1847
|
const setSessionModel = async (activeRuntime, model) => {
|
|
1629
1848
|
if (!model || typeof model.providerId !== 'string' || typeof model.modelId !== 'string') {
|
|
1630
1849
|
throw new SessionDaemonProtocolError('INVALID_MODEL', 'The requested Pi model is invalid.');
|
|
@@ -1868,15 +2087,17 @@ export function createSessionDaemon({
|
|
|
1868
2087
|
};
|
|
1869
2088
|
|
|
1870
2089
|
const prepareAttachmentContent = async (attachments) => {
|
|
1871
|
-
if (attachments === undefined) return { text: '', images: [] };
|
|
2090
|
+
if (attachments === undefined) return { text: '', images: [], files: [] };
|
|
1872
2091
|
if (!Array.isArray(attachments) || attachments.length > 32) throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session attachments are invalid.');
|
|
1873
2092
|
const text = [];
|
|
1874
2093
|
const images = [];
|
|
2094
|
+
const files = [];
|
|
1875
2095
|
for (const attachment of attachments) {
|
|
1876
2096
|
if (!attachment || typeof attachment.path !== 'string' || typeof attachment.name !== 'string'
|
|
1877
2097
|
|| typeof attachment.mime !== 'string' || !Number.isSafeInteger(attachment.size) || attachment.size <= 0) {
|
|
1878
2098
|
throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session attachments are invalid.');
|
|
1879
2099
|
}
|
|
2100
|
+
files.push({ mime: attachment.mime, filename: attachment.name });
|
|
1880
2101
|
try {
|
|
1881
2102
|
if (attachment.mime.startsWith('image/') && attachment.size <= 20 * 1024 * 1024) {
|
|
1882
2103
|
const data = await readFile(attachment.path);
|
|
@@ -1892,7 +2113,7 @@ export function createSessionDaemon({
|
|
|
1892
2113
|
throw err;
|
|
1893
2114
|
}
|
|
1894
2115
|
}
|
|
1895
|
-
return { text: text.join('\n'), images };
|
|
2116
|
+
return { text: text.join('\n'), images, files };
|
|
1896
2117
|
};
|
|
1897
2118
|
|
|
1898
2119
|
const sessionInput = async (payload, delivery) => {
|
|
@@ -1916,9 +2137,26 @@ export function createSessionDaemon({
|
|
|
1916
2137
|
applyThinking(activeRuntime, payload.thinking, payload.sessionId, activeRuntime.cwd);
|
|
1917
2138
|
}
|
|
1918
2139
|
|
|
1919
|
-
//
|
|
2140
|
+
// Extension commands can configure an otherwise empty session. They are
|
|
2141
|
+
// not conversation prompts, so leave the session unnamed until the first
|
|
2142
|
+
// input that actually enters the transcript. Resolve this from Pi's live
|
|
2143
|
+
// registered-command catalog rather than trusting a browser hint.
|
|
1920
2144
|
const manager = activeRuntime.session?.sessionManager;
|
|
1921
|
-
|
|
2145
|
+
const slashInvocation = typeof payload.text === 'string'
|
|
2146
|
+
? /^\/([^\s]+)/.exec(payload.text.trim())?.[1]
|
|
2147
|
+
: undefined;
|
|
2148
|
+
const registeredExtensionCommands = typeof activeRuntime.session?.extensionRunner?.getRegisteredCommands === 'function'
|
|
2149
|
+
? activeRuntime.session.extensionRunner.getRegisteredCommands()
|
|
2150
|
+
: [];
|
|
2151
|
+
const isExtensionCommand = Boolean(
|
|
2152
|
+
slashInvocation
|
|
2153
|
+
&& Array.isArray(registeredExtensionCommands)
|
|
2154
|
+
&& registeredExtensionCommands.some((command) => typeof command?.invocationName === 'string'
|
|
2155
|
+
&& command.invocationName.toLowerCase() === slashInvocation.toLowerCase()),
|
|
2156
|
+
);
|
|
2157
|
+
// Auto-assign deterministic title on the first conversation prompt if the
|
|
2158
|
+
// session manager still has no explicit or extension-owned name.
|
|
2159
|
+
if (!isExtensionCommand && typeof payload.text === 'string' && payload.text.trim().length > 0 && !manager?.getSessionName?.()) {
|
|
1922
2160
|
const derived = deriveSessionTitle(payload.text);
|
|
1923
2161
|
if (derived && typeof manager?.appendSessionInfo === 'function') {
|
|
1924
2162
|
manager.appendSessionInfo(derived);
|
|
@@ -1943,15 +2181,40 @@ export function createSessionDaemon({
|
|
|
1943
2181
|
// Slash-prefixed input dispatches extension commands and skill/template
|
|
1944
2182
|
// expansion exactly like the pi CLI and RPC modes; plain text keeps the
|
|
1945
2183
|
// sendUserMessage path so it is never expanded.
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
2184
|
+
enqueueUserStart(payload.sessionId, generation, attachments.files);
|
|
2185
|
+
// Pi's `session.setModel()` notifies extensions (`model_select`) but not
|
|
2186
|
+
// session subscribers, so an extension-driven model switch would otherwise
|
|
2187
|
+
// never publish `session.model`. Snapshot the live model to reconcile
|
|
2188
|
+
// below from authoritative runtime state. Thinking does emit
|
|
2189
|
+
// `thinking_level_changed` to subscribers, so it needs no reconciliation.
|
|
2190
|
+
const prevModel = activeRuntime.session?.model
|
|
2191
|
+
? { provider: activeRuntime.session.model.provider, id: activeRuntime.session.model.id }
|
|
2192
|
+
: null;
|
|
2193
|
+
let sendCall;
|
|
2194
|
+
try {
|
|
2195
|
+
sendCall = typeof content === 'string' && content.startsWith('/')
|
|
2196
|
+
? activeRuntime.session.prompt(content, {
|
|
2197
|
+
source: 'rpc',
|
|
2198
|
+
...(deliverAs ? { streamingBehavior: deliverAs } : {}),
|
|
2199
|
+
})
|
|
2200
|
+
: activeRuntime.session.sendUserMessage(content, deliverAs ? { deliverAs } : undefined);
|
|
2201
|
+
} catch (error) {
|
|
2202
|
+
removeUserStart(payload.sessionId, generation);
|
|
2203
|
+
throw error;
|
|
2204
|
+
}
|
|
1952
2205
|
Promise.resolve(sendCall).then(() => {
|
|
2206
|
+
removeUserStart(payload.sessionId, generation);
|
|
1953
2207
|
if (sendGenerationBySession.get(payload.sessionId) !== generation) return;
|
|
1954
2208
|
if (settledSendGenerationBySession.get(payload.sessionId) === generation) return;
|
|
2209
|
+
const curModel = activeRuntime.session?.model;
|
|
2210
|
+
if (
|
|
2211
|
+
curModel?.provider && curModel?.id
|
|
2212
|
+
&& (curModel.provider !== prevModel?.provider || curModel.id !== prevModel?.id)
|
|
2213
|
+
) {
|
|
2214
|
+
publish('session.model', {
|
|
2215
|
+
model: { providerId: curModel.provider, modelId: curModel.id },
|
|
2216
|
+
}, payload.sessionId, activeRuntime.cwd);
|
|
2217
|
+
}
|
|
1955
2218
|
if (activeRuntime.session?.isStreaming) return;
|
|
1956
2219
|
settledSendGenerationBySession.set(payload.sessionId, generation);
|
|
1957
2220
|
// Extension commands can complete without starting an agent turn, so Pi
|
|
@@ -1960,6 +2223,7 @@ export function createSessionDaemon({
|
|
|
1960
2223
|
publish('session.lifecycle', { state: 'idle', serverNow: Date.now() }, payload.sessionId, activeRuntime.cwd);
|
|
1961
2224
|
completeRequestedShutdown(payload.sessionId);
|
|
1962
2225
|
}).catch((error) => {
|
|
2226
|
+
removeUserStart(payload.sessionId, generation);
|
|
1963
2227
|
if (sendGenerationBySession.get(payload.sessionId) !== generation) return;
|
|
1964
2228
|
publish('session.error', {
|
|
1965
2229
|
code: 'ASSISTANT_ERROR',
|
|
@@ -2015,6 +2279,7 @@ export function createSessionDaemon({
|
|
|
2015
2279
|
shutdownRequestedBySession.delete(sessionId);
|
|
2016
2280
|
sendGenerationBySession.delete(sessionId);
|
|
2017
2281
|
settledSendGenerationBySession.delete(sessionId);
|
|
2282
|
+
pendingUserStartsBySession.delete(sessionId);
|
|
2018
2283
|
latestUserMessageIds.delete(sessionId);
|
|
2019
2284
|
latestAssistantMessageIds.delete(sessionId);
|
|
2020
2285
|
toolInputBySession.delete(sessionId);
|
|
@@ -2026,11 +2291,15 @@ export function createSessionDaemon({
|
|
|
2026
2291
|
case 'message_start': {
|
|
2027
2292
|
if (event.message?.role === 'user') {
|
|
2028
2293
|
const content = event.message.content;
|
|
2029
|
-
const
|
|
2294
|
+
const rawText = typeof content === 'string'
|
|
2030
2295
|
? content
|
|
2031
2296
|
: Array.isArray(content)
|
|
2032
2297
|
? textFromContent(content)
|
|
2033
|
-
: ''
|
|
2298
|
+
: '';
|
|
2299
|
+
const text = redactAttachmentPaths(
|
|
2300
|
+
rawText.replace(/(\r?\n)*\s*\[Attachment\s+.+?\s+is available at\s+[^\]]+\]/gi, ''),
|
|
2301
|
+
).trim();
|
|
2302
|
+
const files = takeUserStart(sessionId)?.files ?? [];
|
|
2034
2303
|
const messageId = `user-${sessionId}-${sequence + 1}`;
|
|
2035
2304
|
messageEntryAliases.retain({ cwd: directory, sessionId, syntheticMessageId: messageId, message: event.message });
|
|
2036
2305
|
latestUserMessageIds.set(sessionId, messageId);
|
|
@@ -2038,6 +2307,15 @@ export function createSessionDaemon({
|
|
|
2038
2307
|
messageId,
|
|
2039
2308
|
role: 'user',
|
|
2040
2309
|
text,
|
|
2310
|
+
...(files.length > 0 ? {
|
|
2311
|
+
files: files.map((file, index) => ({
|
|
2312
|
+
type: 'file',
|
|
2313
|
+
id: `${messageId}:file:${index}`,
|
|
2314
|
+
index,
|
|
2315
|
+
mime: file.mime,
|
|
2316
|
+
filename: file.filename,
|
|
2317
|
+
})),
|
|
2318
|
+
} : {}),
|
|
2041
2319
|
startedAt: Number.isFinite(event.message.timestamp) ? event.message.timestamp : Date.now(),
|
|
2042
2320
|
}, sessionId, directory);
|
|
2043
2321
|
} else if (event.message?.role === 'assistant') {
|
|
@@ -2332,7 +2610,7 @@ export function createSessionDaemon({
|
|
|
2332
2610
|
'sessions.steer', 'sessions.followUp', 'sessions.abort', 'sessions.setModel',
|
|
2333
2611
|
'sessions.setThinking', 'sessions.compact', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.status', 'providers.login',
|
|
2334
2612
|
'providers.login.respond', 'providers.login.status', 'providers.logout', 'settings.get', 'settings.set',
|
|
2335
|
-
'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.delete',
|
|
2613
|
+
'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.update', 'resources.prompts.delete',
|
|
2336
2614
|
'extensions.list', 'extensions.respond',
|
|
2337
2615
|
],
|
|
2338
2616
|
...(Number.isInteger(healthMetadata.daemonPid) ? { daemonPid: healthMetadata.daemonPid } : {}),
|
|
@@ -2432,6 +2710,11 @@ export function createSessionDaemon({
|
|
|
2432
2710
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
|
|
2433
2711
|
return;
|
|
2434
2712
|
}
|
|
2713
|
+
case 'resources.prompts.update': {
|
|
2714
|
+
const result = await updatePrompt(message.payload);
|
|
2715
|
+
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
|
|
2716
|
+
return;
|
|
2717
|
+
}
|
|
2435
2718
|
case 'resources.prompts.delete': {
|
|
2436
2719
|
const result = await deletePrompt(message.payload);
|
|
2437
2720
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
|
|
@@ -2754,6 +3037,7 @@ export function createSessionDaemon({
|
|
|
2754
3037
|
disposingSessionIds.clear();
|
|
2755
3038
|
sendGenerationBySession.clear();
|
|
2756
3039
|
settledSendGenerationBySession.clear();
|
|
3040
|
+
pendingUserStartsBySession.clear();
|
|
2757
3041
|
latestUserMessageIds.clear();
|
|
2758
3042
|
latestAssistantMessageIds.clear();
|
|
2759
3043
|
for (const client of clients) client.destroy();
|
|
@@ -702,6 +702,37 @@ describe('Pi session daemon spike', () => {
|
|
|
702
702
|
await client.close();
|
|
703
703
|
});
|
|
704
704
|
|
|
705
|
+
it('leaves an extension-only session unnamed until its first conversation prompt', async () => {
|
|
706
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-extension-title-'));
|
|
707
|
+
const endpoint = testDaemonEndpoint(root);
|
|
708
|
+
const runtime = new FakeRuntime({ cwd: root, session: new FakeSession('pi-session-old') });
|
|
709
|
+
daemon = createSessionDaemon({
|
|
710
|
+
endpoint,
|
|
711
|
+
credential,
|
|
712
|
+
cwd: root,
|
|
713
|
+
createRuntime: async () => runtime,
|
|
714
|
+
});
|
|
715
|
+
await daemon.start();
|
|
716
|
+
|
|
717
|
+
const client = connectClient(endpoint);
|
|
718
|
+
await client.authenticate();
|
|
719
|
+
await client.request('sessions.create', { cwd: root });
|
|
720
|
+
runtime.session.extensionRunner = {
|
|
721
|
+
getRegisteredCommands: () => [{ invocationName: 'balance' }],
|
|
722
|
+
};
|
|
723
|
+
|
|
724
|
+
await client.request('sessions.prompt', { sessionId: 'pi-session-new', text: '/balance' });
|
|
725
|
+
expect(runtime.session.names).toEqual([]);
|
|
726
|
+
|
|
727
|
+
const promptedUpdated = client.next((frame) => frame.event === 'session.updated' && frame.payload?.title === 'Build the feature');
|
|
728
|
+
await client.request('sessions.prompt', { sessionId: 'pi-session-new', text: 'Build the feature' });
|
|
729
|
+
await expect(promptedUpdated).resolves.toMatchObject({
|
|
730
|
+
payload: { sessionId: 'pi-session-new', title: 'Build the feature' },
|
|
731
|
+
});
|
|
732
|
+
expect(runtime.session.names).toEqual(['Build the feature']);
|
|
733
|
+
await client.close();
|
|
734
|
+
});
|
|
735
|
+
|
|
705
736
|
it('creates a global session from the literal home-directory target', async () => {
|
|
706
737
|
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-'));
|
|
707
738
|
const endpoint = testDaemonEndpoint(root);
|
|
@@ -1846,6 +1877,45 @@ describe('Pi session daemon spike', () => {
|
|
|
1846
1877
|
await client.close();
|
|
1847
1878
|
});
|
|
1848
1879
|
|
|
1880
|
+
it('publishes session.model when an extension command switches the model without a session event', async () => {
|
|
1881
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-command-model-'));
|
|
1882
|
+
const endpoint = testDaemonEndpoint(root);
|
|
1883
|
+
const sessionFile = join(root, 'session-1.jsonl');
|
|
1884
|
+
await writeFile(sessionFile, `{"type":"session","id":"session-1","cwd":"${root}"}\n`);
|
|
1885
|
+
const session = new FakeSession('session-1', sessionFile);
|
|
1886
|
+
// Pi notifies extensions of model switches, not session subscribers:
|
|
1887
|
+
// mutate live runtime state without emitting any session event.
|
|
1888
|
+
session.prompt = async () => {
|
|
1889
|
+
session.model = { provider: 'openai-codex', id: 'gpt-5.6-luna' };
|
|
1890
|
+
};
|
|
1891
|
+
daemon = createSessionDaemon({
|
|
1892
|
+
endpoint,
|
|
1893
|
+
credential,
|
|
1894
|
+
cwd: root,
|
|
1895
|
+
createRuntime: async () => new FakeRuntime({ cwd: root, session }),
|
|
1896
|
+
listSessions: async () => [
|
|
1897
|
+
{ path: sessionFile, id: 'session-1', cwd: root, created: new Date(), modified: new Date(), messageCount: 0 },
|
|
1898
|
+
],
|
|
1899
|
+
});
|
|
1900
|
+
await daemon.start();
|
|
1901
|
+
const client = connectClient(endpoint);
|
|
1902
|
+
await client.authenticate();
|
|
1903
|
+
|
|
1904
|
+
const modelChanged = client.next((frame) => frame.event === 'session.model');
|
|
1905
|
+
await expect(client.request('sessions.prompt', {
|
|
1906
|
+
sessionId: 'session-1',
|
|
1907
|
+
text: '/balance',
|
|
1908
|
+
})).resolves.toMatchObject({ result: { accepted: true } });
|
|
1909
|
+
|
|
1910
|
+
await expect(modelChanged).resolves.toMatchObject({
|
|
1911
|
+
payload: {
|
|
1912
|
+
sessionId: 'session-1',
|
|
1913
|
+
model: { providerId: 'openai-codex', modelId: 'gpt-5.6-luna' },
|
|
1914
|
+
},
|
|
1915
|
+
});
|
|
1916
|
+
await client.close();
|
|
1917
|
+
});
|
|
1918
|
+
|
|
1849
1919
|
it('acknowledges a prompt without waiting for the agent turn to finish', async () => {
|
|
1850
1920
|
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-prompt-ack-'));
|
|
1851
1921
|
const endpoint = testDaemonEndpoint(root);
|
|
@@ -1884,6 +1954,73 @@ describe('Pi session daemon spike', () => {
|
|
|
1884
1954
|
await client.close();
|
|
1885
1955
|
});
|
|
1886
1956
|
|
|
1957
|
+
it('handles prompt with image attachments and sends multi-part content', async () => {
|
|
1958
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-prompt-img-'));
|
|
1959
|
+
const endpoint = testDaemonEndpoint(root);
|
|
1960
|
+
const sessionFile = join(root, 'session-1.jsonl');
|
|
1961
|
+
const imageFile = join(root, 'test.png');
|
|
1962
|
+
await writeFile(sessionFile, `{"type":"session","id":"session-1","cwd":"${root}"}\n`);
|
|
1963
|
+
await writeFile(imageFile, Buffer.from('fake-png-data'));
|
|
1964
|
+
const session = new FakeSession('session-1', sessionFile);
|
|
1965
|
+
const finishSends = [];
|
|
1966
|
+
session.sendUserMessage = (content, options) => {
|
|
1967
|
+
session.sent.push({ text: content, options });
|
|
1968
|
+
return new Promise((resolve) => finishSends.push(resolve));
|
|
1969
|
+
};
|
|
1970
|
+
daemon = createSessionDaemon({
|
|
1971
|
+
endpoint,
|
|
1972
|
+
credential,
|
|
1973
|
+
cwd: root,
|
|
1974
|
+
createRuntime: async () => new FakeRuntime({ cwd: root, session }),
|
|
1975
|
+
listSessions: async () => [
|
|
1976
|
+
{ path: sessionFile, id: 'session-1', cwd: root, created: new Date(), modified: new Date(), messageCount: 0 },
|
|
1977
|
+
],
|
|
1978
|
+
});
|
|
1979
|
+
await daemon.start();
|
|
1980
|
+
const client = connectClient(endpoint);
|
|
1981
|
+
await client.authenticate();
|
|
1982
|
+
|
|
1983
|
+
await client.request('sessions.prompt', {
|
|
1984
|
+
sessionId: 'session-1',
|
|
1985
|
+
text: 'first without a file',
|
|
1986
|
+
messageId: 'msg-0',
|
|
1987
|
+
});
|
|
1988
|
+
const firstUserStart = client.next((frame) => frame.event === 'assistant.message.start' && frame.payload.role === 'user');
|
|
1989
|
+
session.emit({ type: 'message_start', message: { role: 'user', content: 'first without a file', timestamp: 900 } });
|
|
1990
|
+
|
|
1991
|
+
const response = await client.request('sessions.prompt', {
|
|
1992
|
+
sessionId: 'session-1',
|
|
1993
|
+
text: 'what is this?',
|
|
1994
|
+
attachments: [{
|
|
1995
|
+
name: 'image-1.png',
|
|
1996
|
+
mime: 'image/png',
|
|
1997
|
+
path: imageFile,
|
|
1998
|
+
size: 13,
|
|
1999
|
+
}],
|
|
2000
|
+
messageId: 'msg-1',
|
|
2001
|
+
});
|
|
2002
|
+
|
|
2003
|
+
expect(response.result).toEqual({ accepted: true, messageId: 'msg-1' });
|
|
2004
|
+
const secondUserStart = client.next((frame) => frame.event === 'assistant.message.start'
|
|
2005
|
+
&& frame.payload?.role === 'user'
|
|
2006
|
+
&& frame.payload?.text === 'what is this?');
|
|
2007
|
+
session.emit({ type: 'message_start', message: { role: 'user', content: session.sent[1].text, timestamp: 1_000 } });
|
|
2008
|
+
await expect(firstUserStart).resolves.not.toHaveProperty('payload.files');
|
|
2009
|
+
await expect(secondUserStart).resolves.toMatchObject({
|
|
2010
|
+
payload: {
|
|
2011
|
+
role: 'user',
|
|
2012
|
+
text: 'what is this?',
|
|
2013
|
+
files: [{ type: 'file', mime: 'image/png', filename: 'image-1.png' }],
|
|
2014
|
+
},
|
|
2015
|
+
});
|
|
2016
|
+
expect(session.sent).toHaveLength(2);
|
|
2017
|
+
expect(Array.isArray(session.sent[1].text)).toBe(true);
|
|
2018
|
+
expect(session.sent[1].text[0]).toEqual({ type: 'text', text: 'what is this?' });
|
|
2019
|
+
expect(session.sent[1].text[1]).toEqual({ type: 'image', mimeType: 'image/png', data: Buffer.from('fake-png-data').toString('base64') });
|
|
2020
|
+
for (const finish of finishSends) finish();
|
|
2021
|
+
await client.close();
|
|
2022
|
+
});
|
|
2023
|
+
|
|
1887
2024
|
it('starts a new turn when follow-up arrives after the stream has already ended', async () => {
|
|
1888
2025
|
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-followup-idle-'));
|
|
1889
2026
|
const endpoint = testDaemonEndpoint(root);
|