@selesai/code 0.13.26 → 0.13.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/cli/args.js +1 -0
  3. package/dist/cli/session-picker.d.ts +1 -1
  4. package/dist/config.js +1 -1
  5. package/dist/core/agent-session-auto-handoff.test.js +2 -1
  6. package/dist/core/agent-session-length-continuation.test.js +2 -1
  7. package/dist/core/agent-session.d.ts +58 -7
  8. package/dist/core/agent-session.js +334 -167
  9. package/dist/core/bug-report-upload.d.ts +11 -0
  10. package/dist/core/bug-report-upload.js +21 -0
  11. package/dist/core/bug-report.d.ts +175 -0
  12. package/dist/core/bug-report.js +291 -0
  13. package/dist/core/cache-stats.js +12 -1
  14. package/dist/core/cache-warmer.d.ts +101 -0
  15. package/dist/core/cache-warmer.js +341 -0
  16. package/dist/core/compaction/branch-summarization.js +2 -2
  17. package/dist/core/compaction/compaction.d.ts +6 -5
  18. package/dist/core/compaction/compaction.js +49 -42
  19. package/dist/core/crash-log.d.ts +21 -0
  20. package/dist/core/crash-log.js +70 -0
  21. package/dist/core/experimental.d.ts +0 -4
  22. package/dist/core/experimental.js +0 -4
  23. package/dist/core/extensions/index.d.ts +1 -1
  24. package/dist/core/extensions/jiti-loader.d.ts +1 -0
  25. package/dist/core/extensions/jiti-loader.js +3 -0
  26. package/dist/core/extensions/jiti-static-loader.d.ts +1 -0
  27. package/dist/core/extensions/jiti-static-loader.js +3 -0
  28. package/dist/core/extensions/loader.js +39 -49
  29. package/dist/core/extensions/runner.d.ts +10 -7
  30. package/dist/core/extensions/runner.js +85 -67
  31. package/dist/core/extensions/types.d.ts +66 -52
  32. package/dist/core/extensions/virtual-modules.d.ts +2 -0
  33. package/dist/core/extensions/virtual-modules.js +39 -0
  34. package/dist/core/extensions/wrapper.js +1 -20
  35. package/dist/core/index.d.ts +2 -1
  36. package/dist/core/keybindings.d.ts +1 -1
  37. package/dist/core/keybindings.js +1 -1
  38. package/dist/core/messages.js +1 -0
  39. package/dist/core/model-config.d.ts +101 -20
  40. package/dist/core/model-config.js +25 -18
  41. package/dist/core/model-resolver.js +2 -1
  42. package/dist/core/model-runtime.js +5 -3
  43. package/dist/core/provider-composer.d.ts +7 -2
  44. package/dist/core/provider-composer.js +10 -5
  45. package/dist/core/radius.d.ts +3 -0
  46. package/dist/core/radius.js +6 -0
  47. package/dist/core/sdk.js +60 -38
  48. package/dist/core/session-export.d.ts +6 -2
  49. package/dist/core/session-export.js +14 -13
  50. package/dist/core/session-format.test.d.ts +1 -0
  51. package/dist/core/session-format.test.js +96 -0
  52. package/dist/core/session-manager.d.ts +29 -6
  53. package/dist/core/session-manager.js +159 -96
  54. package/dist/core/settings-manager.d.ts +22 -5
  55. package/dist/core/settings-manager.js +56 -23
  56. package/dist/core/slash-commands.js +1 -0
  57. package/dist/core/system-prompt.d.ts +49 -4
  58. package/dist/core/system-prompt.js +155 -102
  59. package/dist/core/system-prompt.test.js +61 -23
  60. package/dist/core/tools/bash.d.ts +2 -1
  61. package/dist/core/tools/bash.js +10 -4
  62. package/dist/core/tools/edit.js +1 -2
  63. package/dist/core/tools/read.js +1 -2
  64. package/dist/core/tools/renderers/bash.js +9 -1
  65. package/dist/core/tools/write.js +1 -2
  66. package/dist/core/usage-totals.d.ts +1 -1
  67. package/dist/core/usage-totals.js +5 -1
  68. package/dist/extensions/pi-web-agent/src/backends/factory.ts +14 -6
  69. package/dist/extensions/pi-web-agent/src/extension.ts +3 -1
  70. package/dist/extensions/pi-web-agent/src/orchestration/answer-synthesizer.ts +7 -3
  71. package/dist/extensions/pi-web-agent/src/orchestration/research-orchestrator.ts +3 -0
  72. package/dist/extensions/pi-web-agent/src/orchestration/research-types.ts +2 -0
  73. package/dist/extensions/pi-web-agent/src/presentation/explore-presentation.ts +4 -2
  74. package/dist/extensions/pi-web-agent/src/search/tokenin.ts +4 -1
  75. package/dist/extensions/pi-web-agent/src/tools/web-explore.ts +2 -1
  76. package/dist/extensions/pi-web-agent/src/types.ts +4 -0
  77. package/dist/index.d.ts +3 -2
  78. package/dist/main.js +13 -9
  79. package/dist/migrations.js +2 -2
  80. package/dist/modes/interactive/bug-report.d.ts +15 -0
  81. package/dist/modes/interactive/bug-report.js +205 -0
  82. package/dist/modes/interactive/chat-viewport.js +1 -1
  83. package/dist/modes/interactive/components/branch-summary-message.js +12 -5
  84. package/dist/modes/interactive/components/compaction-summary-message.js +12 -5
  85. package/dist/modes/interactive/components/custom-editor.d.ts +3 -3
  86. package/dist/modes/interactive/components/extension-editor.d.ts +4 -1
  87. package/dist/modes/interactive/components/extension-editor.js +7 -2
  88. package/dist/modes/interactive/components/extension-input.d.ts +2 -0
  89. package/dist/modes/interactive/components/extension-input.js +6 -0
  90. package/dist/modes/interactive/components/extension-selector.d.ts +1 -0
  91. package/dist/modes/interactive/components/extension-selector.js +4 -0
  92. package/dist/modes/interactive/components/footer.js +4 -1
  93. package/dist/modes/interactive/components/session-selector.d.ts +5 -5
  94. package/dist/modes/interactive/components/session-selector.js +74 -48
  95. package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
  96. package/dist/modes/interactive/components/settings-selector.js +11 -0
  97. package/dist/modes/interactive/components/skill-invocation-message.js +11 -4
  98. package/dist/modes/interactive/components/status-indicator.d.ts +2 -2
  99. package/dist/modes/interactive/components/status-indicator.js +7 -7
  100. package/dist/modes/interactive/components/tool-execution.js +18 -9
  101. package/dist/modes/interactive/components/tree-selector.js +2 -0
  102. package/dist/modes/interactive/interactive-mode.d.ts +15 -2
  103. package/dist/modes/interactive/interactive-mode.js +257 -81
  104. package/dist/modes/interactive/session-share.d.ts +2 -0
  105. package/dist/modes/interactive/session-share.js +8 -4
  106. package/dist/modes/interactive/tui-renderer.js +2 -2
  107. package/dist/modes/rpc/rpc-mode.js +2 -2
  108. package/dist/utils/clipboard-command.d.ts +6 -0
  109. package/dist/utils/clipboard-command.js +44 -0
  110. package/dist/utils/clipboard-image.js +55 -89
  111. package/dist/utils/clipboard.d.ts +1 -1
  112. package/dist/utils/clipboard.js +118 -108
  113. package/dist/utils/wsl.d.ts +2 -0
  114. package/dist/utils/wsl.js +14 -0
  115. package/dist/utils/zip.d.ts +6 -0
  116. package/dist/utils/zip.js +59 -0
  117. package/package.json +9 -9
  118. package/dist/utils/clipboard-native.d.ts +0 -10
  119. package/dist/utils/clipboard-native.js +0 -19
