pi-plus 0.2.27 → 0.2.28

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.
@@ -86,7 +86,7 @@ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.ht
86
86
 
87
87
  `)}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
88
88
 
89
- `),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model2,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model2.cost,matchedThreshold=-1;for(let tier of model2.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model2){return model2.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model2.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model2,level){let availableLevels=getSupportedThinkingLevels(model2);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i5=requestedIndex;i5<EXTENDED_THINKING_LEVELS.length;i5++){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}for(let i5=requestedIndex-1;i5>=0;i5--){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body);return{status,body,message:error2.message,messageCarriesBody}}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var import_partial_json=__toESM(require_dist()),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"]);function isControlCharacter(char){let codePoint=char.codePointAt(0);return codePoint!==void 0&&codePoint>=0&&codePoint<=31}function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
89
+ `),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model2,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model2.cost,matchedThreshold=-1;for(let tier of model2.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost.totalFromProvider=!1,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model2){return model2.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model2.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model2,level){let availableLevels=getSupportedThinkingLevels(model2);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i5=requestedIndex;i5<EXTENDED_THINKING_LEVELS.length;i5++){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}for(let i5=requestedIndex-1;i5>=0;i5--){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body);return{status,body,message:error2.message,messageCarriesBody}}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var import_partial_json=__toESM(require_dist()),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"]);function isControlCharacter(char){let codePoint=char.codePointAt(0);return codePoint!==void 0&&codePoint>=0&&codePoint<=31}function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
90
90
  `:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${char.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function repairJson(json){let repaired="",inString=!1;for(let index=0;index<json.length;index++){let char=json[index];if(!inString){repaired+=char,char==='"'&&(inString=!0);continue}if(char==='"'){repaired+=char,inString=!1;continue}if(char==="\\"){let nextChar=json[index+1];if(nextChar===void 0){repaired+="\\\\";continue}if(nextChar==="u"){let unicodeDigits=json.slice(index+2,index+6);if(/^[0-9a-fA-F]{4}$/.test(unicodeDigits)){repaired+=`\\u${unicodeDigits}`,index+=5;continue}}if(VALID_JSON_ESCAPES.has(nextChar)){repaired+=`\\${nextChar}`,index+=1;continue}repaired+="\\\\";continue}repaired+=isControlCharacter(char)?escapeControlCharacter(char):char}return repaired}function parseJsonWithRepair(json){try{return JSON.parse(json)}catch(error2){let repairedJson=repairJson(json);if(repairedJson!==json)return JSON.parse(repairedJson);throw error2}}function parseToolCallArguments(json){if(!json?.trim())return{arguments:{}};try{let parsed=parseJsonWithRepair(json);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Tool arguments must be a JSON object");return{arguments:parsed}}catch(error2){return{arguments:{},argumentsError:`${error2 instanceof Error?error2.message:String(error2)}
91
91
 
92
92
  Received arguments:
@@ -687,6 +687,15 @@
687
687
  display: block;
688
688
  }
689
689
 
690
+ .system-entry > .message-timestamp {
691
+ padding-left: var(--line-height);
692
+ margin-bottom: 4px;
693
+ }
694
+
695
+ .system-entry > :last-child {
696
+ margin-bottom: 0;
697
+ }
698
+
690
699
  .system-prompt.provider-prompt {
691
700
  border-left: 3px solid var(--warning);
692
701
  }
@@ -98,14 +98,12 @@
98
98
  }
99
99
  }
100
100
 
101
- // Sort children by timestamp
102
- function sortChildren(node) {
101
+ // Sort children by timestamp. Iterative: long sessions form chains deeper than the JS call stack.
102
+ for (const node of nodeMap.values()) {
103
103
  node.children.sort((a, b) =>
104
104
  new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()
105
105
  );
106
- node.children.forEach(sortChildren);
107
106
  }
108
- roots.forEach(sortChildren);
109
107
 
110
108
  return roots;
111
109
  }
@@ -134,14 +132,14 @@
134
132
  const path = [];
135
133
  let current = byId.get(targetId);
136
134
  while (current) {
137
- path.unshift(current);
135
+ path.push(current);
138
136
  // Stop if no parent or self-referencing (root)
139
137
  if (!current.parentId || current.parentId === current.id) {
140
138
  break;
141
139
  }
142
140
  current = byId.get(current.parentId);
143
141
  }
144
- return path;
142
+ return path.reverse();
145
143
  }
146
144
 
147
145
  // Tree node lookup for finding leaves
@@ -156,12 +154,12 @@
156
154
  // Build tree node map lazily
