Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
/**
* Message helpers shared by the session runtime and its subagents.
*
* Both loops read pi-ai assistant content and usage into the same `UiMessage`
* shape, so the conversions live here instead of being duplicated per loop.
*/
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { JsonObject, JsonValue, Usage } from "@earendil-works/pi-ai";
import { responsesTextPhase, type AssistantProviderReplay, type MessageUsage, type UsageProvenance } from "@pi-desktop/shared";
export function nowIso(): string {
return new Date().toISOString();
}
/** Epoch milliseconds for a pi session entry. pi 0.84 changed `Entry.timestamp`
* from an ISO string to a number, so entries we synthesize from stored history
* need the numeric form. */
export function timestampMs(timestamp: unknown): number {
if (typeof timestamp === "number" && Number.isFinite(timestamp)) {
return timestamp;
}
if (typeof timestamp === "string") {
const parsed = Date.parse(timestamp);
if (Number.isFinite(parsed)) return parsed;
}
return Date.now();
}
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/** JSON-clone an opaque value so it satisfies pi 0.86 `JsonValue`. */
export function toJsonValue(value: unknown): JsonValue | undefined {
if (value === undefined) return undefined;
try {
return JSON.parse(JSON.stringify(value)) as JsonValue;
} catch {
return undefined;
}
}
function isJsonObject(value: JsonValue): value is JsonObject {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function toJsonObject(value: unknown): Record<string, JsonValue> {
const normalized = toJsonValue(value);
return normalized !== undefined && isJsonObject(normalized)
? normalized
: {};
}
/** Pi requires numeric costs, including when replaying history with no price. */
export type AccountedPiUsage = Usage & { desktopUsage?: MessageUsage };
export function usageFromPi(
usage: Usage | undefined | null,
provenance: UsageProvenance = {},
): MessageUsage | undefined {
if (!usage) return undefined;
const retained = (usage as AccountedPiUsage).desktopUsage;
if (retained) return { ...retained, ...provenance };
const tokens = (value: number | undefined) => Number.isFinite(value) ? Math.max(0, Math.round(value ?? 0)) : 0;
const inputTokens = tokens(usage.input);
const outputTokens = tokens(usage.output);
const cacheReadTokens = tokens(usage.cacheRead);
const cacheWriteTokens = tokens(usage.cacheWrite);
const reasoningTokens = typeof usage.reasoning === "number" ? tokens(usage.reasoning) : undefined;
const totalTokens = tokens(usage.totalTokens) || inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens;
const validCost = usage.cost && (["input", "output", "cacheRead", "cacheWrite", "total"] as const).every((key) => Number.isFinite(usage.cost[key]) && usage.cost[key] >= 0);
// Pi adapters normally calculate cost from model rates. Unmarked all-zero
// costs are also their missing-price placeholder, not evidence of free use.
// Pi 1.5 marks a total that is the provider-billed cost (for example
// OpenRouter usage accounting). That is authoritative over catalog-rate
// provenance, including models without native rates.
const billed = validCost && usage.cost.totalFromProvider === true;
const costStatus = billed ? "reported"
: provenance.costStatus ?? (validCost && usage.cost.total > 0 ? "estimated" : "unknown");
const cost = validCost && costStatus !== "unknown"
? { input: usage.cost.input, output: usage.cost.output, cacheRead: usage.cost.cacheRead, cacheWrite: usage.cost.cacheWrite, total: usage.cost.total }
: undefined;
if (totalTokens <= 0 && inputTokens <= 0 && outputTokens <= 0 && !cost?.total) return undefined;
return {
inputTokens,
outputTokens,
...(Number.isFinite(usage.cacheRead) && usage.cacheRead >= 0 ? { cacheReadTokens } : {}),
...(Number.isFinite(usage.cacheWrite) && usage.cacheWrite >= 0 ? { cacheWriteTokens } : {}),
...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
totalTokens,
usageOrigin: "pi",
...provenance,
costStatus: cost ? costStatus : "unknown",
...(cost ? { cost } : {}),
...(provenance.operationId ? { aggregation: "operation" } : {}),
};
}
export function usageToPi(usage: MessageUsage | undefined): AccountedPiUsage {
const input = usage?.inputTokens ?? 0;
const output = usage?.outputTokens ?? 0;
const cacheRead = usage?.cacheReadTokens ?? 0;
const cacheWrite = usage?.cacheWriteTokens ?? 0;
return {
input,
output,
cacheRead,
cacheWrite,
...(usage?.reasoningTokens !== undefined ? { reasoning: usage.reasoningTokens } : {}),
totalTokens: usage?.totalTokens ?? input + output + cacheRead + cacheWrite,
cost: usage?.cost && usage.costStatus !== "unknown"
? { ...usage.cost, ...(usage.costStatus === "reported" ? { totalFromProvider: true } : {}) }
: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
// Explicitly tag the numeric placeholder so it can never become a known
// zero-dollar charge when reconstructed history crosses this boundary again.
...(usage ? { desktopUsage: { ...usage } } : {}),
};
}
/** Only the transcript needs the signed original; report and recovery callers consume `text`. */
export type CommentaryTranscript = { text: string; replay: AssistantProviderReplay };
/** Appends to the trailing text block need only a delta. A different partition needs one snapshot. */
export function sameCommentaryBoundaries(previous?: CommentaryTranscript, next?: CommentaryTranscript): boolean {
if (!previous || !next) return previous === next;
const before = previous.replay.blocks;
const after = next.replay.blocks;
return before.length === after.length && before.every((block, i) =>
block.signature === after[i].signature && (i === before.length - 1 || block.length === after[i].length));
}
export type AssistantContent = {
text: string;
thinking: string;
hasText: boolean;
hasThinking: boolean;
hasFinalAnswer?: true;
transcript?: CommentaryTranscript;
};
/** Flatten a pi-ai assistant content array into visible text and reasoning. */
export function assistantContent(content: unknown): AssistantContent {
if (typeof content === "string") {
return { text: content, thinking: "", hasText: true, hasThinking: false };
}
if (!Array.isArray(content)) {
return { text: "", thinking: "", hasText: false, hasThinking: false };
}
let text = "";
let thinking = "";
let hasText = false;
let hasThinking = false;
let hasFinalAnswer = false;
let transcript: CommentaryTranscript | undefined;
for (const block of content) {
if (!isRecord(block)) continue;
if (block.type === "text" && typeof block.text === "string") {
hasText = true;
const phase = responsesTextPhase(block.textSignature);
if (phase === "commentary" && !transcript) {
transcript = { text, replay: { version: 1, blocks: text ? [{ type: "text", length: text.length }] : [] } };
}
if (transcript) {
transcript.text += block.text;
transcript.replay.blocks.push({
type: "text", length: block.text.length,
...(phase && typeof block.textSignature === "string" ? { signature: block.textSignature } : {}),
});
}
if (phase !== "commentary") text += block.text;
if (phase === "final_answer" && block.text.length) hasFinalAnswer = true;
} else if (block.type === "thinking") {
hasThinking = true;
if (typeof block.thinking === "string") {
thinking += block.thinking;
} else if (typeof block.text === "string") {
// Accept OpenAI-compatible adapters that expose thinking as `text`.
thinking += block.text;
}
}
}
return {
text, thinking, hasText, hasThinking,
...(hasFinalAnswer ? { hasFinalAnswer: true } : {}),
...(transcript ? { transcript } : {}),
};
}
/**
* Bound `text` to `maxChars`, keeping both ends and naming the cut in the
* middle. Compaction uses this wherever a message has to fit a budget it
* cannot: the survived text stays readable and the marker says why it is
* shorter.
*/
export function truncateTextWithMarker(
text: string,
maxChars: number,
marker: string,
): string {
if (text.length <= maxChars) return text;
if (maxChars <= marker.length) return marker.trim().slice(0, maxChars);
const retainedChars = maxChars - marker.length;
const headChars = Math.ceil(retainedChars * 0.75);
const tailChars = retainedChars - headChars;
return `${text.slice(0, headChars)}${marker}${
tailChars > 0 ? text.slice(-tailChars) : ""
}`;
}
/**
* Which string a block contributes to the truncation budget.
*
* Readable assistant thinking lives in `thinking`, not `text`, and pi counts
* it toward the context estimate. Redacted thinking is an opaque signature
* replay and is not rewritten. A thinking block that only carries `text`
* (some OpenAI-compatible adapters) still uses that field.
*/
function truncationField(block: Record<string, unknown>): "text" | "thinking" | undefined {
if (block.type === "thinking" && block.redacted === true) return undefined;
if (block.type === "thinking" && typeof block.thinking === "string") return "thinking";
if (typeof block.text === "string") return "text";
return undefined;
}
/**
* Bound every text block of one message so the message's total text is at most
* `maxChars`. Answer text is reserved first; assistant thinking is then cut to
* whatever remains, and a shortened thinking block drops its provider signature
* so the replay is not a mutated signed trace. Blocks without text (tool calls,
* images, redacted thinking) are kept, so a truncated message is still a
* provider-valid message with its tool calls intact.
*/
export function truncateMessageText(
message: AgentMessage,
maxChars: number,
marker: string,
): AgentMessage {
const content: unknown = (message as { content?: unknown }).content;
if (typeof content === "string") {
const text = truncateTextWithMarker(content, maxChars, marker);
return text === content ? message : ({ ...message, content: text } as AgentMessage);
}
if (!Array.isArray(content)) return message;
const fields = content.map((block) =>
isRecord(block) ? truncationField(block) : undefined,
);
// Reserve answer text first so a long thinking trace cannot evict it.
let textBudget = maxChars;
const textAllowance: number[] = [];
content.forEach((block, index) => {
if (fields[index] !== "text" || !isRecord(block)) return;
const value = block.text as string;
const allowance = Math.min(value.length, Math.max(0, textBudget));
textAllowance[index] = allowance;
textBudget -= allowance;
});
let thinkingBudget = Math.max(0, textBudget);
let changed = false;
const blocks = content.map((block, index) => {
const field = fields[index];
if (!field || !isRecord(block)) return block;
const value = block[field];
if (typeof value !== "string") return block;
const allowance = field === "text" ? (textAllowance[index] ?? 0) : thinkingBudget;
if (value.length <= allowance) {
if (field === "thinking") thinkingBudget -= value.length;
return block;
}
changed = true;
const nextValue = truncateTextWithMarker(value, Math.max(1, allowance), marker);
if (field === "thinking") thinkingBudget = 0;
if (field === "text") return { ...block, text: nextValue };
const next: Record<string, unknown> = { ...block, thinking: nextValue };
delete next.thinkingSignature;
delete next.redacted;
return next;
});
return changed ? ({ ...message, content: blocks } as AgentMessage) : message;
}