@narumitw/pi-goal 0.54.16 → 0.54.17

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.
@@ -81,14 +81,6 @@ var USAGE_LIMIT_GOAL_ERROR_PATTERNS = [
81
81
  /insufficient[_\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,
82
82
  /(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i
83
83
  ];
84
- var NON_RETRYABLE_GOAL_ERROR_RE = /multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
85
- var RETRYABLE_GOAL_ERROR_PATTERNS = [
86
- /overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
87
- /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
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|closed|terminated) before|premature(?:ly)? (?:close|end)|incomplete (?:stream|response)|unexpected end of (?:stream|response)|http2 request did not get a response|retry delay/i,
90
- /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i
91
- ];
92
84
  function safeTerminalText(value) {
93
85
  return [...stripTerminalSequences(value)].map((character) => {
94
86
  const codePoint = character.codePointAt(0) ?? 0;
@@ -120,10 +112,7 @@ function isUsageLimitedGoalInterruption(assistant) {
120
112
  }
121
113
  function isRetryableGoalInterruption(assistant) {
122
114
  if (assistant.stopReason !== "error" || !assistant.errorMessage) return false;
123
- if (isUsageLimitedGoalInterruption(assistant) || NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)) {
124
- return false;
125
- }
126
- return isGoalContextOverflow(assistant) || isRetryableAssistantError(toPiAssistantMessage(assistant)) || RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? ""));
115
+ return isGoalContextOverflow(assistant) || isRetryableAssistantError(toPiAssistantMessage(assistant));
127
116
  }
128
117
  function isGoalContextOverflow(assistant) {
129
118
  return isContextOverflow(toPiAssistantMessage(assistant));
@@ -340,4 +329,4 @@ export {
340
329
  saveGoalSettings,
341
330
  readGoalSettings
342
331
  };
343
- //# sourceMappingURL=chunk-35Q7SHFA.ts.map
332
+ //# sourceMappingURL=chunk-ZLKWPYIF.ts.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 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;\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 // Pi owns eligibility and execution; Goal only tracks the recovery boundary.\n return isGoalContextOverflow(assistant) || isRetryableAssistantError(toPiAssistantMessage(assistant));\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
+ "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,E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AE,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
+ "names": ["formatError"]
7
+ }
@@ -3,13 +3,13 @@
3
3
  import {
4
4
  goalSummary,
5
5
  parseTokenBudget
6
- } from "./chunk-DJULXRA6.ts";
6
+ } from "./chunk-MHW7VEET.ts";
7
7
  import {
8
8
  formatDuration,
9
9
  formatTokenCount,
10
10
  notifyTerminal,
11
11
  safeGoalMenuText
12
- } from "./chunk-35Q7SHFA.ts";
12
+ } from "./chunk-ZLKWPYIF.ts";
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-D2YSESU6.ts.map
550
+ //# sourceMappingURL=menu-3AYWQ637.ts.map
@@ -6,7 +6,7 @@ import {
6
6
  notifyTerminal,
7
7
  safeTerminalText,
8
8
  saveGoalSettings
9
- } from "./chunk-35Q7SHFA.ts";
9
+ } from "./chunk-ZLKWPYIF.ts";
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-HV4QGJZ2.ts.map
363
+ //# sourceMappingURL=settings-ui-RVQTWGJ5.ts.map
package/dist/index.ts CHANGED
@@ -43,7 +43,7 @@ import {
43
43
  stoppedStatusLabel,
44
44
  transitionGoal,
45
45
  validateObjective
46
- } from "./chunks/chunk-DJULXRA6.ts";
46
+ } from "./chunks/chunk-MHW7VEET.ts";
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-35Q7SHFA.ts";
62
+ } from "./chunks/chunk-ZLKWPYIF.ts";
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-D2YSESU6.ts")));
67
- const loadGoalSettings = cachedModuleLoader(options.loadGoalSettings ?? (() => import("./chunks/settings-ui-HV4QGJZ2.ts")));
66
+ const loadGoalManager = cachedModuleLoader(options.loadGoalManager ?? (() => import("./chunks/menu-3AYWQ637.ts")));
67
+ const loadGoalSettings = cachedModuleLoader(options.loadGoalSettings ?? (() => import("./chunks/settings-ui-RVQTWGJ5.ts")));
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),
@@ -584,8 +584,11 @@ var REMOVED_QUEUE_SETTING_WARNING = "Ordered goal queue has been removed. Use /g
584
584
  var REMOVED_PERSISTED_QUEUE_WARNING = "Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.";