@@ -0,0 +1,11 @@
1
+ import type { BugReportBundle } from "./bug-report.ts";
2
+ interface UploadBugReportOptions {
3
+ token?: string;
4
+ signal?: AbortSignal;
5
+ gatewayUrl?: string;
6
+ }
7
+ /** Upload a report as multipart form data, anonymously or attributed to a Radius account. */
8
+ export declare function uploadBugReport(bundle: BugReportBundle, options?: UploadBugReportOptions): Promise<{
9
+ id: string;
10
+ }>;
11
+ export {};
@@ -0,0 +1,21 @@
1
+ import { bugReportFiles } from "./bug-report.js";
2
+ import { getRadiusGatewayUrl } from "./radius.js";
3
+ /** Upload a report as multipart form data, anonymously or attributed to a Radius account. */
4
+ export async function uploadBugReport(bundle, options = {}) {
5
+ const body = new FormData();
6
+ for (const file of bugReportFiles(bundle)) {
7
+ body.append(file.name, new Blob([file.data], { type: file.contentType }), file.name);
8
+ }
9
+ const response = await fetch(new URL("/v1/bug-reports", options.gatewayUrl ?? getRadiusGatewayUrl()), {
10
+ method: "POST",
11
+ headers: options.token ? { Authorization: `Bearer ${options.token}` } : undefined,
12
+ body,
13
+ signal: options.signal,
14
+ });
15
+ const json = (await response.json().catch(() => null));
16
+ if (response.ok && json?.ok === true && typeof json.bug_report?.id === "string") {
17
+ return { id: json.bug_report.id };
18
+ }
19
+ const detail = json && !json.ok ? json.description || json.error : undefined;
20
+ throw new Error(`Bug report upload failed: ${detail || response.statusText || response.status}`);
21
+ }
@@ -0,0 +1,175 @@
1
+ import type { AgentMessage, StreamFn, ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import { type RetryPolicy } from "@earendil-works/pi-ai";
3
+ import type { Api, Model } from "@earendil-works/pi-ai/compat";
4
+ import type { CrashRecord } from "./crash-log.ts";
5
+ import type { Extension } from "./extensions/types.ts";
6
+ import type { ModelRuntime } from "./model-runtime.ts";
7
+ import type { ReadonlySessionManager } from "./session-manager.ts";
8
+ import type { Settings } from "./settings-manager.ts";
9
+ export declare const BUG_REPORT_CUSTOM_ENTRY_TYPE = "pi.bug-report";
10
+ /** Strip credentials and secret-looking query parameters from a URL. */
11
+ export declare function redactUrl(value: string): string;
12
+ /** Copy a JSON value while removing values that may contain credentials. */
13
+ export declare function redactJsonValue(value: unknown): unknown;
14
+ interface CollectBugReportMetadataOptions {
15
+ id?: string;
16
+ hint?: string;
17
+ sessionId: string;
18
+ cwd: string;
19
+ includeSession: boolean;
20
+ includeSummary: boolean;
21
+ messageCount: number;
22
+ model?: Model<Api>;
23
+ modelRuntime: ModelRuntime;
24
+ thinkingLevel: ThinkingLevel;
25
+ extensions: readonly Extension[];
26
+ extensionErrors: ReadonlyArray<{
27
+ path: string;
28
+ error: string;
29
+ }>;
30
+ globalSettings: Settings;
31
+ projectSettings: Settings;
32
+ }
33
+ export declare function collectBugReportMetadata(options: CollectBugReportMetadataOptions): {
34
+ schemaVersion: number;
35
+ id: string;
36
+ createdAt: string;
37
+ hint: string | null;
38
+ environment: {
39
+ version: string;
40
+ userAgent: string;
41
+ runtime: string;
42
+ platform: NodeJS.Platform;
43
+ arch: NodeJS.Architecture;
44
+ osRelease: string;
45
+ osVersion: string;
46
+ shell: string | null;
47
+ terminal: {
48
+ term: string | null;
49
+ program: string | null;
50
+ programVersion: string | null;
51
+ colorterm: string | null;
52
+ tmux: boolean;
53
+ ssh: boolean;
54
+ ci: boolean;
55
+ };
56
+ piEnvironmentVariables: string[];
57
+ };
58
+ session: {
59
+ id: string;
60
+ included: boolean;
61
+ summaryIncluded: boolean;
62
+ messageCount: number;
63
+ cwd?: string | undefined;
64
+ };
65
+ model: {
66
+ provider: string;
67
+ id: string;
68
+ name: string;
69
+ api: Api;
70
+ baseUrl: string;
71
+ reasoning: boolean;
72
+ input: ("image" | "text")[];
73
+ contextWindow: number;
74
+ maxTokens: number;
75
+ samplingParams: unknown;
76
+ compat: unknown;
77
+ thinkingLevelMap: Partial<Record<import("@earendil-works/pi-ai").ModelThinkingLevel, string | null>> | null;
78
+ headerNames: string[];
79
+ } | null;
80
+ provider: {
81
+ id: string;
82
+ name: string;
83
+ baseUrl: string | null;
84
+ headerNames: string[];
85
+ authTypes: ("api_key" | "oauth")[];
86
+ authStatus: import("./provider-composer.ts").AuthStatus;
87
+ usingOAuth: boolean;
88
+ registeredByExtension: boolean;
89
+ } | null;
90
+ thinkingLevel: ThinkingLevel;
91
+ extensions: {
92
+ path: string;
93
+ source: string;
94
+ scope: import("./source-info.ts").SourceScope;
95
+ origin: import("./source-info.ts").SourceOrigin;
96
+ hidden: boolean;
97
+ }[];
98
+ extensionErrors: {
99
+ path: string;
100
+ error: string;
101
+ }[];
102
+ settings: {
103
+ global: Settings;
104
+ project: Settings;
105
+ };
106
+ };
107
+ /** Collect failed assistant turns without collecting conversation content. */
108
+ export declare function collectBugReportDiagnostics(sessionManager: ReadonlySessionManager, crashes?: readonly CrashRecord[]): {
109
+ schemaVersion: number;
110
+ sessionId: string;
111
+ entryCount: number;
112
+ assistantMessageCount: number;
113
+ assistant: {
114
+ entryId: string;
115
+ timestamp: string;
116
+ provider: string;
117
+ model: string;
118
+ api: Api;
119
+ stopReason: import("@earendil-works/pi-ai").StopReason;
120
+ rawStopReason?: string | undefined;
121
+ errorMessage?: string | undefined;
122
+ diagnostics: import("@earendil-works/pi-ai").AssistantMessageDiagnostic[];
123
+ }[];
124
+ crashes: {
125
+ timestamp: string;
126
+ version: string;
127
+ kind: "fatal_error" | "uncaught_exception";
128
+ message: string;
129
+ stack: string | null;
130
+ sessionFile: string | null;
131
+ cwd: string;
132
+ }[];
133
+ };
134
+ export type BugReportMetadata = ReturnType<typeof collectBugReportMetadata>;
135
+ export type BugReportDiagnostics = ReturnType<typeof collectBugReportDiagnostics>;
136
+ export interface BugReportBundle {
137
+ metadata: BugReportMetadata;
138
+ diagnostics: BugReportDiagnostics;
139
+ sessionJsonl?: string;
140
+ summary?: string;
141
+ }
142
+ export interface BugReportSessionEntryData {
143
+ id: string;
144
+ createdAt: string;
145
+ hint: string | null;
146
+ sessionIncluded: boolean;
147
+ summaryIncluded: boolean;
148
+ delivery: "zip" | "upload";
149
+ path?: string;
150
+ }
151
+ interface BugReportFile {
152
+ name: string;
153
+ contentType: string;
154
+ data: string;
155
+ }
156
+ /** Files shared by upload and zip export. */
157
+ export declare function bugReportFiles(bundle: BugReportBundle): BugReportFile[];
158
+ export declare function writeBugReportArchive(bundle: BugReportBundle, filePath: string): Promise<void>;
159
+ export declare function bugReportArchiveFileName(id: string): string;
160
+ interface GenerateBugReportSummaryOptions {
161
+ messages: readonly AgentMessage[];
162
+ hint?: string;
163
+ model: Model<Api>;
164
+ apiKey?: string;
165
+ headers?: Record<string, string>;
166
+ env?: Record<string, string>;
167
+ signal: AbortSignal;
168
+ thinkingLevel?: ThinkingLevel;
169
+ streamFn?: StreamFn;
170
+ retry?: RetryPolicy;
171
+ sessionId?: string;
172
+ }
173
+ /** Ask the session model for a report when the user does not share the transcript. */
174
+ export declare function generateBugReportSummary(options: GenerateBugReportSummaryOptions): Promise<string>;
175
+ export {};
@@ -0,0 +1,291 @@
1
+ import * as os from "node:os";
2
+ import { contentText, normalizeContext, uuidv7 } from "@earendil-works/pi-ai";
3
+ import { VERSION } from "../config.js";
4
+ import { getPiUserAgent } from "../utils/pi-user-agent.js";
5
+ import { writeZipArchive } from "../utils/zip.js";
6
+ import { completeSummarization, estimateTokens, getSummarizationFailure } from "./compaction/compaction.js";
7
+ import { serializeConversation } from "./compaction/utils.js";
8
+ import { convertToLlm } from "./messages.js";
9
+ export const BUG_REPORT_CUSTOM_ENTRY_TYPE = "pi.bug-report";
10
+ const BUG_REPORT_SCHEMA_VERSION = 1;
11
+ const REDACTED = "<redacted>";
12
+ const SENSITIVE_KEY = /(?:^|[-_])(api[-_]?key|secret|token|password|passwd|credential|authorization|cookie)(?:$|[-_])/i;
13
+ function isSensitiveKey(key) {
14
+ return SENSITIVE_KEY.test(key.replace(/([a-z0-9])([A-Z])/g, "$1_$2"));
15
+ }
16
+ /** Strip credentials and secret-looking query parameters from a URL. */
17
+ export function redactUrl(value) {
18
+ const nested = /^([a-z][a-z0-9+.-]*:)([a-z][a-z0-9+.-]*:\/\/.*)$/i.exec(value);
19
+ if (nested)
20
+ return `${nested[1]}${redactUrl(nested[2])}`;
21
+ try {
22
+ const url = new URL(value);
23
+ let changed = false;
24
+ if (url.username || url.password) {
25
+ url.username = "";
26
+ url.password = "";
27
+ changed = true;
28
+ }
29
+ for (const key of url.searchParams.keys()) {
30
+ if (isSensitiveKey(key)) {
31
+ url.searchParams.set(key, REDACTED);
32
+ changed = true;
33
+ }
34
+ }
35
+ return changed ? url.toString() : value;
36
+ }
37
+ catch {
38
+ return value;
39
+ }
40
+ }
41
+ /** Copy a JSON value while removing values that may contain credentials. */
42
+ export function redactJsonValue(value) {
43
+ if (value === undefined)
44
+ return undefined;
45
+ return JSON.parse(JSON.stringify(value, (key, child) => {
46
+ if (child !== null && child !== undefined && isSensitiveKey(key))
47
+ return REDACTED;
48
+ return typeof child === "string" ? redactUrl(child) : child;
49
+ }));
50
+ }
51
+ function redactSettings(settings) {
52
+ const { trackingId: _trackingId, ...rest } = settings;
53
+ return redactJsonValue(rest);
54
+ }
55
+ function collectEnvironment() {
56
+ const env = (name) => process.env[name] || null;
57
+ return {
58
+ version: VERSION,
59
+ userAgent: getPiUserAgent(VERSION),
60
+ runtime: process.versions.bun ? `bun/${process.versions.bun}` : `node/${process.version}`,
61
+ platform: process.platform,
62
+ arch: process.arch,
63
+ osRelease: os.release(),
64
+ osVersion: os.version(),
65
+ shell: process.env.SHELL?.split(/[\\/]/).pop() || null,
66
+ terminal: {
67
+ term: env("TERM"),
68
+ program: env("TERM_PROGRAM"),
69
+ programVersion: env("TERM_PROGRAM_VERSION"),
70
+ colorterm: env("COLORTERM"),
71
+ tmux: Boolean(process.env.TMUX),
72
+ ssh: Boolean(process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY),
73
+ ci: Boolean(process.env.CI),
74
+ },
75
+ // Names help diagnose configuration; values never leave the machine.
76
+ piEnvironmentVariables: Object.keys(process.env)
77
+ .filter((name) => name.startsWith("PI_"))
78
+ .sort(),
79
+ };
80
+ }
81
+ function describeModel(model) {
82
+ return {
83
+ provider: model.provider,
84
+ id: model.id,
85
+ name: model.name,
86
+ api: model.api,
87
+ baseUrl: redactUrl(model.baseUrl),
88
+ reasoning: model.reasoning,
89
+ input: model.input,
90
+ contextWindow: model.contextWindow,
91
+ maxTokens: model.maxTokens,
92
+ samplingParams: model.samplingParams ? redactJsonValue(model.samplingParams) : null,
93
+ compat: model.compat ? redactJsonValue(model.compat) : null,
94
+ thinkingLevelMap: model.thinkingLevelMap ?? null,
95
+ headerNames: Object.keys(model.headers ?? {}).sort(),
96
+ };
97
+ }
98
+ function describeProvider(modelRuntime, provider) {
99
+ const authTypes = [];
100
+ if (provider.auth.apiKey)
101
+ authTypes.push("api_key");
102
+ if (provider.auth.oauth)
103
+ authTypes.push("oauth");
104
+ return {
105
+ id: provider.id,
106
+ name: provider.name,
107
+ baseUrl: provider.baseUrl ? redactUrl(provider.baseUrl) : null,
108
+ headerNames: Object.keys(provider.headers ?? {}).sort(),
109
+ authTypes,
110
+ authStatus: modelRuntime.getProviderAuthStatus(provider.id),
111
+ usingOAuth: modelRuntime.isUsingOAuth(provider.id),
112
+ registeredByExtension: modelRuntime.getRegisteredProviderIds().includes(provider.id),
113
+ };
114
+ }
115
+ function describeExtension(extension) {
116
+ return {
117
+ path: extension.path,
118
+ source: redactUrl(extension.sourceInfo.source),
119
+ scope: extension.sourceInfo.scope,
120
+ origin: extension.sourceInfo.origin,
121
+ hidden: extension.hidden === true,
122
+ };
123
+ }
124
+ export function collectBugReportMetadata(options) {
125
+ const hint = options.hint?.trim() || null;
126
+ const provider = options.model ? options.modelRuntime.getProvider(options.model.provider) : undefined;
127
+ return {
128
+ schemaVersion: BUG_REPORT_SCHEMA_VERSION,
129
+ id: options.id ?? uuidv7(),
130
+ createdAt: new Date().toISOString(),
131
+ hint,
132
+ environment: collectEnvironment(),
133
+ session: {
134
+ id: options.sessionId,
135
+ included: options.includeSession,
136
+ summaryIncluded: options.includeSummary,
137
+ messageCount: options.messageCount,
138
+ ...(options.includeSession ? { cwd: options.cwd } : {}),
139
+ },
140
+ model: options.model ? describeModel(options.model) : null,
141
+ provider: provider ? describeProvider(options.modelRuntime, provider) : null,
142
+ thinkingLevel: options.thinkingLevel,
143
+ extensions: options.extensions.map(describeExtension),
144
+ extensionErrors: options.extensionErrors.map(({ path, error }) => ({ path, error })),
145
+ settings: {
146
+ global: redactSettings(options.globalSettings),
147
+ project: redactSettings(options.projectSettings),
148
+ },
149
+ };
150
+ }
151
+ /** Collect failed assistant turns without collecting conversation content. */
152
+ export function collectBugReportDiagnostics(sessionManager, crashes = []) {
153
+ const entries = sessionManager.getEntries();
154
+ const assistant = [];
155
+ let assistantMessageCount = 0;
156
+ for (const entry of entries) {
157
+ if (entry.type !== "message" || entry.message.role !== "assistant")
158
+ continue;
159
+ assistantMessageCount++;
160
+ const message = entry.message;
161
+ const diagnostics = message.diagnostics ?? [];
162
+ if (diagnostics.length === 0 &&
163
+ message.stopReason !== "error" &&
164
+ message.stopReason !== "aborted" &&
165
+ !message.errorMessage) {
166
+ continue;
167
+ }
168
+ assistant.push({
169
+ entryId: entry.id,
170
+ timestamp: entry.timestamp,
171
+ provider: message.provider,
172
+ model: message.model,
173
+ api: message.api,
174
+ stopReason: message.stopReason,
175
+ ...(message.rawStopReason === undefined ? {} : { rawStopReason: message.rawStopReason }),
176
+ ...(message.errorMessage === undefined ? {} : { errorMessage: message.errorMessage }),
177
+ diagnostics,
178
+ });
179
+ }
180
+ return {
181
+ schemaVersion: BUG_REPORT_SCHEMA_VERSION,
182
+ sessionId: sessionManager.getSessionId(),
183
+ entryCount: entries.length,
184
+ assistantMessageCount,
185
+ assistant,
186
+ crashes: crashes.map(({ notified: _notified, ...record }) => record),
187
+ };
188
+ }
189
+ /** Files shared by upload and zip export. */
190
+ export function bugReportFiles(bundle) {
191
+ const files = [
192
+ { name: "report.json", contentType: "application/json", data: `${JSON.stringify(bundle.metadata, null, 2)}\n` },
193
+ {
194
+ name: "diagnostics.json",
195
+ contentType: "application/json",
196
+ data: `${JSON.stringify(bundle.diagnostics, null, 2)}\n`,
197
+ },
198
+ ];
199
+ if (bundle.sessionJsonl !== undefined) {
200
+ files.push({ name: "session.jsonl", contentType: "application/x-ndjson", data: bundle.sessionJsonl });
201
+ }
202
+ if (bundle.summary !== undefined) {
203
+ files.push({
204
+ name: "summary.md",
205
+ contentType: "text/markdown",
206
+ data: bundle.summary.endsWith("\n") ? bundle.summary : `${bundle.summary}\n`,
207
+ });
208
+ }
209
+ return files;
210
+ }
211
+ export function writeBugReportArchive(bundle, filePath) {
212
+ return writeZipArchive(filePath, bugReportFiles(bundle));
213
+ }
214
+ export function bugReportArchiveFileName(id) {
215
+ return `pi-bug-report-${id}.zip`;
216
+ }
217
+ const BUG_SUMMARY_SYSTEM_PROMPT = `You are helping a user file a bug report about pi, the coding agent they are talking to. You will be shown the conversation transcript. Write a report for the pi developers describing what the user was doing and what went wrong.
218
+
219
+ Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the report.`;
220
+ const BUG_SUMMARY_INSTRUCTIONS = `Write the bug report in Markdown with these sections:
221
+
222
+ ## What the user was doing
223
+ One short paragraph.
224
+
225
+ ## What went wrong
226
+ Concrete description of the failure: wrong output, errors, hangs, tool failures, unexpected behavior. Quote error messages and tool output verbatim where they exist.
227
+
228
+ ## Steps to reproduce
229
+ Numbered list, as specific as the transcript allows.
230
+
231
+ ## Relevant details
232
+ Tool calls involved, files touched, model behavior, anything else that helps a developer reproduce or locate the problem.
233
+
234
+ Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.`;
235
+ function selectMessages(messages, tokenBudget) {
236
+ const selected = [];
237
+ let tokens = 0;
238
+ for (let index = messages.length - 1; index >= 0; index--) {
239
+ const message = messages[index];
240
+ const next = estimateTokens(message);
241
+ if (selected.length > 0 && tokens + next > tokenBudget)
242
+ break;
243
+ selected.push(message);
244
+ tokens += next;
245
+ }
246
+ return selected.reverse();
247
+ }
248
+ /** Ask the session model for a report when the user does not share the transcript. */
249
+ export async function generateBugReportSummary(options) {
250
+ const { model } = options;
251
+ const contextWindow = model.contextWindow > 0 ? model.contextWindow : 128_000;
252
+ const messages = selectMessages(options.messages, Math.floor(contextWindow * 0.6));
253
+ const hint = options.hint?.trim();
254
+ const prompt = [
255
+ messages.length < options.messages.length
256
+ ? `Note: only the last ${messages.length} of ${options.messages.length} messages are shown.`
257
+ : undefined,
258
+ `<conversation>\n${serializeConversation(convertToLlm(messages))}\n</conversation>`,
259
+ hint ? `<user-report>\n${hint}\n</user-report>` : undefined,
260
+ BUG_SUMMARY_INSTRUCTIONS,
261
+ ]
262
+ .filter((part) => part !== undefined)
263
+ .join("\n\n");
264
+ const requestOptions = {
265
+ maxTokens: Math.min(4096, model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY),
266
+ signal: options.signal,
267
+ apiKey: options.apiKey,
268
+ headers: options.headers,
269
+ env: options.env,
270
+ sessionId: options.sessionId,
271
+ ...(model.reasoning && options.thinkingLevel && options.thinkingLevel !== "off"
272
+ ? { reasoning: options.thinkingLevel }
273
+ : {}),
274
+ };
275
+ const response = await completeSummarization(model, normalizeContext({
276
+ systemPrompt: BUG_SUMMARY_SYSTEM_PROMPT,
277
+ messages: [{ role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() }],
278
+ }), requestOptions, options.streamFn, options.retry);
279
+ if (response.stopReason === "aborted")
280
+ throw new Error("Bug report summary was cancelled");
281
+ const failure = getSummarizationFailure(response, "Bug report summary");
282
+ if (failure)
283
+ throw new Error(failure);
284
+ if (response.content.some((block) => block.type === "toolCall")) {
285
+ throw new Error("Bug report summary attempted to call a tool");
286
+ }
287
+ const text = contentText(response.content).trim();
288
+ if (!text)
289
+ throw new Error("Bug report summary was empty");
290
+ return text;
291
+ }
@@ -63,7 +63,18 @@ function scan(entries, models) {
63
63
  prev = undefined;
64
64
  continue;
65
65
  }
66
- if (entry.type === "message" && entry.message.role === "assistant") {
66
+ if (entry.type === "usage" && entry.kind === "cache_warm") {
67
+ const promptTokens = entry.usage.input + entry.usage.cacheRead + entry.usage.cacheWrite;
68
+ if (promptTokens > 0) {
69
+ prev = {
70
+ promptTokens,
71
+ modelKey: `${entry.provider}/${entry.model}`,
72
+ timestamp: Date.parse(entry.timestamp),
73
+ reportedCache: true,
74
+ };
75
+ }
76
+ }
77
+ else if (entry.type === "message" && entry.message.role === "assistant") {
67
78
  const miss = detectMiss(prev, entry.message, models);
68
79
  if (miss) {
69
80
  totals.missedTokens += miss.missedTokens;
@@ -0,0 +1,101 @@
1
+ import { type Api, type Context, type Model, type ModelsSimpleStreamOptions, type SimpleStreamOptions } from "@earendil-works/pi-ai";
2
+ import type { ModelRuntime } from "./model-runtime.ts";
3
+ import type { SessionManager, UsageEntry } from "./session-manager.ts";
4
+ import type { CacheWarmingMode } from "./settings-manager.ts";
5
+ /** Refresh at 90% of the TTL while preserving at least ten seconds of margin. */
6
+ export declare function getCacheWarmingDelayMs(ttlMs: number): number | undefined;
7
+ /**
8
+ * Lifetime of the prompt cache entry a request writes, from the model's
9
+ * `promptCache` tier for the retention the request used. Undefined when the
10
+ * model has no lifetime for that tier or caching is off.
11
+ */
12
+ export declare function getPromptCacheTtlMs(model: Model<Api>, options: SimpleStreamOptions | undefined): number | undefined;
13
+ /**
14
+ * Whether replaying the request with a one-token output cap leaves its cache
15
+ * entry untouched. Anthropic's budget-based thinking (Claude models without
16
+ * adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay
17
+ * would get a different budget, which Anthropic keys the message cache on,
18
+ * and the model could still think for thousands of tokens.
19
+ */
20
+ export declare function isReplayable(model: Model<Api>, options: SimpleStreamOptions | undefined): boolean;
21
+ export type CacheWarmingAction = "warm" | "stop";
22
+ /** Inputs and outcome of one warm-or-stop decision, as shown by `/session`. */
23
+ export interface CacheWarmingDecision {
24
+ /** "streaming" while the agent run that sent the request is still active. */
25
+ phase: "streaming" | "idle";
26
+ /** Price of this refresh: a cache read of the prompt plus one output token. */
27
+ warmCost: number;
28
+ /** Extra price of the next real request if the cache entry is lost. */
29
+ missCost: number;
30
+ /** Estimated chance that a real request arrives before the entry expires. */
31
+ continuationProbability: number;
32
+ /** `continuationProbability * missCost - warmCost`. */
33
+ expectedSavings: number;
34
+ /** False when the prompt size or the model's prices are unknown. */
35
+ economicsAvailable: boolean;
36
+ /** Pi's decision: "warm" when `expectedSavings` is at least $0.05. */
37
+ action: CacheWarmingAction;
38
+ }
39
+ /**
40
+ * Fired before each refresh with pi's decision filled in. Everything else an
41
+ * extension might want (model, idle state, context size) is on the context.
42
+ */
43
+ export interface CacheWarmingDecisionEvent extends Pick<CacheWarmingDecision, "warmCost" | "missCost" | "continuationProbability" | "action"> {
44
+ type: "cache_warming_decision";
45
+ }
46
+ export interface CacheWarmingDecisionEventResult {
47
+ /** Override whether this refresh is sent. "stop" ends warming until the next real request. */
48
+ action?: CacheWarmingAction;
49
+ }
50
+ export interface CacheWarmingStatus {
51
+ /** "scheduled": a refresh timer is armed; "refreshing": a warm request is in flight. */
52
+ state: "inactive" | "scheduled" | "refreshing";
53
+ /** Why nothing is scheduled. */
54
+ reason?: string;
55
+ nextWarmAt?: number;
56
+ /** The pending decision, or the decision that stopped warming. */
57
+ decision?: CacheWarmingDecision;
58
+ /** True when an extension changed `decision.action`. */
59
+ extensionOverride?: boolean;
60
+ }
61
+ /** The request whose prompt cache entry should be kept warm, exactly as it was sent. */
62
+ export interface CacheWarmRequest {
63
+ model: Model<Api>;
64
+ context: Context;
65
+ options: ModelsSimpleStreamOptions;
66
+ }
67
+ /**
68
+ * Keeps one prompt cache entry alive by re-sending its request with a
69
+ * one-token output cap before the entry expires. `start` replaces any
70
+ * previous run; warm requests never extend the fixed safety windows.
71
+ */
72
+ export declare class CacheWarmer {
73
+ private run?;
74
+ private inactive;
75
+ private readonly models;
76
+ private readonly sessionManager;
77
+ private readonly getMode;
78
+ /** Lets extensions override `event.action`; failures fall back to pi's decision. */
79
+ private readonly decide;
80
+ /** Called with the persisted usage entry after each successful refresh. */
81
+ onWarmed?: (entry: UsageEntry) => void;
82
+ constructor(models: Pick<ModelRuntime, "streamSimple">, sessionManager: Pick<SessionManager, "appendUsage" | "getBranch">, getMode: () => CacheWarmingMode, decide?: (event: CacheWarmingDecisionEvent) => Promise<CacheWarmingAction>);
83
+ get status(): CacheWarmingStatus;
84
+ /** Keep the prompt cache entry written by `request` warm while `isCurrent` holds. */
85
+ start(request: CacheWarmRequest, isCurrent: () => boolean): void;
86
+ onAgentSettled(): void;
87
+ /** Reconcile an active run after the persisted warming mode changes. */
88
+ onModeChanged(): void;
89
+ cancel(): void;
90
+ private clearRun;
91
+ private stop;
92
+ private schedule;
93
+ private refresh;
94
+ private validateRun;
95
+ private getModeStopReason;
96
+ private evaluate;
97
+ }
98
+ /** One-line status for `/session`. */
99
+ export declare function formatCacheWarmingStatus(status: CacheWarmingStatus, now?: number): string;
100
+ /** One-line transcript text for persisted cache-warming usage. */
101
+ export declare function formatCacheWarmingUsage(entry: UsageEntry): string;