@narumitw/pi-goal 0.54.5 → 0.54.6

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 @@ var RETRYABLE_GOAL_ERROR_PATTERNS = [
86
86
  /overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
87
87
  /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
88
88
  /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
89
- /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,
89
+ /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream (?:ended|closed|terminated) before|premature (?:close|end)|incomplete (?:stream|response)|unexpected end of (?:stream|response)|http2 request did not get a response|retry delay/i,
90
90
  /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i
91
91
  ];
92
92
  function safeTerminalText(value) {
@@ -340,4 +340,4 @@ export {
340
340
  saveGoalSettings,
341
341
  readGoalSettings
342
342
  };
343
- //# sourceMappingURL=chunk-WQIA35U2.js.map
343
+ //# sourceMappingURL=chunk-6T3MHA45.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/accounting.ts", "../../src/errors.ts", "../../src/settings.ts"],
4
- "sourcesContent": ["import type { Usage } from \"@earendil-works/pi-ai\";\n\nexport interface GoalAccountingState {\n status: string;\n baselineTokens: number;\n tokensUsed: number;\n timeUsedSeconds: number;\n activeStartedAt?: number;\n updatedAt: number;\n}\n\ninterface AssistantUsageEntryLike {\n type?: unknown;\n message?: unknown;\n}\n\ninterface UsageContext {\n sessionManager?: unknown;\n}\n\nexport function checkpointGoalActiveTime(goal: GoalAccountingState, now: number, continueClock: boolean) {\n const accumulated = nonNegativeFiniteNumber(goal.timeUsedSeconds);\n const startedAt = goal.activeStartedAt;\n if (typeof startedAt === \"number\" && Number.isFinite(startedAt)) {\n goal.timeUsedSeconds = accumulated + Math.max(0, now - startedAt) / 1000;\n } else {\n goal.timeUsedSeconds = accumulated;\n }\n goal.activeStartedAt = continueClock ? now : undefined;\n}\n\nexport function updateGoalUsage(\n goal: GoalAccountingState,\n ctx: UsageContext,\n continueClock = goal.status === \"active\",\n) {\n const now = Date.now();\n const baselineTokens = nonNegativeFiniteNumber(goal.baselineTokens);\n goal.baselineTokens = baselineTokens;\n goal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - baselineTokens);\n checkpointGoalActiveTime(goal, now, continueClock);\n goal.updatedAt = now;\n}\n\nexport function formatDuration(seconds: number) {\n const wholeSeconds = Math.max(0, Math.floor(nonNegativeFiniteNumber(seconds)));\n if (wholeSeconds < 60) return `${wholeSeconds}s`;\n const minutes = Math.floor(wholeSeconds / 60);\n if (minutes < 60) return `${minutes}m`;\n const hours = Math.floor(minutes / 60);\n return `${hours}h${minutes % 60}m`;\n}\n\nexport function formatTokenCount(value: number) {\n if (value < 1_000) return `${value}`;\n if (value < 1_000_000) {\n return `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;\n }\n return `${Number.isInteger(value / 1_000_000) ? value / 1_000_000 : (value / 1_000_000).toFixed(1)}m`;\n}\n\nexport function isNonNegativeFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nexport function nonNegativeFiniteNumber(value: unknown) {\n return isNonNegativeFiniteNumber(value) ? value : 0;\n}\n\nexport function normalizeTokenBudget(value: unknown) {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function assistantUsageTokens(value: unknown) {\n if (!value || typeof value !== \"object\") return 0;\n const usage = value as Partial<Usage>;\n if (isNonNegativeFiniteNumber(usage.totalTokens)) return usage.totalTokens;\n return Math.min(\n Number.MAX_SAFE_INTEGER,\n nonNegativeFiniteNumber(usage.input) +\n nonNegativeFiniteNumber(usage.output) +\n nonNegativeFiniteNumber(usage.cacheRead) +\n nonNegativeFiniteNumber(usage.cacheWrite),\n );\n}\n\nexport function cumulativeAssistantTokens(entries: unknown[]) {\n let total = 0;\n for (const entry of entries) {\n const candidate = entry as AssistantUsageEntryLike;\n if (candidate?.type !== \"message\") continue;\n const message = candidate.message as { role?: unknown; usage?: unknown } | undefined;\n if (message?.role !== \"assistant\") continue;\n total = Math.min(Number.MAX_SAFE_INTEGER, total + assistantUsageTokens(message.usage));\n }\n return total;\n}\n\nexport function currentTokenTotal(ctx: UsageContext): number {\n const sessionManager = ctx.sessionManager as { getBranch?: () => unknown[] } | undefined;\n return cumulativeAssistantTokens(sessionManager?.getBranch?.() ?? []);\n}\n", "import {\n isContextOverflow,\n isRetryableAssistantError,\n type AssistantMessage as PiAssistantMessage,\n type Usage,\n} from \"@earendil-works/pi-ai\";\nimport { stripTerminalSequences } from \"@earendil-works/pi-tui\";\nimport { assistantUsageTokens, nonNegativeFiniteNumber } from \"./accounting.js\";\n\nexport type AgentStopReason = \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\";\n\nexport interface AssistantMessageLike {\n role: \"assistant\";\n stopReason?: AgentStopReason;\n errorMessage?: string;\n content?: PiAssistantMessage[\"content\"];\n api?: PiAssistantMessage[\"api\"];\n provider?: PiAssistantMessage[\"provider\"];\n model?: string;\n usage?: Usage;\n timestamp?: number;\n}\n\nconst USAGE_LIMIT_GOAL_ERROR_PATTERNS = [\n /usage[_\\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,\n /quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,\n /insufficient[_\\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,\n /(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,\n] as const;\nconst NON_RETRYABLE_GOAL_ERROR_RE = /multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;\nconst RETRYABLE_GOAL_ERROR_PATTERNS = [\n /overloaded|rate.?limit|too many requests|\\b(?:429|500|502|503|504)\\b|service.?unavailable|server.?error|internal.?error/i,\n /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,\n /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,\n /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,\n /context[_\\s-]*length[_\\s-]*exceeded|input exceeds the context window/i,\n] as const;\n\nexport function safeTerminalText(value: string) {\n return [...stripTerminalSequences(value)]\n .map((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n if (character === \"\\n\") return character;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n })\n .join(\"\")\n .trim();\n}\n\nexport function safeGoalMenuText(value: string, maxCharacters = 120) {\n const sanitized = safeTerminalText(value).replace(/\\s+/gu, \" \").trim();\n const characters = [...sanitized];\n return characters.length <= maxCharacters ? sanitized : `${characters.slice(0, maxCharacters).join(\"\")}\u2026`;\n}\n\nexport function notifyTerminal(\n ui: { notify: (message: string, level?: \"info\" | \"warning\" | \"error\") => void },\n message: string,\n level?: \"info\" | \"warning\" | \"error\",\n) {\n ui.notify(safeTerminalText(message), level);\n}\n\n/**\n * True when an error came from an ExtensionContext invalidated by session\n * replacement or reload. Pi throws this from every ctx getter and pi method on\n * the stale runner, so deferred callbacks must treat it as cancellation.\n */\nexport function isStaleContextError(error: unknown): boolean {\n return (\n error instanceof Error && error.message.includes(\"This extension ctx is stale after session replacement or reload\")\n );\n}\n\nexport function formatError(error: unknown) {\n return truncateNotification(error instanceof Error ? error.message : String(error));\n}\n\nexport function truncateNotification(value: string) {\n const safe = [...safeTerminalText(value)];\n return safe.length > 160 ? `${safe.slice(0, 157).join(\"\")}...` : safe.join(\"\");\n}\n\nexport function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {\n const errorMessage = assistant.errorMessage;\n return (\n assistant.stopReason === \"error\" &&\n typeof errorMessage === \"string\" &&\n USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))\n );\n}\n\nexport function isRetryableGoalInterruption(assistant: AssistantMessageLike) {\n if (assistant.stopReason !== \"error\" || !assistant.errorMessage) return false;\n if (isUsageLimitedGoalInterruption(assistant) || NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)) {\n return false;\n }\n return (\n isGoalContextOverflow(assistant) ||\n isRetryableAssistantError(toPiAssistantMessage(assistant)) ||\n RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? \"\"))\n );\n}\n\nexport function isGoalContextOverflow(assistant: AssistantMessageLike) {\n return isContextOverflow(toPiAssistantMessage(assistant));\n}\n\nexport function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (!message || typeof message !== \"object\") continue;\n const candidate = message as Record<string, unknown>;\n if (candidate.role !== \"assistant\") continue;\n const assistant: AssistantMessageLike = {\n role: \"assistant\",\n stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,\n errorMessage: typeof candidate.errorMessage === \"string\" ? candidate.errorMessage : undefined,\n };\n if (Array.isArray(candidate.content)) {\n assistant.content = candidate.content as PiAssistantMessage[\"content\"];\n }\n if (typeof candidate.api === \"string\") assistant.api = candidate.api;\n if (typeof candidate.provider === \"string\") assistant.provider = candidate.provider;\n if (typeof candidate.model === \"string\") assistant.model = candidate.model;\n if (typeof candidate.timestamp === \"number\") assistant.timestamp = candidate.timestamp;\n const usage = normalizeUsage(candidate.usage);\n if (usage) assistant.usage = usage;\n return assistant;\n }\n return undefined;\n}\n\nfunction toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {\n return {\n role: \"assistant\",\n content: assistant.content ?? [],\n api: assistant.api ?? \"openai-responses\",\n provider: assistant.provider ?? \"unknown\",\n model: assistant.model ?? \"unknown\",\n usage: assistant.usage ?? zeroUsage(),\n stopReason: assistant.stopReason ?? \"error\",\n errorMessage: assistant.errorMessage,\n timestamp: assistant.timestamp ?? Date.now(),\n };\n}\n\nfunction zeroUsage(): Usage {\n return {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n}\n\nfunction isAgentStopReason(value: unknown): value is AgentStopReason {\n return [\"stop\", \"length\", \"toolUse\", \"error\", \"aborted\"].includes(String(value));\n}\n\nfunction normalizeUsage(value: unknown): Usage | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const usage = value as Partial<Usage>;\n if (typeof usage.input !== \"number\" || typeof usage.output !== \"number\") return undefined;\n return {\n input: nonNegativeFiniteNumber(usage.input),\n output: nonNegativeFiniteNumber(usage.output),\n cacheRead: nonNegativeFiniteNumber(usage.cacheRead),\n cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),\n totalTokens: assistantUsageTokens(usage),\n cost: {\n input: usage.cost?.input ?? 0,\n output: usage.cost?.output ?? 0,\n cacheRead: usage.cost?.cacheRead ?? 0,\n cacheWrite: usage.cost?.cacheWrite ?? 0,\n total: usage.cost?.total ?? 0,\n },\n };\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { getAgentDir } from \"@earendil-works/pi-coding-agent\";\n\nexport const GOAL_SETTINGS_FILE = \"pi-goal.json\";\n\nexport type ContinuationLimit = number | null;\n\nexport interface GoalSettings {\n rpc: {\n enabled: boolean;\n };\n continuationLimits: {\n automaticTurns: ContinuationLimit;\n noProgressTurns: ContinuationLimit;\n };\n}\n\nexport const DEFAULT_GOAL_SETTINGS: GoalSettings = {\n rpc: { enabled: false },\n continuationLimits: { automaticTurns: 25, noProgressTurns: 3 },\n};\n\nexport type GoalSettingsLoadResult =\n | { kind: \"missing\"; legacyExperimentalGoals: false }\n | { kind: \"invalid\"; reason: string }\n | { kind: \"loaded\"; settings: GoalSettings; legacyExperimentalGoals: boolean };\n\nexport type GoalSettingsLoadIssue = Extract<GoalSettingsLoadResult, { kind: \"invalid\" }>;\n\ninterface GoalSettingsSaveFileSystem {\n mkdirSync: typeof mkdirSync;\n writeFileSync: typeof writeFileSync;\n renameSync: typeof renameSync;\n rmSync: typeof rmSync;\n}\n\nexport function normalizeGoalSettings(value: unknown): GoalSettings | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\n const rpcValue = Object.hasOwn(value, \"rpc\") ? Reflect.get(value, \"rpc\") : undefined;\n if (rpcValue !== undefined && (typeof rpcValue !== \"object\" || rpcValue === null || Array.isArray(rpcValue))) {\n return undefined;\n }\n const rpcEnabled =\n rpcValue && Object.hasOwn(rpcValue, \"enabled\")\n ? Reflect.get(rpcValue, \"enabled\")\n : DEFAULT_GOAL_SETTINGS.rpc.enabled;\n if (typeof rpcEnabled !== \"boolean\") return undefined;\n\n const continuationLimitsValue = Object.hasOwn(value, \"continuationLimits\")\n ? Reflect.get(value, \"continuationLimits\")\n : undefined;\n if (\n continuationLimitsValue !== undefined &&\n (typeof continuationLimitsValue !== \"object\" ||\n continuationLimitsValue === null ||\n Array.isArray(continuationLimitsValue))\n ) {\n return undefined;\n }\n const automaticTurns = continuationLimitsValue\n ? normalizeContinuationLimit(\n Reflect.get(continuationLimitsValue, \"automaticTurns\"),\n DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,\n )\n : DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns;\n const noProgressTurns = continuationLimitsValue\n ? normalizeContinuationLimit(\n Reflect.get(continuationLimitsValue, \"noProgressTurns\"),\n DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns,\n )\n : DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;\n if (automaticTurns === undefined || noProgressTurns === undefined) return undefined;\n\n return {\n rpc: { enabled: rpcEnabled },\n continuationLimits: { automaticTurns, noProgressTurns },\n };\n}\n\nfunction normalizeContinuationLimit(value: unknown, fallback: ContinuationLimit): ContinuationLimit | undefined {\n if (value === undefined) return fallback;\n if (value === null) return null;\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function saveGoalSettings(\n settings: GoalSettings,\n settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n overrides: Partial<GoalSettingsSaveFileSystem> = {},\n) {\n const normalized = normalizeGoalSettings(settings);\n if (!normalized) throw new Error(\"Refusing to save invalid pi-goal settings.\");\n\n let raw: Record<string, unknown> = {};\n try {\n const contents = readFileSync(settingsPath, \"utf8\");\n const parsed = JSON.parse(contents) as unknown;\n if (!normalizeGoalSettings(parsed)) {\n throw new Error(`${settingsPath}: invalid settings shape`);\n }\n raw = ownRecord(parsed) ?? {};\n } catch (error) {\n if (!isNodeError(error) || error.code !== \"ENOENT\") {\n throw new Error(`Cannot save invalid settings file: ${formatError(error)}`);\n }\n }\n\n const rpc = ownRecord(raw.rpc) ?? {};\n const continuationLimits = ownRecord(raw.continuationLimits) ?? {};\n const document = `${JSON.stringify(\n {\n ...raw,\n rpc: { ...rpc, enabled: normalized.rpc.enabled },\n continuationLimits: {\n ...continuationLimits,\n automaticTurns: normalized.continuationLimits.automaticTurns,\n noProgressTurns: normalized.continuationLimits.noProgressTurns,\n },\n },\n null,\n 2,\n )}\\n`;\n const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };\n const temporaryPath = join(dirname(settingsPath), `.${basename(settingsPath)}.${randomUUID()}.tmp`);\n try {\n fs.mkdirSync(dirname(settingsPath), { recursive: true });\n fs.writeFileSync(temporaryPath, document, { encoding: \"utf8\", flag: \"wx\" });\n fs.renameSync(temporaryPath, settingsPath);\n } finally {\n try {\n fs.rmSync(temporaryPath, { force: true });\n } catch {\n // Best-effort cleanup must not replace the save result.\n }\n }\n}\n\nexport function readGoalSettings(settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE)): GoalSettingsLoadResult {\n let contents: string;\n try {\n contents = readFileSync(settingsPath, \"utf8\");\n } catch (error: unknown) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return { kind: \"missing\", legacyExperimentalGoals: false };\n }\n return { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n }\n\n try {\n const parsed = JSON.parse(contents) as unknown;\n const settings = normalizeGoalSettings(parsed);\n return settings\n ? { kind: \"loaded\", settings, legacyExperimentalGoals: hasLegacyExperimentalGoals(parsed) }\n : { kind: \"invalid\", reason: `${settingsPath}: invalid settings shape` };\n } catch (error: unknown) {\n return { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n }\n}\n\nfunction hasLegacyExperimentalGoals(value: unknown) {\n const experimental = ownRecord(ownRecord(value)?.experimental);\n return experimental?.goals === true;\n}\n\nfunction ownRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction formatError(error: unknown) {\n return error instanceof Error ? error.message : String(error);\n}\n"],
4
+ "sourcesContent": ["import type { Usage } from \"@earendil-works/pi-ai\";\n\nexport interface GoalAccountingState {\n status: string;\n baselineTokens: number;\n tokensUsed: number;\n timeUsedSeconds: number;\n activeStartedAt?: number;\n updatedAt: number;\n}\n\ninterface AssistantUsageEntryLike {\n type?: unknown;\n message?: unknown;\n}\n\ninterface UsageContext {\n sessionManager?: unknown;\n}\n\nexport function checkpointGoalActiveTime(goal: GoalAccountingState, now: number, continueClock: boolean) {\n const accumulated = nonNegativeFiniteNumber(goal.timeUsedSeconds);\n const startedAt = goal.activeStartedAt;\n if (typeof startedAt === \"number\" && Number.isFinite(startedAt)) {\n goal.timeUsedSeconds = accumulated + Math.max(0, now - startedAt) / 1000;\n } else {\n goal.timeUsedSeconds = accumulated;\n }\n goal.activeStartedAt = continueClock ? now : undefined;\n}\n\nexport function updateGoalUsage(\n goal: GoalAccountingState,\n ctx: UsageContext,\n continueClock = goal.status === \"active\",\n) {\n const now = Date.now();\n const baselineTokens = nonNegativeFiniteNumber(goal.baselineTokens);\n goal.baselineTokens = baselineTokens;\n goal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - baselineTokens);\n checkpointGoalActiveTime(goal, now, continueClock);\n goal.updatedAt = now;\n}\n\nexport function formatDuration(seconds: number) {\n const wholeSeconds = Math.max(0, Math.floor(nonNegativeFiniteNumber(seconds)));\n if (wholeSeconds < 60) return `${wholeSeconds}s`;\n const minutes = Math.floor(wholeSeconds / 60);\n if (minutes < 60) return `${minutes}m`;\n const hours = Math.floor(minutes / 60);\n return `${hours}h${minutes % 60}m`;\n}\n\nexport function formatTokenCount(value: number) {\n if (value < 1_000) return `${value}`;\n if (value < 1_000_000) {\n return `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;\n }\n return `${Number.isInteger(value / 1_000_000) ? value / 1_000_000 : (value / 1_000_000).toFixed(1)}m`;\n}\n\nexport function isNonNegativeFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nexport function nonNegativeFiniteNumber(value: unknown) {\n return isNonNegativeFiniteNumber(value) ? value : 0;\n}\n\nexport function normalizeTokenBudget(value: unknown) {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function assistantUsageTokens(value: unknown) {\n if (!value || typeof value !== \"object\") return 0;\n const usage = value as Partial<Usage>;\n if (isNonNegativeFiniteNumber(usage.totalTokens)) return usage.totalTokens;\n return Math.min(\n Number.MAX_SAFE_INTEGER,\n nonNegativeFiniteNumber(usage.input) +\n nonNegativeFiniteNumber(usage.output) +\n nonNegativeFiniteNumber(usage.cacheRead) +\n nonNegativeFiniteNumber(usage.cacheWrite),\n );\n}\n\nexport function cumulativeAssistantTokens(entries: unknown[]) {\n let total = 0;\n for (const entry of entries) {\n const candidate = entry as AssistantUsageEntryLike;\n if (candidate?.type !== \"message\") continue;\n const message = candidate.message as { role?: unknown; usage?: unknown } | undefined;\n if (message?.role !== \"assistant\") continue;\n total = Math.min(Number.MAX_SAFE_INTEGER, total + assistantUsageTokens(message.usage));\n }\n return total;\n}\n\nexport function currentTokenTotal(ctx: UsageContext): number {\n const sessionManager = ctx.sessionManager as { getBranch?: () => unknown[] } | undefined;\n return cumulativeAssistantTokens(sessionManager?.getBranch?.() ?? []);\n}\n", "import {\n isContextOverflow,\n isRetryableAssistantError,\n type AssistantMessage as PiAssistantMessage,\n type Usage,\n} from \"@earendil-works/pi-ai\";\nimport { stripTerminalSequences } from \"@earendil-works/pi-tui\";\nimport { assistantUsageTokens, nonNegativeFiniteNumber } from \"./accounting.js\";\n\nexport type AgentStopReason = \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\";\n\nexport interface AssistantMessageLike {\n role: \"assistant\";\n stopReason?: AgentStopReason;\n errorMessage?: string;\n content?: PiAssistantMessage[\"content\"];\n api?: PiAssistantMessage[\"api\"];\n provider?: PiAssistantMessage[\"provider\"];\n model?: string;\n usage?: Usage;\n timestamp?: number;\n}\n\nconst USAGE_LIMIT_GOAL_ERROR_PATTERNS = [\n /usage[_\\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,\n /quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,\n /insufficient[_\\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,\n /(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,\n] as const;\nconst NON_RETRYABLE_GOAL_ERROR_RE = /multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;\nconst RETRYABLE_GOAL_ERROR_PATTERNS = [\n /overloaded|rate.?limit|too many requests|\\b(?:429|500|502|503|504)\\b|service.?unavailable|server.?error|internal.?error/i,\n /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,\n /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,\n /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream (?:ended|closed|terminated) before|premature (?:close|end)|incomplete (?:stream|response)|unexpected end of (?:stream|response)|http2 request did not get a response|retry delay/i,\n /context[_\\s-]*length[_\\s-]*exceeded|input exceeds the context window/i,\n] as const;\n\nexport function safeTerminalText(value: string) {\n return [...stripTerminalSequences(value)]\n .map((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n if (character === \"\\n\") return character;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n })\n .join(\"\")\n .trim();\n}\n\nexport function safeGoalMenuText(value: string, maxCharacters = 120) {\n const sanitized = safeTerminalText(value).replace(/\\s+/gu, \" \").trim();\n const characters = [...sanitized];\n return characters.length <= maxCharacters ? sanitized : `${characters.slice(0, maxCharacters).join(\"\")}\u2026`;\n}\n\nexport function notifyTerminal(\n ui: { notify: (message: string, level?: \"info\" | \"warning\" | \"error\") => void },\n message: string,\n level?: \"info\" | \"warning\" | \"error\",\n) {\n ui.notify(safeTerminalText(message), level);\n}\n\n/**\n * True when an error came from an ExtensionContext invalidated by session\n * replacement or reload. Pi throws this from every ctx getter and pi method on\n * the stale runner, so deferred callbacks must treat it as cancellation.\n */\nexport function isStaleContextError(error: unknown): boolean {\n return (\n error instanceof Error && error.message.includes(\"This extension ctx is stale after session replacement or reload\")\n );\n}\n\nexport function formatError(error: unknown) {\n return truncateNotification(error instanceof Error ? error.message : String(error));\n}\n\nexport function truncateNotification(value: string) {\n const safe = [...safeTerminalText(value)];\n return safe.length > 160 ? `${safe.slice(0, 157).join(\"\")}...` : safe.join(\"\");\n}\n\nexport function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {\n const errorMessage = assistant.errorMessage;\n return (\n assistant.stopReason === \"error\" &&\n typeof errorMessage === \"string\" &&\n USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))\n );\n}\n\nexport function isRetryableGoalInterruption(assistant: AssistantMessageLike) {\n if (assistant.stopReason !== \"error\" || !assistant.errorMessage) return false;\n if (isUsageLimitedGoalInterruption(assistant) || NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)) {\n return false;\n }\n return (\n isGoalContextOverflow(assistant) ||\n isRetryableAssistantError(toPiAssistantMessage(assistant)) ||\n RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? \"\"))\n );\n}\n\nexport function isGoalContextOverflow(assistant: AssistantMessageLike) {\n return isContextOverflow(toPiAssistantMessage(assistant));\n}\n\nexport function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (!message || typeof message !== \"object\") continue;\n const candidate = message as Record<string, unknown>;\n if (candidate.role !== \"assistant\") continue;\n const assistant: AssistantMessageLike = {\n role: \"assistant\",\n stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,\n errorMessage: typeof candidate.errorMessage === \"string\" ? candidate.errorMessage : undefined,\n };\n if (Array.isArray(candidate.content)) {\n assistant.content = candidate.content as PiAssistantMessage[\"content\"];\n }\n if (typeof candidate.api === \"string\") assistant.api = candidate.api;\n if (typeof candidate.provider === \"string\") assistant.provider = candidate.provider;\n if (typeof candidate.model === \"string\") assistant.model = candidate.model;\n if (typeof candidate.timestamp === \"number\") assistant.timestamp = candidate.timestamp;\n const usage = normalizeUsage(candidate.usage);\n if (usage) assistant.usage = usage;\n return assistant;\n }\n return undefined;\n}\n\nfunction toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {\n return {\n role: \"assistant\",\n content: assistant.content ?? [],\n api: assistant.api ?? \"openai-responses\",\n provider: assistant.provider ?? \"unknown\",\n model: assistant.model ?? \"unknown\",\n usage: assistant.usage ?? zeroUsage(),\n stopReason: assistant.stopReason ?? \"error\",\n errorMessage: assistant.errorMessage,\n timestamp: assistant.timestamp ?? Date.now(),\n };\n}\n\nfunction zeroUsage(): Usage {\n return {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n}\n\nfunction isAgentStopReason(value: unknown): value is AgentStopReason {\n return [\"stop\", \"length\", \"toolUse\", \"error\", \"aborted\"].includes(String(value));\n}\n\nfunction normalizeUsage(value: unknown): Usage | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const usage = value as Partial<Usage>;\n if (typeof usage.input !== \"number\" || typeof usage.output !== \"number\") return undefined;\n return {\n input: nonNegativeFiniteNumber(usage.input),\n output: nonNegativeFiniteNumber(usage.output),\n cacheRead: nonNegativeFiniteNumber(usage.cacheRead),\n cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),\n totalTokens: assistantUsageTokens(usage),\n cost: {\n input: usage.cost?.input ?? 0,\n output: usage.cost?.output ?? 0,\n cacheRead: usage.cost?.cacheRead ?? 0,\n cacheWrite: usage.cost?.cacheWrite ?? 0,\n total: usage.cost?.total ?? 0,\n },\n };\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { getAgentDir } from \"@earendil-works/pi-coding-agent\";\n\nexport const GOAL_SETTINGS_FILE = \"pi-goal.json\";\n\nexport type ContinuationLimit = number | null;\n\nexport interface GoalSettings {\n rpc: {\n enabled: boolean;\n };\n continuationLimits: {\n automaticTurns: ContinuationLimit;\n noProgressTurns: ContinuationLimit;\n };\n}\n\nexport const DEFAULT_GOAL_SETTINGS: GoalSettings = {\n rpc: { enabled: false },\n continuationLimits: { automaticTurns: 25, noProgressTurns: 3 },\n};\n\nexport type GoalSettingsLoadResult =\n | { kind: \"missing\"; legacyExperimentalGoals: false }\n | { kind: \"invalid\"; reason: string }\n | { kind: \"loaded\"; settings: GoalSettings; legacyExperimentalGoals: boolean };\n\nexport type GoalSettingsLoadIssue = Extract<GoalSettingsLoadResult, { kind: \"invalid\" }>;\n\ninterface GoalSettingsSaveFileSystem {\n mkdirSync: typeof mkdirSync;\n writeFileSync: typeof writeFileSync;\n renameSync: typeof renameSync;\n rmSync: typeof rmSync;\n}\n\nexport function normalizeGoalSettings(value: unknown): GoalSettings | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\n const rpcValue = Object.hasOwn(value, \"rpc\") ? Reflect.get(value, \"rpc\") : undefined;\n if (rpcValue !== undefined && (typeof rpcValue !== \"object\" || rpcValue === null || Array.isArray(rpcValue))) {\n return undefined;\n }\n const rpcEnabled =\n rpcValue && Object.hasOwn(rpcValue, \"enabled\")\n ? Reflect.get(rpcValue, \"enabled\")\n : DEFAULT_GOAL_SETTINGS.rpc.enabled;\n if (typeof rpcEnabled !== \"boolean\") return undefined;\n\n const continuationLimitsValue = Object.hasOwn(value, \"continuationLimits\")\n ? Reflect.get(value, \"continuationLimits\")\n : undefined;\n if (\n continuationLimitsValue !== undefined &&\n (typeof continuationLimitsValue !== \"object\" ||\n continuationLimitsValue === null ||\n Array.isArray(continuationLimitsValue))\n ) {\n return undefined;\n }\n const automaticTurns = continuationLimitsValue\n ? normalizeContinuationLimit(\n Reflect.get(continuationLimitsValue, \"automaticTurns\"),\n DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,\n )\n : DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns;\n const noProgressTurns = continuationLimitsValue\n ? normalizeContinuationLimit(\n Reflect.get(continuationLimitsValue, \"noProgressTurns\"),\n DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns,\n )\n : DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;\n if (automaticTurns === undefined || noProgressTurns === undefined) return undefined;\n\n return {\n rpc: { enabled: rpcEnabled },\n continuationLimits: { automaticTurns, noProgressTurns },\n };\n}\n\nfunction normalizeContinuationLimit(value: unknown, fallback: ContinuationLimit): ContinuationLimit | undefined {\n if (value === undefined) return fallback;\n if (value === null) return null;\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function saveGoalSettings(\n settings: GoalSettings,\n settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n overrides: Partial<GoalSettingsSaveFileSystem> = {},\n) {\n const normalized = normalizeGoalSettings(settings);\n if (!normalized) throw new Error(\"Refusing to save invalid pi-goal settings.\");\n\n let raw: Record<string, unknown> = {};\n try {\n const contents = readFileSync(settingsPath, \"utf8\");\n const parsed = JSON.parse(contents) as unknown;\n if (!normalizeGoalSettings(parsed)) {\n throw new Error(`${settingsPath}: invalid settings shape`);\n }\n raw = ownRecord(parsed) ?? {};\n } catch (error) {\n if (!isNodeError(error) || error.code !== \"ENOENT\") {\n throw new Error(`Cannot save invalid settings file: ${formatError(error)}`);\n }\n }\n\n const rpc = ownRecord(raw.rpc) ?? {};\n const continuationLimits = ownRecord(raw.continuationLimits) ?? {};\n const document = `${JSON.stringify(\n {\n ...raw,\n rpc: { ...rpc, enabled: normalized.rpc.enabled },\n continuationLimits: {\n ...continuationLimits,\n automaticTurns: normalized.continuationLimits.automaticTurns,\n noProgressTurns: normalized.continuationLimits.noProgressTurns,\n },\n },\n null,\n 2,\n )}\\n`;\n const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };\n const temporaryPath = join(dirname(settingsPath), `.${basename(settingsPath)}.${randomUUID()}.tmp`);\n try {\n fs.mkdirSync(dirname(settingsPath), { recursive: true });\n fs.writeFileSync(temporaryPath, document, { encoding: \"utf8\", flag: \"wx\" });\n fs.renameSync(temporaryPath, settingsPath);\n } finally {\n try {\n fs.rmSync(temporaryPath, { force: true });\n } catch {\n // Best-effort cleanup must not replace the save result.\n }\n }\n}\n\nexport function readGoalSettings(settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE)): GoalSettingsLoadResult {\n let contents: string;\n try {\n contents = readFileSync(settingsPath, \"utf8\");\n } catch (error: unknown) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return { kind: \"missing\", legacyExperimentalGoals: false };\n }\n return { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n }\n\n try {\n const parsed = JSON.parse(contents) as unknown;\n const settings = normalizeGoalSettings(parsed);\n return settings\n ? { kind: \"loaded\", settings, legacyExperimentalGoals: hasLegacyExperimentalGoals(parsed) }\n : { kind: \"invalid\", reason: `${settingsPath}: invalid settings shape` };\n } catch (error: unknown) {\n return { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n }\n}\n\nfunction hasLegacyExperimentalGoals(value: unknown) {\n const experimental = ownRecord(ownRecord(value)?.experimental);\n return experimental?.goals === true;\n}\n\nfunction ownRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction formatError(error: unknown) {\n return error instanceof Error ? error.message : String(error);\n}\n"],
5
5
  "mappings": ";;;;AAoBO,SAAS,yBAAyB,MAA2B,KAAa,eAAwB;AACvG,QAAM,cAAc,wBAAwB,KAAK,eAAe;AAChE,QAAM,YAAY,KAAK;AACvB,MAAI,OAAO,cAAc,YAAY,OAAO,SAAS,SAAS,GAAG;AAC/D,SAAK,kBAAkB,cAAc,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI;AAAA,EACtE,OAAO;AACL,SAAK,kBAAkB;AAAA,EACzB;AACA,OAAK,kBAAkB,gBAAgB,MAAM;AAC/C;AAEO,SAAS,gBACd,MACA,KACA,gBAAgB,KAAK,WAAW,UAChC;AACA,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,iBAAiB,wBAAwB,KAAK,cAAc;AAClE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M,SAAS,UAAU;AACjD,aAAO,EAAE,MAAM,WAAW,yBAAyB,MAAM;AAAA,IAC3D;AACA,WAAO,EAAE,MAAM,WAAW,QAAQ,GAAG,YAAY,KAAKA,aAAY,KAAK,CAAC,GAAG;AAAA,EAC7E;AAEA,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,QAAQ;AAClC,UAAM,WAAW,sBAAsB,MAAM;AAC7C,WAAO,WACH,EAAE,MAAM,UAAU,UAAU,yBAAyB,2BAA2B,MAAM,EAAE,IACxF,EAAE,MAAM,WAAW,QAAQ,GAAG,YAAY,2BAA2B;AAAA,EAC3E,SAAS,OAAgB;AACvB,WAAO,EAAE,MAAM,WAAW,QAAQ,GAAG,YAAY,KAAKA,aAAY,KAAK,CAAC,GAAG;AAAA,EAC7E;AACF;AAEA,SAAS,2BAA2B,OAAgB;AAClD,QAAM,eAAe,UAAU,UAAU,KAAK,GAAG,YAAY;AAC7D,SAAO,cAAc,UAAU;AACjC;AAEA,SAAS,UAAU,OAAqD;AACtE,SAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAK,QAAoC;AAC5G;AAEA,SAAS,YAAY,OAAgD;AACnE,SAAO,iBAAiB,SAAS,UAAU;AAC7C;AAEA,SAASA,aAAY,OAAgB;AACnC,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;",
6
6
  "names": ["formatError"]
7
7
  }