585
585
  function registerGoalLifecycle(pi, runtime, runController, options = {}) {
586
586
  let sessionActive = true;
587
+ let endedGoalRun;
587
588
  pi.on("session_start", async (_event, ctx) => {
588
589
  sessionActive = true;
590
+ runtime.pendingLengthRecovery = void 0;
591
+ endedGoalRun = void 0;
589
592
  runtime.bindWorkflowSession(ctx.sessionManager);
590
593
  runtime.replaceMenuSession();
591
594
  runtime.clearCompletionStatusTimer();
@@ -668,6 +671,8 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
668
671
  });
669
672
  pi.on("session_shutdown", (_event, ctx) => {
670
673
  sessionActive = false;
674
+ runtime.pendingLengthRecovery = void 0;
675
+ endedGoalRun = void 0;
671
676
  const shutdownSession = ctx.sessionManager;
672
677
  runController.unbindSession();
673
678
  runtime.closeMenuSession();
@@ -704,11 +709,17 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
704
709
  return;
705
710
  }
706
711
  if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
712
+ if (event.willRetry === true) claimCompactionRecovery(runtime.activeGoal.id);
707
713
  runtime.cancelContinuationWork();
708
714
  runtime.persistGoal(runtime.activeGoal);
709
715
  runtime.updateStatus(ctx, runtime.activeGoal);
710
716
  if (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true };
711
717
  });
718
+ pi.on("session_compact_failed", (event) => {
719
+ if (!sessionActive || !runtime.ownsWorkflow() || !runtime.activeGoal) return;
720
+ if (event.reason === "overflow") claimCompactionRecovery(runtime.activeGoal.id);
721
+ if (event.aborted && endedGoalRun?.goalId === runtime.activeGoal.id) endedGoalRun.aborted = true;
722
+ });
712
723
  pi.on("session_compact", async (event, ctx) => {
713
724
  if (!sessionActive) return;
714
725
  if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
@@ -733,7 +744,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
733
744
  }
734
745
  if (!usageRecorded) return;
735
746
  const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
736
- if (wasPiRetry) return;
747
+ if (wasPiRetry || runtime.hasActiveGoalRecovery()) return;
737
748
  runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);
738
749
  runtime.requestContinuation(runtime.activeGoal);
739
750
  runtime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);
@@ -750,6 +761,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
750
761
  if (event.streamingBehavior === "steer" || event.streamingBehavior === "followUp") {
751
762
  runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);
752
763
  }
764
+ runtime.pendingLengthRecovery = void 0;
753
765
  runtime.clearGoalRecovery();
754
766
  return;
755
767
  }
@@ -762,6 +774,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
762
774
  if (event.streamingBehavior === "steer") {
763
775
  runtime.noteQueuedNonGoalInput(event.text, "steer");
764
776
  }
777
+ runtime.pendingLengthRecovery = void 0;
765
778
  runtime.clearGoalRecovery();
766
779
  runtime.clearBudgetWrapUp();
767
780
  runtime.clearStaleGoalToolCallBlock();
@@ -858,6 +871,8 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
858
871
  });
859
872
  pi.on("before_agent_start", (event, ctx) => {
860
873
  if (!sessionActive || event.messageType === "custom") return;
874
+ runtime.pendingLengthRecovery = void 0;
875
+ endedGoalRun = void 0;
861
876
  runtime.clearAgentRun();
862
877
  if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = void 0;
863
878
  const goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);
@@ -914,6 +929,8 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
914
929
  });