157
155
  if (!treeNodeMap) {
158
156
  treeNodeMap = new Map();
159
- const tree = buildTree();
160
- function mapNodes(node) {
157
+ const stack = [...buildTree()];
158
+ while (stack.length > 0) {
159
+ const node = stack.pop();
161
160
  treeNodeMap.set(node.entry.id, node);
162
- node.children.forEach(mapNodes);
161
+ for (const child of node.children) stack.push(child);
163
162
  }
164
- tree.forEach(mapNodes);
165
163
  }
166
164
 
167
165
  const node = treeNodeMap.get(nodeId);
@@ -185,16 +183,22 @@
185
183
  const multipleRoots = roots.length > 1;
186
184
 
187
185
  // Mark which subtrees contain the active leaf
186
+ // Iterative post-order: long sessions form chains deeper than the JS call stack.
188
187
  const containsActive = new Map();
189
- function markActive(node) {
190
- let has = activePathIds.has(node.entry.id);
191
- for (const child of node.children) {
192
- if (markActive(child)) has = true;
193
- }
194
- containsActive.set(node, has);
195
- return has;
188
+ const postOrder = [];
189
+ const pending = [...roots];
190
+ while (pending.length > 0) {
191
+ const node = pending.pop();
192
+ postOrder.push(node);
193
+ for (const child of node.children) pending.push(child);
194
+ }
195
+ for (let i = postOrder.length - 1; i >= 0; i--) {
196
+ const node = postOrder[i];
197
+ containsActive.set(
198
+ node,
199
+ activePathIds.has(node.entry.id) || node.children.some(child => containsActive.get(child))
200
+ );
196
201
  }
197
- roots.forEach(markActive);
198
202
 
199
203
  // Stack: [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]
200
204
  const stack = [];
@@ -313,6 +317,76 @@
313
317
  return '';
314
318
  }
315
319
 
320
+ // ============================================================
321
+ // SYSTEM MESSAGES (pure data)
322
+ // ============================================================
323
+
324
+ function systemContentText(content) {
325
+ if (typeof content === 'string') return content;
326
+ if (Array.isArray(content)) {
327
+ return content.filter(c => c.type === 'text' && c.text).map(c => c.text).join('\n');
328
+ }
329
+ return '';
330
+ }
331
+
332
+ /** Full prompt text of a system message, mirroring getSystemMessageText() in pi-ai. */
333
+ function getSystemMessageText(msg) {
334
+ const parts = [systemContentText(msg.content)];
335
+ for (const value of Object.values(msg.sections || {})) {
336
+ if (value !== null) parts.push(value);
337
+ }
338
+ return parts.filter(part => part.length > 0).join('\n\n');
339
+ }
340
+
341
+ /** Text of a later system message, mirroring renderSystemMessageUpdate() in pi-ai. */
342
+ function renderSystemMessageUpdate(msg) {
343
+ const parts = [];
344
+ const text = systemContentText(msg.content);
345
+ if (text.length > 0) parts.push(text);
346
+ for (const [name, value] of Object.entries(msg.sections || {})) {
347
+ parts.push(value === null
348
+ ? `Removed system prompt section "${name}".`
349
+ : `Updated system prompt section "${name}":\n\n${value}`);
350
+ }
351
+ return parts.join('\n\n');
352
+ }
353
+
354
+ function carriesSystemState(entry) {
355
+ return (entry.type === 'message' && entry.message.role === 'system') ||
356
+ (entry.type === 'compaction' && entry.systemMessage);
357
+ }
358
+
359
+ /**
360
+ * Whether a system entry starts the prompt on its branch. Later system entries
361
+ * patch the prompt, so they render as updates instead of a full prompt.
362
+ */
363
+ function isLeadingSystemEntry(entry) {
364
+ let current = entry.parentId && entry.parentId !== entry.id ? byId.get(entry.parentId) : undefined;
365
+ while (current) {
366
+ if (carriesSystemState(current)) return false;
367
+ if (!current.parentId || current.parentId === current.id) break;
368
+ current = byId.get(current.parentId);
369
+ }
370
+ return true;
371
+ }
372
+
373
+ /** Short description of what a later system message changes, e.g. "project_context, -rules, tools +bash". */
374
+ function describeSystemUpdate(msg) {
375
+ const parts = [];
376
+ if (systemContentText(msg.content).length > 0) parts.push('instructions');
377
+ for (const [name, value] of Object.entries(msg.sections || {})) {
378
+ parts.push(value === null ? `-${name}` : name);
379
+ }
380
+ const toolChanges = [
381
+ ...(msg.toolsAdded || []).map(t => `+${t.name}`),
382
+ ...(msg.toolsRemoved || []).map(t => `-${t.name}`),
383
+ ];
384
+ if (toolChanges.length > 0) parts.push(`tools ${toolChanges.join(' ')}`);
385
+ return parts.join(', ');
386
+ }
387
+
388
+ const hasSystemEntries = entries.some(entry => entry.type === 'message' && entry.message.role === 'system');
389
+
316
390
  /**
317
391
  * Parse a skill block from message text.
318
392
  * Returns null if the text doesn't contain a skill block.
@@ -337,6 +411,13 @@
337
411
  case 'message': {
338
412
  const msg = entry.message;
339
413
  parts.push(msg.role);
414
+ if (msg.role === 'system') {
415
+ parts.push(isLeadingSystemEntry(entry) ? 'system prompt' : 'system update');
416
+ parts.push(getSystemMessageText(msg));
417
+ for (const name of Object.keys(msg.sections || {})) parts.push(name);
418
+ for (const tool of [...(msg.toolsAdded || []), ...(msg.toolsRemoved || [])]) parts.push(tool.name);
419
+ break;
420
+ }
340
421
  if (msg.content) parts.push(extractContent(msg.content));
341
422
  if (msg.role === 'bashExecution' && msg.command) parts.push(msg.command);
342
423
  break;
@@ -675,6 +756,13 @@
675
756
  const cmd = truncate(normalize(msg.command || ''));
676
757
  return labelHtml + `<span class="tree-role-tool">[bash]:</span> ${escapeHtml(cmd)}`;
677
758
  }
759
+ if (msg.role === 'system') {
760
+ if (isLeadingSystemEntry(entry)) {
761
+ return labelHtml + `<span class="tree-muted">[system prompt]</span>`;
762
+ }
763
+ const changes = describeSystemUpdate(msg);
764
+ return labelHtml + `<span class="tree-muted">[system update${changes ? ': ' + escapeHtml(truncate(changes)) : ''}]</span>`;
765
+ }
678
766
  return labelHtml + `<span class="tree-muted">[${escapeHtml(msg.role)}]</span>`;
679
767
  }
680
768
  case 'compaction':
@@ -1311,6 +1399,24 @@
1311
1399
  }
1312
1400
 
1313
1401
  if (msg.role === 'toolResult') return '';
1402
+
1403
+ if (msg.role === 'system') {
1404
+ let html = '';
1405
+ if (isLeadingSystemEntry(entry)) {
1406
+ const text = getSystemMessageText(msg);
1407
+ if (text) html += renderSystemPromptBlock('System Prompt', text);
1408
+ html += renderToolsList('Available Tools', msg.toolsAdded);
1409
+ } else {
1410
+ const text = renderSystemMessageUpdate(msg);
1411
+ const changes = describeSystemUpdate(msg);
1412
+ if (text) html += renderSystemPromptBlock(`System Prompt Update${changes ? ': ' + changes : ''}`, text);
1413
+ html += renderToolsList('Tools Added', msg.toolsAdded);
1414
+ if (msg.toolsRemoved && msg.toolsRemoved.length > 0) {
1415
+ html += `<div class="tools-list"><div class="tools-header">Tools Removed</div><div class="tools-content">${msg.toolsRemoved.map(t => `<div class="tool-item"><span class="tool-item-name">${escapeHtml(t.name)}</span></div>`).join('')}</div></div>`;
1416
+ }
1417
+ }
1418
+ return html ? `<div class="system-entry" id="${entryDomId}">${tsHtml}${html}</div>` : '';
1419
+ }
1314
1420
  }
1315
1421
 
1316
1422
  if (entry.type === 'model_change') {
@@ -1351,7 +1457,7 @@
1351
1457
  let userMessages = 0, assistantMessages = 0, toolResults = 0;
1352
1458
  let customMessages = 0, compactions = 0, branchSummaries = 0, toolCalls = 0;
1353
1459
  const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1354
- const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1460
+ const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
1355
1461
  const models = new Set();
1356
1462
 
1357
1463
  for (const entry of entryList) {
@@ -1367,10 +1473,18 @@
1367
1473
  tokens.cacheRead += msg.usage.cacheRead || 0;
1368
1474
  tokens.cacheWrite += msg.usage.cacheWrite || 0;
1369
1475
  if (msg.usage.cost) {
1476
+ const componentTotal =
1477
+ (msg.usage.cost.input || 0) +
1478
+ (msg.usage.cost.output || 0) +
1479
+ (msg.usage.cost.cacheRead || 0) +
1480
+ (msg.usage.cost.cacheWrite || 0);
1370
1481
  cost.input += msg.usage.cost.input || 0;
1371
1482
  cost.output += msg.usage.cost.output || 0;
1372
1483
  cost.cacheRead += msg.usage.cost.cacheRead || 0;
1373
1484
  cost.cacheWrite += msg.usage.cost.cacheWrite || 0;
1485
+ // Provider-reported totals can intentionally differ from catalog-estimated components.
1486
+ // Fall back to the component sum for sessions written before cost.total was recorded.
1487
+ cost.total += typeof msg.usage.cost.total === 'number' ? msg.usage.cost.total : componentTotal;
1374
1488
  }
1375
1489
  }
1376
1490
  toolCalls += msg.content.filter(c => c.type === 'toolCall').length;
@@ -1391,7 +1505,7 @@
1391
1505
  const globalStats = computeStats(entries);
1392
1506
 
1393
1507
  function renderHeader() {
1394
- const totalCost = globalStats.cost.input + globalStats.cost.output + globalStats.cost.cacheRead + globalStats.cost.cacheWrite;
1508
+ const totalCost = globalStats.cost.total;
1395
1509
 
1396
1510
  const tokenParts = [];
1397
1511
  if (globalStats.tokens.input) tokenParts.push(`↑${formatTokens(globalStats.tokens.input)}`);
@@ -1429,30 +1543,39 @@
1429
1543
  </div>
1430
1544
  </div>`;
1431
1545
 
1432
- // Render system prompt (user's base prompt, applies to all providers)
1433
- if (systemPrompt) {
1434
- const lines = systemPrompt.split('\n');
1435
- const previewLines = 10;
1436
- if (lines.length > previewLines) {
1437
- const preview = lines.slice(0, previewLines).join('\n');
1438
- const remaining = lines.length - previewLines;
1439
- html += `<div class="system-prompt expandable" onclick="if(window.getSelection().toString())return;this.classList.toggle('expanded')">
1440
- <div class="system-prompt-header">System Prompt</div>
1441
- <div class="system-prompt-preview">${escapeHtml(preview)}</div>
1442
- <div class="system-prompt-expand-hint">... (${remaining} more lines, click to expand)</div>
1443
- <div class="system-prompt-full">${escapeHtml(systemPrompt)}</div>
1444
- </div>`;
1445
- } else {
1446
- html += `<div class="system-prompt">
1447
- <div class="system-prompt-header">System Prompt</div>
1448
- <div class="system-prompt-full" style="display: block">${escapeHtml(systemPrompt)}</div>
1449
- </div>`;
1450
- }
1546
+ // Sessions with system entries render the prompt and tools in the transcript, where they
1547
+ // occur. Older sessions have none, so fall back to the exporting agent's current state.
1548
+ if (!hasSystemEntries) {
1549
+ if (systemPrompt) html += renderSystemPromptBlock('System Prompt', systemPrompt);
1550
+ html += renderToolsList('Available Tools', tools);
1451
1551
  }
1452
1552
 
1453
- if (tools && tools.length > 0) {
1454
- html += `<div class="tools-list">
1455
- <div class="tools-header">Available Tools</div>
1553
+ return html;
1554
+ }
1555
+
1556
+ function renderSystemPromptBlock(title, text) {
1557
+ const lines = text.split('\n');
1558
+ const previewLines = 10;
1559
+ if (lines.length > previewLines) {
1560
+ const preview = lines.slice(0, previewLines).join('\n');
1561
+ const remaining = lines.length - previewLines;
1562
+ return `<div class="system-prompt expandable" onclick="if(window.getSelection().toString())return;this.classList.toggle('expanded')">
1563
+ <div class="system-prompt-header">${escapeHtml(title)}</div>
1564
+ <div class="system-prompt-preview">${escapeHtml(preview)}</div>
1565
+ <div class="system-prompt-expand-hint">... (${remaining} more lines, click to expand)</div>
1566
+ <div class="system-prompt-full">${escapeHtml(text)}</div>
1567
+ </div>`;
1568
+ }
1569
+ return `<div class="system-prompt">
1570
+ <div class="system-prompt-header">${escapeHtml(title)}</div>
1571
+ <div class="system-prompt-full" style="display: block">${escapeHtml(text)}</div>
1572
+ </div>`;
1573
+ }
1574
+
1575
+ function renderToolsList(title, tools) {
1576
+ if (!tools || tools.length === 0) return '';
1577
+ return `<div class="tools-list">
1578
+ <div class="tools-header">${escapeHtml(title)}</div>
1456
1579
  <div class="tools-content">
1457
1580
  ${tools.map(t => {
1458
1581
  const hasParams = t.parameters && typeof t.parameters === 'object' && t.parameters.properties && Object.keys(t.parameters.properties).length > 0;
@@ -1477,9 +1600,6 @@
1477
1600
  }).join('')}
1478
1601
  </div>
1479
1602
  </div>`;
1480
- }
1481
-
1482
- return html;
1483
1603
  }
1484
1604
 
1485
1605
  // ============================================================
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-plus",
3
- "version": "0.2.27",
3
+ "version": "0.2.28",
4
4
  "description": "pi coding agent with the pi-plus override layer (pipi CLI)",
5
5
  "type": "module",
6
6
  "piConfig": {