@farazirfan/costar-server-executor 1.7.2 → 1.7.5

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 (30) hide show
  1. package/dist/agent/pi-embedded-helpers/errors.d.ts +35 -0
  2. package/dist/agent/pi-embedded-helpers/errors.d.ts.map +1 -0
  3. package/dist/agent/pi-embedded-helpers/errors.js +89 -0
  4. package/dist/agent/pi-embedded-helpers/errors.js.map +1 -0
  5. package/dist/agent/pi-embedded-runner/compact.d.ts +45 -0
  6. package/dist/agent/pi-embedded-runner/compact.d.ts.map +1 -0
  7. package/dist/agent/pi-embedded-runner/compact.js +176 -0
  8. package/dist/agent/pi-embedded-runner/compact.js.map +1 -0
  9. package/dist/agent/pi-embedded-runner/run.d.ts +17 -0
  10. package/dist/agent/pi-embedded-runner/run.d.ts.map +1 -1
  11. package/dist/agent/pi-embedded-runner/run.js +176 -30
  12. package/dist/agent/pi-embedded-runner/run.js.map +1 -1
  13. package/dist/agent/pi-embedded-runner/tool-result-truncation.d.ts +72 -0
  14. package/dist/agent/pi-embedded-runner/tool-result-truncation.d.ts.map +1 -0
  15. package/dist/agent/pi-embedded-runner/tool-result-truncation.js +281 -0
  16. package/dist/agent/pi-embedded-runner/tool-result-truncation.js.map +1 -0
  17. package/dist/agent/pi-embedded-runner/types.d.ts +25 -0
  18. package/dist/agent/pi-embedded-runner/types.d.ts.map +1 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +8 -5
  21. package/dist/index.js.map +1 -1
  22. package/dist/tools/fetch-api-data.d.ts +15 -4
  23. package/dist/tools/fetch-api-data.d.ts.map +1 -1
  24. package/dist/tools/fetch-api-data.js +169 -81
  25. package/dist/tools/fetch-api-data.js.map +1 -1
  26. package/dist/tools/index.d.ts +5 -5
  27. package/dist/tools/index.d.ts.map +1 -1
  28. package/dist/tools/index.js +8 -7
  29. package/dist/tools/index.js.map +1 -1
  30. package/package.json +1 -1
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Error classification helpers for context overflow and compaction failures.
3
+ * Ported from OpenClaw's pi-embedded-helpers/errors.ts
4
+ */
5
+ /**
6
+ * Detect context overflow errors from API error messages.
7
+ * Matches known error patterns from Anthropic, OpenAI, and other providers.
8
+ *
9
+ * (Ported from OpenClaw — exact pattern matching)
10
+ */
11
+ export declare function isContextOverflowError(errorMessage?: string): boolean;
12
+ /**
13
+ * Fuzzy context overflow detection using regex patterns.
14
+ * Catches edge cases that isContextOverflowError misses.
15
+ * Excludes "context window too small" errors.
16
+ *
17
+ * (Ported from OpenClaw)
18
+ */
19
+ export declare function isLikelyContextOverflowError(errorMessage?: string): boolean;
20
+ /**
21
+ * Detect compaction-specific failure errors.
22
+ * These occur when the compaction/summarization process itself fails
23
+ * (e.g., the summary prompt is also too large).
24
+ *
25
+ * Important: compaction failures should NOT trigger another compaction retry.
26
+ *
27
+ * (Ported from OpenClaw)
28
+ */
29
+ export declare function isCompactionFailureError(errorMessage?: string): boolean;
30
+ /**
31
+ * Describe an unknown error as a string.
32
+ * (Simplified from OpenClaw's describeUnknownError)
33
+ */
34
+ export declare function describeUnknownError(err: unknown): string;
35
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/agent/pi-embedded-helpers/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAwBrE;AAMD;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAW3E;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAgBvE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAKzD"}
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Error classification helpers for context overflow and compaction failures.
3
+ * Ported from OpenClaw's pi-embedded-helpers/errors.ts
4
+ */
5
+ /**
6
+ * Detect context overflow errors from API error messages.
7
+ * Matches known error patterns from Anthropic, OpenAI, and other providers.
8
+ *
9
+ * (Ported from OpenClaw — exact pattern matching)
10
+ */
11
+ export function isContextOverflowError(errorMessage) {
12
+ if (!errorMessage) {
13
+ return false;
14
+ }
15
+ const lower = errorMessage.toLowerCase();
16
+ const hasRequestSizeExceeds = lower.includes("request size exceeds");
17
+ const hasContextWindow = lower.includes("context window") ||
18
+ lower.includes("context length") ||
19
+ lower.includes("maximum context length");
20
+ return (lower.includes("request_too_large") ||
21
+ lower.includes("request exceeds the maximum size") ||
22
+ lower.includes("context length exceeded") ||
23
+ lower.includes("maximum context length") ||
24
+ lower.includes("prompt is too long") ||
25
+ lower.includes("exceeds model context window") ||
26
+ (hasRequestSizeExceeds && hasContextWindow) ||
27
+ lower.includes("context overflow:") ||
28
+ (lower.includes("413") && lower.includes("too large")) ||
29
+ // Anthropic-specific: "input length and `max_tokens` exceed context limit"
30
+ (lower.includes("input length") && lower.includes("exceed") && lower.includes("context limit")) ||
31
+ (lower.includes("max_tokens") && lower.includes("exceed") && lower.includes("context limit")));
32
+ }
33
+ const CONTEXT_WINDOW_TOO_SMALL_RE = /context window.*(too small|minimum is)/i;
34
+ const CONTEXT_OVERFLOW_HINT_RE = /context.*overflow|context window.*(too (?:large|long)|exceed|over|limit|max(?:imum)?|requested|sent|tokens)|(?:prompt|request|input).*(too (?:large|long)|exceed|over|limit|max(?:imum)?)/i;
35
+ /**
36
+ * Fuzzy context overflow detection using regex patterns.
37
+ * Catches edge cases that isContextOverflowError misses.
38
+ * Excludes "context window too small" errors.
39
+ *
40
+ * (Ported from OpenClaw)
41
+ */
42
+ export function isLikelyContextOverflowError(errorMessage) {
43
+ if (!errorMessage) {
44
+ return false;
45
+ }
46
+ if (CONTEXT_WINDOW_TOO_SMALL_RE.test(errorMessage)) {
47
+ return false;
48
+ }
49
+ if (isContextOverflowError(errorMessage)) {
50
+ return true;
51
+ }
52
+ return CONTEXT_OVERFLOW_HINT_RE.test(errorMessage);
53
+ }
54
+ /**
55
+ * Detect compaction-specific failure errors.
56
+ * These occur when the compaction/summarization process itself fails
57
+ * (e.g., the summary prompt is also too large).
58
+ *
59
+ * Important: compaction failures should NOT trigger another compaction retry.
60
+ *
61
+ * (Ported from OpenClaw)
62
+ */
63
+ export function isCompactionFailureError(errorMessage) {
64
+ if (!errorMessage) {
65
+ return false;
66
+ }
67
+ const lower = errorMessage.toLowerCase();
68
+ const hasCompactionTerm = lower.includes("summarization failed") ||
69
+ lower.includes("auto-compaction") ||
70
+ lower.includes("compaction failed") ||
71
+ lower.includes("compaction");
72
+ if (!hasCompactionTerm) {
73
+ return false;
74
+ }
75
+ // For compaction failures, also accept "context overflow" without colon
76
+ // since the error message itself describes a compaction/summarization failure
77
+ return isContextOverflowError(errorMessage) || lower.includes("context overflow");
78
+ }
79
+ /**
80
+ * Describe an unknown error as a string.
81
+ * (Simplified from OpenClaw's describeUnknownError)
82
+ */
83
+ export function describeUnknownError(err) {
84
+ if (err instanceof Error) {
85
+ return err.message;
86
+ }
87
+ return String(err);
88
+ }
89
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/agent/pi-embedded-helpers/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,YAAqB;IAC1D,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,KAAK,GAAG,YAAY,CAAC,WAAW,EAAE,CAAC;IACzC,MAAM,qBAAqB,GAAG,KAAK,CAAC,QAAQ,CAAC,sBAAsB,CAAC,CAAC;IACrE,MAAM,gBAAgB,GACpB,KAAK,CAAC,QAAQ,CAAC,gBAAgB,CAAC;QA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AAY,CAAC,EAAE,CAAC;QACzC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,wBAAwB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AACrD,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,wBAAwB,CAAC,YAAqB;IAC5D,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,KAAK,GAAG,YAAY,CAAC,WAAW,EAAE,CAAC;IACzC,MAAM,iBAAiB,GACrB,KAAK,CAAC,QAAQ,CAAC,sBAAsB,CAAC;QACtC,KAAK,CAAC,QAAQ,CAAC,iBAAiB,CAAC;QACjC,KAAK,CAAC,QAAQ,CAAC,mBAAmB,CAAC;QACnC,KAAK,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;IAC/B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,wEAAwE;IACxE,8EAA8E;IAC9E,OAAO,sBAAsB,CAAC,YAAY,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC;AACpF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,GAAY;IAC/C,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;QACzB,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;IACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;AACrB,CAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Session compaction — calls session.compact() directly.
3
+ * Ported from OpenClaw's pi-embedded-runner/compact.ts (simplified for CoStar).
4
+ *
5
+ * Key difference from our previous forceCompactSession:
6
+ * - Uses session.compact(customInstructions) instead of sending a summarization prompt
7
+ * - Returns structured EmbeddedPiCompactResult instead of a boolean
8
+ * - Estimates tokensAfter using estimateTokens
9
+ */
10
+ import type { EmbeddedPiCompactResult, RunEmbeddedPiAgentParams } from "./types.js";
11
+ /**
12
+ * Parameters for compactEmbeddedPiSessionDirect.
13
+ * Subset of RunEmbeddedPiAgentParams with compaction-specific additions.
14
+ */
15
+ export type CompactEmbeddedPiSessionParams = {
16
+ sessionId: string;
17
+ sessionKey?: string;
18
+ sessionFile: string;
19
+ workspaceDir: string;
20
+ agentDir?: string;
21
+ config?: RunEmbeddedPiAgentParams["config"];
22
+ provider?: string;
23
+ model?: string;
24
+ thinkLevel?: "off" | "brief" | "full";
25
+ customInstructions?: string;
26
+ authProfileId?: string;
27
+ extraSystemPrompt?: string;
28
+ skillEntries?: Array<{
29
+ name: string;
30
+ description: string;
31
+ filePath: string;
32
+ }>;
33
+ };
34
+ /**
35
+ * Core compaction logic — opens session, creates agent, calls session.compact().
36
+ *
37
+ * Simplified from OpenClaw's compactEmbeddedPiSessionDirect:
38
+ * - No lane queueing (CoStar doesn't use lanes)
39
+ * - No sandbox resolution (CoStar runs in a single sandbox)
40
+ * - No channel/skills/bootstrap resolution (not needed for compaction)
41
+ *
42
+ * @returns Structured result with compaction details
43
+ */
44
+ export declare function compactEmbeddedPiSessionDirect(params: CompactEmbeddedPiSessionParams): Promise<EmbeddedPiCompactResult>;
45
+ //# sourceMappingURL=compact.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compact.d.ts","sourceRoot":"","sources":["../../../src/agent/pi-embedded-runner/compact.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAUH,OAAO,KAAK,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AA8BpF;;;GAGG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,wBAAwB,CAAC,QAAQ,CAAC,CAAC;IAC5C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,KAAK,GAAG,OAAO,GAAG,MAAM,CAAC;IACtC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC/E,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAClD,MAAM,EAAE,8BAA8B,GACrC,OAAO,CAAC,uBAAuB,CAAC,CAgJlC"}
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Session compaction — calls session.compact() directly.
3
+ * Ported from OpenClaw's pi-embedded-runner/compact.ts (simplified for CoStar).
4
+ *
5
+ * Key difference from our previous forceCompactSession:
6
+ * - Uses session.compact(customInstructions) instead of sending a summarization prompt
7
+ * - Returns structured EmbeddedPiCompactResult instead of a boolean
8
+ * - Estimates tokensAfter using estimateTokens
9
+ */
10
+ import fs from "node:fs/promises";
11
+ import os from "node:os";
12
+ import { createAgentSession, estimateTokens, SessionManager, SettingsManager, } from "@mariozechner/pi-coding-agent";
13
+ import { resolveModel, DEFAULT_PROVIDER, DEFAULT_MODEL } from "./model.js";
14
+ import { getCustomTools } from "./tools.js";
15
+ import { buildAgentSystemPrompt, createSystemPromptOverride } from "./system-prompt.js";
16
+ import { describeUnknownError } from "../pi-embedded-helpers/errors.js";
17
+ /**
18
+ * Default compaction reserve tokens — minimum tokens to keep after compaction.
19
+ * Matches OpenClaw's DEFAULT_COMPACTION_RESERVE_TOKENS.
20
+ */
21
+ const DEFAULT_COMPACTION_RESERVE_TOKENS = 20_000;
22
+ /**
23
+ * Map thinking level to pi-ai format.
24
+ */
25
+ function mapThinkingLevel(level) {
26
+ switch (level) {
27
+ case "off":
28
+ return "off";
29
+ case "brief":
30
+ return "minimal";
31
+ case "full":
32
+ return "medium";
33
+ default:
34
+ return "off";
35
+ }
36
+ }
37
+ /**
38
+ * Core compaction logic — opens session, creates agent, calls session.compact().
39
+ *
40
+ * Simplified from OpenClaw's compactEmbeddedPiSessionDirect:
41
+ * - No lane queueing (CoStar doesn't use lanes)
42
+ * - No sandbox resolution (CoStar runs in a single sandbox)
43
+ * - No channel/skills/bootstrap resolution (not needed for compaction)
44
+ *
45
+ * @returns Structured result with compaction details
46
+ */
47
+ export async function compactEmbeddedPiSessionDirect(params) {
48
+ const resolvedWorkspace = params.workspaceDir;
49
+ const provider = (params.provider ?? DEFAULT_PROVIDER).trim() || DEFAULT_PROVIDER;
50
+ const modelId = (params.model ?? DEFAULT_MODEL).trim() || DEFAULT_MODEL;
51
+ const agentDir = params.agentDir ?? process.cwd();
52
+ // Resolve model and auth
53
+ const { model, error, authStorage, modelRegistry } = resolveModel(provider, modelId, agentDir, params.config);
54
+ if (!model) {
55
+ return {
56
+ ok: false,
57
+ compacted: false,
58
+ reason: error ?? `Unknown model: ${provider}/${modelId}`,
59
+ };
60
+ }
61
+ try {
62
+ await fs.mkdir(resolvedWorkspace, { recursive: true });
63
+ // Ensure session file directory exists
64
+ const sessionFileDir = params.sessionFile.substring(0, params.sessionFile.lastIndexOf("/"));
65
+ if (sessionFileDir) {
66
+ await fs.mkdir(sessionFileDir, { recursive: true });
67
+ }
68
+ // Open session manager
69
+ const sessionManager = SessionManager.open(params.sessionFile);
70
+ const settingsManager = SettingsManager.create(resolvedWorkspace, agentDir);
71
+ // Ensure compaction reserve tokens are set
72
+ const currentReserveTokens = settingsManager.getCompactionReserveTokens();
73
+ if (currentReserveTokens < DEFAULT_COMPACTION_RESERVE_TOKENS) {
74
+ settingsManager.applyOverrides({
75
+ compaction: { reserveTokens: DEFAULT_COMPACTION_RESERVE_TOKENS },
76
+ });
77
+ }
78
+ // Build minimal system prompt for compaction context
79
+ const systemPromptText = buildAgentSystemPrompt({
80
+ workspaceDir: resolvedWorkspace,
81
+ config: params.config,
82
+ extraSystemPrompt: params.extraSystemPrompt,
83
+ promptMode: "full",
84
+ thinkLevel: params.thinkLevel,
85
+ runtimeInfo: {
86
+ host: os.hostname(),
87
+ os: `${os.type()} ${os.release()}`,
88
+ arch: os.arch(),
89
+ node: process.version,
90
+ model: `${provider}/${modelId}`,
91
+ provider,
92
+ },
93
+ userTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
94
+ userTime: new Date().toISOString(),
95
+ skills: params.skillEntries,
96
+ });
97
+ const systemPrompt = createSystemPromptOverride(systemPromptText);
98
+ const customTools = getCustomTools();
99
+ // Create agent session
100
+ const { session } = await createAgentSession({
101
+ cwd: resolvedWorkspace,
102
+ agentDir,
103
+ authStorage,
104
+ modelRegistry,
105
+ model,
106
+ thinkingLevel: mapThinkingLevel(params.thinkLevel ?? "off"),
107
+ systemPrompt,
108
+ tools: [],
109
+ customTools,
110
+ sessionManager,
111
+ settingsManager,
112
+ skills: [],
113
+ contextFiles: [],
114
+ additionalExtensionPaths: [],
115
+ });
116
+ if (!session) {
117
+ return {
118
+ ok: false,
119
+ compacted: false,
120
+ reason: "Failed to create agent session for compaction",
121
+ };
122
+ }
123
+ try {
124
+ // Call session.compact() — the pi-coding-agent's built-in compaction
125
+ // This generates a summary of older messages and keeps recent ones
126
+ const result = await session.compact(params.customInstructions);
127
+ // Estimate tokens after compaction
128
+ let tokensAfter;
129
+ try {
130
+ tokensAfter = 0;
131
+ for (const message of session.messages) {
132
+ tokensAfter += estimateTokens(message);
133
+ }
134
+ // Sanity check: tokensAfter should be less than tokensBefore
135
+ if (tokensAfter > result.tokensBefore) {
136
+ tokensAfter = undefined;
137
+ }
138
+ }
139
+ catch {
140
+ tokensAfter = undefined;
141
+ }
142
+ console.log(`[COMPACT] Session ${params.sessionId} compacted: ` +
143
+ `${result.tokensBefore} → ${tokensAfter ?? "?"} tokens`);
144
+ return {
145
+ ok: true,
146
+ compacted: true,
147
+ result: {
148
+ summary: result.summary,
149
+ firstKeptEntryId: result.firstKeptEntryId,
150
+ tokensBefore: result.tokensBefore,
151
+ tokensAfter,
152
+ details: result.details,
153
+ },
154
+ };
155
+ }
156
+ finally {
157
+ try {
158
+ sessionManager.flushPendingToolResults?.();
159
+ session.dispose();
160
+ }
161
+ catch {
162
+ /* ignore dispose errors */
163
+ }
164
+ }
165
+ }
166
+ catch (err) {
167
+ const reason = describeUnknownError(err);
168
+ console.error(`[COMPACT] Compaction failed for session ${params.sessionId}: ${reason}`);
169
+ return {
170
+ ok: false,
171
+ compacted: false,
172
+ reason,
173
+ };
174
+ }
175
+ }
176
+ //# sourceMappingURL=compact.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compact.js","sourceRoot":"","sources":["../../../src/agent/pi-embedded-runner/compact.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,eAAe,GAChB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,sBAAsB,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AACxF,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AAExE;;;GAGG;AACH,MAAM,iCAAiC,GAAG,MAAM,CAAC;AAEjD;;GAEG;AACH,SAAS,gBAAgB,CACvB,KAA+B;IAE/B,QAAQ,KAAK,EAAE,CAAC;QACd,KAAK,KAAK;YACR,OAAO,KAAK,CAAC;QACf,KAAK,OAAO;YACV,OAAO,SAAS,CAAC;QACnB,KAAK,MAAM;YACT,OAAO,QAAQ,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,OAAO,EAAE,MAAM,CAAC,OAAO;oBACvB,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;oBACzC,YAAY,EAAE,MAAM,CAAC,YAAY;oBACjC,WAAW;oBACX,OAAO,EAAE,MAAM,CAAC,OAAO;iBACxB;aACF,CAAC;QACJ,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC;gBACF,cAAsB,CAAC,uBAAuB,EAAE,EAAE,CAAC;gBACpD,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,CAAC;YAAC,MAAM,CAAC;gBACP,2BAA2B;YAC7B,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,MAAM,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;QACzC,OAAO,CAAC,KAAK,CAAC,2CAA2C,MAAM,CAAC,SAAS,KAAK,MAAM,EAAE,CAAC,CAAC;QACxF,OAAO;YACL,EAAE,EAAE,KAAK;YACT,SAAS,EAAE,KAAK;YAChB,MAAM;SACP,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -1,10 +1,27 @@
1
1
  /**
2
2
  * Embedded Pi Agent Runner (based on OpenClaw's pi-embedded-runner/run.ts)
3
3
  * This is the main agent execution function that uses @mariozechner/pi-ai
4
+ *
5
+ * Overflow recovery flow (ported from OpenClaw lines 386-598):
6
+ * 1. Detect overflow from promptError or assistantErrorText
7
+ * 2. Check isCompactionFailureError — skip retry for compaction failures
8
+ * 3. Call compactEmbeddedPiSessionDirect up to MAX_OVERFLOW_COMPACTION_ATTEMPTS times
9
+ * 4. Fall back to truncateOversizedToolResultsInSession if compaction fails
10
+ * 5. Reset session file as absolute last resort (CoStar-specific)
4
11
  */