915
930
  pi.on("agent_start", (_event, _ctx) => {
916
931
  if (!sessionActive) return;
932
+ runtime.pendingLengthRecovery = void 0;
933
+ endedGoalRun = void 0;
917
934
  const activeGoal = runtime.activeGoal;
918
935
  if (activeGoal && runtime.guardAbortGoalId === activeGoal.id && activeGoal.status === "paused") {
919
936
  if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {
@@ -934,6 +951,8 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
934
951
  });
935
952
  pi.on("agent_end", (event, ctx) => {
936
953
  if (!sessionActive) return;
954
+ runtime.pendingLengthRecovery = void 0;
955
+ endedGoalRun = void 0;
937
956
  const run = runtime.finishAgentRun();
938
957
  if (run.goalId === null) return;
939
958
  if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;
@@ -950,6 +969,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
950
969
  return;
951
970
  }
952
971
  const goalId = runtime.activeGoal.id;
972
+ endedGoalRun = { goalId, aborted: false };
953
973
  const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);
954
974
  const finalAssistant = findFinalAssistantMessage(event.messages);
955
975
  if (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);
@@ -960,31 +980,31 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
960
980
  return;
961
981
  }
962
982
  if (finalAssistant?.stopReason === "error") {
963
- if (isRetryableGoalInterruption(finalAssistant)) {
964
- if (run.origin === "automatic" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;
965
- if (runtime.limitActiveGoalForBudget(ctx, false)) return;
966
- if (!runtime.goalToolsAvailable()) {
967
- runtime.pauseGoalForUnavailableTools(ctx);
968
- return;
969
- }
970
- runtime.goalRecovery = {
971
- goalId,
972
- kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
973
- automaticOwner: run.origin === "automatic",
974
- errorMessage: finalAssistant.errorMessage
975
- };
976
- runtime.cancelContinuationWork();
977
- runtime.persistGoal(runtime.activeGoal);
978
- runtime.updateStatus(ctx, runtime.activeGoal);
983
+ const nativeRecovery = isRetryableGoalInterruption(finalAssistant);
984
+ if (!nativeRecovery && isUsageLimitedGoalInterruption(finalAssistant)) {
985
+ runtime.clearGoalRecoveryForGoal(goalId);
986
+ stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, "usage_limited");
979
987
  return;
980
988
  }
981
- runtime.clearGoalRecoveryForGoal(goalId);
982
- stopGoalAfterAgentEnd(
983
- ctx,
984
- runtime.activeGoal,
985
- finalAssistant,
986
- isUsageLimitedGoalInterruption(finalAssistant) ? "usage_limited" : "blocked"
987
- );
989
+ if (run.origin === "automatic" && (runtime.enforceAutomaticTurnLimit(ctx, true) || runtime.enforceNoProgressLimit(ctx, true))) {
990
+ return;
991
+ }
992
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
993
+ if (!runtime.goalToolsAvailable()) {
994
+ runtime.pauseGoalForUnavailableTools(ctx);
995
+ return;
996
+ }
997
+ runtime.goalRecovery = {
998
+ goalId,
999
+ kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : nativeRecovery ? "provider_retry" : "provider_error",
1000
+ automaticOwner: run.origin === "automatic",
1001
+ errorMessage: finalAssistant.errorMessage
1002
+ };
1003
+ runtime.cancelContinuationWork();
1004
+ runtime.persistGoal(runtime.activeGoal);
1005
+ if (runtime.activeGoal?.id === goalId && runtime.ownsWorkflow(runtime.activeGoal)) {
1006
+ runtime.updateStatus(ctx, runtime.activeGoal);
1007
+ }
988
1008
  return;
989
1009
  }
990
1010
  runtime.clearGoalRecoveryForGoal(goalId);
@@ -993,6 +1013,13 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
993
1013
  runtime.pauseGoalForUnavailableTools(ctx);
994
1014
  return;
995
1015
  }
1016
+ if (finalAssistant?.stopReason === "length") {
1017
+ runtime.pendingLengthRecovery = {
1018
+ goalId,
1019
+ kind: "compaction_retry",
1020
+ automaticOwner: run.origin === "automatic"
1021
+ };
1022
+ }
996
1023
  if (run.origin === "automatic" && runtime.recordAutomaticRunProgress(
997
1024
  ctx,
998
1025
  goalId,
@@ -1001,30 +1028,44 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
1001
1028
  )) {
1002
1029
  return;
1003
1030
  }
1004
- runtime.persistGoal(runtime.activeGoal);
1005
- runtime.updateStatus(ctx, runtime.activeGoal);
1006
1031
  const currentGoal = runtime.activeGoal;
1007
- if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
1008
- runtime.requestContinuation(currentGoal);
1032
+ if (!currentGoal || currentGoal.id !== goalId || !runtime.ownsWorkflow(currentGoal)) return;
1033
+ runtime.persistGoal(currentGoal);
1034
+ const persistedGoal = runtime.activeGoal;
1035
+ if (!persistedGoal || persistedGoal.id !== goalId || !runtime.ownsWorkflow(persistedGoal)) return;
1036
+ runtime.updateStatus(ctx, persistedGoal);
1037
+ runtime.requestContinuation(persistedGoal);
1009
1038
  });