@@ -14,7 +14,7 @@ import {
14
14
  safeGoalMenuText,
15
15
  truncateNotification,
16
16
  updateGoalUsage
17
- } from "./chunk-WQIA35U2.js";
17
+ } from "./chunk-6T3MHA45.js";
18
18
 
19
19
  // src/command.ts
20
20
  var MAX_OBJECTIVE_LENGTH = 4e3;
@@ -1880,4 +1880,4 @@ export {
1880
1880
  isContradictoryCompletionSummary,
1881
1881
  goalIdRejectionReason
1882
1882
  };
1883
- //# sourceMappingURL=chunk-VJ5LR26S.js.map
1883
+ //# sourceMappingURL=chunk-WLIH47XO.js.map
@@ -3,13 +3,13 @@
3
3
  import {
4
4
  goalSummary,
5
5
  parseTokenBudget
6
- } from "./chunk-VJ5LR26S.js";
6
+ } from "./chunk-WLIH47XO.js";
7
7
  import {
8
8
  formatDuration,
9
9
  formatTokenCount,
10
10
  notifyTerminal,
11
11
  safeGoalMenuText
12
- } from "./chunk-WQIA35U2.js";
12
+ } from "./chunk-6T3MHA45.js";
13
13
 
14
14
  // src/menu.ts