5
12
  import type { RunEmbeddedPiAgentParams, EmbeddedPiRunResult } from "./types.js";
13
+ export { isContextOverflowError } from "../pi-embedded-helpers/errors.js";
6
14
  /**
7
15
  * Run embedded pi agent (matches OpenClaw's architecture)
16
+ *
17
+ * Includes context overflow detection, auto-compaction, tool result truncation,
18
+ * and session reset as last resort.
19
+ * (Ported from OpenClaw's run.ts lines 386-598)
8
20
  */
9
21
  export declare function runEmbeddedPiAgent(params: RunEmbeddedPiAgentParams): Promise<EmbeddedPiRunResult>;
22
+ /**
23
+ * Reset session file to empty state.
24
+ * Backs up the old session first in case it's needed.
25
+ */
26
+ export declare function resetSessionFile(sessionFile: string): Promise<void>;
10
27
  //# sourceMappingURL=run.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../../src/agent/pi-embedded-runner/run.ts"],"names":[],"mappings":"AAAA;;;GAGG;AASH,OAAO,KAAK,EACV,wBAAwB,EACxB,mBAAmB,EAEpB,MAAM,YAAY,CAAC;AAMpB;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,wBAAwB,GAC/B,OAAO,CAAC,mBAAmB,CAAC,CA0E9B"}
1
+ {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../../src/agent/pi-embedded-runner/run.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AASH,OAAO,KAAK,EACV,wBAAwB,EACxB,mBAAmB,EAEpB,MAAM,YAAY,CAAC;AAiBpB,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAQ1E;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,wBAAwB,GAC/B,OAAO,CAAC,mBAAmB,CAAC,CAiN9B;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAiBzE"}