1010
- pi.on("agent_settled", (_event, ctx) => {
1039
+ pi.on("agent_settled", (event, ctx) => {
1011
1040
  if (!sessionActive) return;
1041
+ runtime.pendingLengthRecovery = void 0;
1042
+ const settledRun = endedGoalRun;
1043
+ endedGoalRun = void 0;
1012
1044
  if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
1013
1045
  runtime.cancelContinuationWork();
1014
1046
  runtime.clearGoalRecovery();
1015
1047
  runtime.clearSettledSafetyTracking();
1016
1048
  return;
1017
1049
  }
1018
- runtime.finalizeSettledRecovery(ctx);
1050
+ runtime.finalizeSettledRecovery(ctx, event.aborted === true || settledRun?.aborted === true, settledRun?.goalId);
1019
1051
  const resumedWait = runtime.dispatchDueGoalWait(ctx);
1020
1052
  if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);
1021
1053
  runtime.clearSettledSafetyTracking();
1022
1054
  });
1055
+ function claimCompactionRecovery(goalId) {
1056
+ const lengthRecovery = runtime.pendingLengthRecovery?.goalId === goalId ? runtime.pendingLengthRecovery : void 0;
1057
+ if (lengthRecovery) runtime.pendingLengthRecovery = void 0;
1058
+ const recovery = lengthRecovery ?? (runtime.goalRecovery?.goalId === goalId ? runtime.goalRecovery : void 0);
1059
+ if (!recovery) return;
1060
+ runtime.goalRecovery = { ...recovery, kind: "compaction_retry" };
1061
+ runtime.cancelContinuationWork();
1062
+ }
1023
1063
  function goalContractBoundaryResult(ctx, goal2) {
1024
1064
  const message = runtime.goalContextContractForPrompt(ctx, goal2);
1025
1065
  return message ? { message } : void 0;
1026
1066
  }
1027
1067
  function beginNonGoalFollowUp(ctx, resetSafetyEpoch) {
1068
+ runtime.pendingLengthRecovery = void 0;
1028
1069
  runtime.clearGoalRecovery();
1029
1070
  runtime.clearStaleGoalToolCallBlock();
1030
1071
  if (resetSafetyEpoch) runtime.clearBudgetWrapUp();
@@ -1045,17 +1086,9 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
1045
1086
  notifyTerminal(ctx.ui, `Goal paused after interruption${details}. Run /goal resume to continue.`, "warning");
1046
1087
  return;
1047
1088
  }
1048
- if (status === "usage_limited") {
1049
- notifyTerminal(
1050
- ctx.ui,
1051
- `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
1052
- "warning"
1053
- );
1054
- return;
1055
- }
1056
1089
  notifyTerminal(
1057
1090
  ctx.ui,
1058
- `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
1091
+ `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
1059
1092
  "warning"
1060
1093
  );
1061
1094
  }