15
15
  var GOAL_MENU_ACTIONS = {
@@ -547,4 +547,4 @@ export {
547
547
  safeGoalMenuText,
548
548
  showGoalManager
549
549
  };
550
- //# sourceMappingURL=menu-JMGWQZIT.js.map
550
+ //# sourceMappingURL=menu-RGCRCQJK.js.map
@@ -6,7 +6,7 @@ import {
6
6
  notifyTerminal,
7
7
  safeTerminalText,
8
8
  saveGoalSettings
9
- } from "./chunk-WQIA35U2.js";
9
+ } from "./chunk-6T3MHA45.js";
10
10
 
11
11
  // src/settings-ui.ts
12
12
  import { join } from "node:path";
@@ -360,4 +360,4 @@ export {
360
360
  parseGoalLimit,
361
361
  showGoalSettings
362
362
  };
363
- //# sourceMappingURL=settings-ui-JG3PFRB5.js.map
363
+ //# sourceMappingURL=settings-ui-BAWNTINU.js.map
package/dist/index.ts CHANGED
@@ -43,7 +43,7 @@ import {
43
43
  stoppedStatusLabel,
44
44
  transitionGoal,
45
45
  validateObjective
46
- } from "./chunks/chunk-VJ5LR26S.js";
46
+ } from "./chunks/chunk-WLIH47XO.js";
47
47
  import {
48
48
  DEFAULT_GOAL_SETTINGS,
49
49
  currentTokenTotal,
@@ -59,12 +59,12 @@ import {
59
59
  safeGoalMenuText,
60
60
  safeTerminalText,
61
61
  truncateNotification
62
- } from "./chunks/chunk-WQIA35U2.js";
62
+ } from "./chunks/chunk-6T3MHA45.js";
63
63
 
64
64
  // src/command-registration.ts
65
65
  function registerGoalCommand(pi, runtime, commands, options = {}) {
66
- const loadGoalManager = cachedModuleLoader(options.loadGoalManager ?? (() => import("./chunks/menu-JMGWQZIT.js")));
67
- const loadGoalSettings = cachedModuleLoader(options.loadGoalSettings ?? (() => import("./chunks/settings-ui-JG3PFRB5.js")));
66
+ const loadGoalManager = cachedModuleLoader(options.loadGoalManager ?? (() => import("./chunks/menu-RGCRCQJK.js")));
67
+ const loadGoalSettings = cachedModuleLoader(options.loadGoalSettings ?? (() => import("./chunks/settings-ui-BAWNTINU.js")));
68
68
  pi.registerCommand("goal", {
69
69
  description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
70
70
  getArgumentCompletions: (prefix) => completeGoalArguments(prefix),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.54.5",
3
+ "version": "0.54.6",
4
4
  "description": "Pi extension for autonomous single-objective /goal completion.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/errors.ts CHANGED
@@ -32,7 +32,7 @@ const RETRYABLE_GOAL_ERROR_PATTERNS = [
32
32
  /overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
33
33
  /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
34
34
  /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
35
- /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,
35
+ /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream (?:ended|closed|terminated) before|premature (?:close|end)|incomplete (?:stream|response)|unexpected end of (?:stream|response)|http2 request did not get a response|retry delay/i,
36
36
  /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
37
37
  ] as const;
38
38