@narumitw/pi-goal 0.53.3 → 0.54.0
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.
- package/README.md +11 -23
- package/dist/chunks/{chunk-2ARA24RR.js → chunk-UQRRW4CY.js} +1 -7
- package/dist/chunks/{chunk-2ARA24RR.js.map → chunk-UQRRW4CY.js.map} +2 -2
- package/dist/chunks/{chunk-ZT3VZXYO.js → chunk-XHEFHXTF.js} +20 -170
- package/dist/chunks/chunk-XHEFHXTF.js.map +7 -0
- package/dist/chunks/{menu-H3C3LAQW.js → menu-4GLAABLR.js} +3 -3
- package/dist/chunks/{settings-ui-LBFJ7TOX.js → settings-ui-MVYTTBHW.js} +31 -84
- package/dist/chunks/settings-ui-MVYTTBHW.js.map +7 -0
- package/dist/index.ts +17 -89
- package/dist/index.ts.map +2 -2
- package/package.json +1 -1
- package/src/commands.ts +6 -16
- package/src/lifecycle.ts +6 -51
- package/src/runtime.ts +11 -35
- package/src/settings-ui.ts +29 -93
- package/src/settings.ts +0 -10
- package/src/tool-policy.ts +8 -171
- package/src/tools.ts +3 -28
- package/dist/chunks/chunk-ZT3VZXYO.js.map +0 -7
- package/dist/chunks/settings-ui-LBFJ7TOX.js.map +0 -7
- /package/dist/chunks/{menu-H3C3LAQW.js.map → menu-4GLAABLR.js.map} +0 -0
package/README.md
CHANGED
|
@@ -55,7 +55,6 @@ When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults
|
|
|
55
55
|
|
|
56
56
|
```json
|
|
57
57
|
{
|
|
58
|
-
"toolVisibility": "after-first-goal",
|
|
59
58
|
"rpc": {
|
|
60
59
|
"enabled": false
|
|
61
60
|
},
|
|
@@ -67,14 +66,13 @@ When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults
|
|
|
67
66
|
```
|
|
68
67
|
|
|
69
68
|
Use `/goal` → **Settings…** in the TUI to create or update the file interactively, or create and edit it directly.
|
|
70
|
-
The standard Settings screen keeps all
|
|
69
|
+
The standard Settings screen keeps all three controls on one level in task order; the two safety limits open standard choice screens:
|
|
71
70
|
|
|
72
71
|
- **Automatic-work limit** shows the exact response limit or **Unlimited**.
|
|
73
72
|
Choose **Set response limit…** to edit the current finite value (or the built-in default of 25 when switching from Unlimited), or choose **Unlimited…**.
|
|
74
73
|
Unlimited requires confirmation that tool loops may continue consuming tokens and provider cost without a response-count cap.
|
|
75
74
|
- **No-progress guard** shows **_N_ runs** or **Off**.
|
|
76
75
|
Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
|
|
77
|
-
- **Goal tools** controls whether all Goal tools are always visible or appear after the first goal.
|
|
78
76
|
- **Managed run RPC** controls whether trusted installed extensions may start and cancel managed Goal runs.
|
|
79
77
|
It defaults to **Off** and is a cooperation setting, not an extension security sandbox.
|
|
80
78
|
|
|
@@ -82,16 +80,12 @@ Custom number inputs reject zero, negative numbers, decimals, text, and unsafe i
|
|
|
82
80
|
Interactive changes are serialized, written atomically, preserve unknown fields, and apply to the current runtime.
|
|
83
81
|
A successful change updates the visible state immediately.
|
|
84
82
|
A failed save restores the prior value and reports the settings path so it can be retried.
|
|
85
|
-
Tool-visibility changes that would alter the active tool schema are rejected while Pi is busy or another cooperative workflow owns the session; retry after both conditions clear.
|
|
86
83
|
Escape returns to the previous screen without reverting changes that were already saved.
|
|
87
84
|
|
|
88
|
-
`
|
|
89
|
-
|
|
90
|
-
-
|
|
91
|
-
|
|
92
|
-
On restore, pi-goal uses the active tools already established by earlier lifecycle handlers; it does not re-add missing terminal tools over a restrictive policy.
|
|
93
|
-
Failed kickoff, replacement, resume, or reactivating-edit delivery restores the exact pre-activation tool set, including Goal tools exposed by another extension.
|
|
94
|
-
If revealing the tools would widen an already-running turn, wait for Pi to become idle and retry `/goal`.
|
|
85
|
+
Pi-goal registers `goal_complete`, `goal_blocked`, and `goal_wait` once and keeps their schemas stable from startup.
|
|
86
|
+
Visible Goal tools do not mean Goal mode is active, and only the latest effective active Goal contract authorizes their use.
|
|
87
|
+
Pi-goal never widens a restrictive active-tool policy; activation rejects when required terminal tools are missing, and an active Goal pauses if they later disappear.
|
|
88
|
+
The retired `toolVisibility` key is ignored and preserved as unknown data when another setting is saved.
|
|
95
89
|
|
|
96
90
|
`experimental.goals` is a removed legacy setting.
|
|
97
91
|
If it remains `true`, pi-goal accepts the settings file, ignores the old queue feature, and shows an affected-user warning that recommends `/goal edit` when an active objective exists or `/goal <objectives>` when no active goal exists.
|
|
@@ -126,11 +120,9 @@ Omitted fields use the defaults above.
|
|
|
126
120
|
Invalid or malformed existing settings are never overwritten; they produce a warning and fall back to all defaults.
|
|
127
121
|
In the TUI, Goal Settings becomes a read-only summary that identifies the invalid file and directs the user to fix it and run `/reload`.
|
|
128
122
|
Reload Pi after changing the file.
|
|
129
|
-
If a live runtime reloads settings, switching `toolVisibility` to `"always"` restores only the exact tools that pi-goal previously hid, while switching to `"after-first-goal"` locks a runtime that has no unfinished goal.
|
|
130
123
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
Plan mode or another restrictive policy may temporarily hide the tools. pi-goal does not fight that policy on restore or on every turn: activation is rejected if the required terminal tools cannot be made available, and an already-active goal is paused without automatic continuation if they disappear.
|
|
124
|
+
Plan mode or another restrictive policy may hide Goal tools.
|
|
125
|
+
Pi-goal does not fight that policy on restore or on later turns: activation rejects when required terminal tools are unavailable, and an already-active goal pauses without automatic continuation if they disappear.
|
|
134
126
|
A restrictive allowlist created before `goal_wait` existed can still run ordinary Goals with `goal_complete` and `goal_blocked`, but the model cannot enter external waiting until that allowlist also includes `goal_wait`.
|
|
135
127
|
The pause aborts a Goal-owned kickoff, resume, active-edit, or automatic-continuation prompt, but it does not cancel or stale-block an unrelated user or extension turn, including startup follow-ups after a restrictive restore.
|
|
136
128
|
|
|
@@ -149,8 +141,6 @@ Restored active Goal state acquires before tool restoration, persistence publica
|
|
|
149
141
|
If restoration is busy, the Goal moves only to its existing paused safe state, does not change active tools or schedule work, and can be resumed explicitly after the other workflow ends.
|
|
150
142
|
Restored stopped Goals and inert legacy queues do not acquire or schedule automatic work.
|
|
151
143
|
|
|
152
|
-
Inactive session-start restoration and live settings changes that could alter Goal tool visibility use temporary synchronous ownership.
|
|
153
|
-
A busy result preserves the settings file, in-memory settings, active tools, and hidden-tool retry ownership.
|
|
154
144
|
An active Goal still pauses if a non-participating restrictive policy later removes its required terminal tools.
|
|
155
145
|
|
|
156
146
|
The coexistence guarantee is cooperative and applies only when every contender implements v1 on the characterized Pi runtime and shares its event bus and session-manager identity.
|
|
@@ -229,8 +219,7 @@ Goal state is stored as Pi session state, similar to Codex's thread-owned goals.
|
|
|
229
219
|
`/reload` and reopening the same Pi session can restore that session's unfinished goal.
|
|
230
220
|
An active restored goal already at or above its finite automatic-work limit pauses before another provider request and reports that progress is saved; use `/goal` to review and continue.
|
|
231
221
|
A restored waiting Goal remains quiet, excludes offline and waiting wall time from active elapsed time, and restores only its absolute optional deadline timer.
|
|
232
|
-
|
|
233
|
-
If no unfinished goal remains, a fresh runtime starts locked again.
|
|
222
|
+
An active restored goal pauses when workflow admission is busy or either required terminal tool is missing, without changing the active tool set.
|
|
234
223
|
Active elapsed time is checkpointed before shutdown and restarted after reload only when the Goal is not waiting, so offline and stopped wall-clock time is excluded.
|
|
235
224
|
Automatic-response counts, repeat fingerprints, and safety-pause causes persist across reload and compaction.
|
|
236
225
|
A direct non-`/goal` user/RPC input resets the safety epoch only while the goal is active and reclassifies the in-flight run as manual; extension input and messages sent while stopped do not reset it.
|
|
@@ -295,9 +284,8 @@ While a goal is active, Goal-owned messages carry persistence rules and a `<goal
|
|
|
295
284
|
Kickoff, resume, edited-objective, wait-resume, and automatic-continuation prompts all place a trust boundary before the escaped objective, identifying it as user-provided task data; they preserve its full scope across turns and require the agent to derive concrete requirements from the objective and referenced artifacts.
|
|
296
285
|
They treat the current worktree, command output, tests, runtime behavior, PR state, rendered artifacts, and external state as authoritative; previous conversation and plans are context rather than proof.
|
|
297
286
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
After activation, pi-goal does not change the base system instructions or ordered active tools merely for continuation, token accounting, or wait resume.
|
|
287
|
+
Goal helper names, definitions, and active prompt metadata remain stable across Goal activation, continuation, token accounting, wait resume, completion, and clearing.
|
|
288
|
+
Mode-only positive instructions live in the append-only active Goal contract instead of globally active tool prompt metadata.
|
|
301
289
|
Current token-budget usage is carried by the newly appended Goal prompt instead of rewriting leading system instructions.
|
|
302
290
|
The first accepted handoff for each Goal identity persists one deterministic hidden Goal contract at the same agent-start boundary, after previously retained conversation history.
|
|
303
291
|
The contract explicitly supersedes earlier Goal contracts, excludes mutable token, iteration, and elapsed-time counters, and stays at its appended history position.
|
|
@@ -503,7 +491,7 @@ packages/pi-goal/
|
|
|
503
491
|
│ ├── lifecycle.ts # Pi session, agent, tool, and compaction event adapter
|
|
504
492
|
│ ├── goal-contract.ts # Deterministic post-compaction model contract
|
|
505
493
|
│ ├── runtime.ts # Per-factory Goal state, transitions, prompts, and budgets
|
|
506
|
-
│ ├── tool-policy.ts # Goal tool
|
|
494
|
+
│ ├── tool-policy.ts # Goal tool names and read-only availability checks
|
|
507
495
|
│ ├── safety.ts # Output normalization and no-progress fingerprint state
|
|
508
496
|
│ ├── wait.ts # External-wait validation and session timer ownership
|
|
509
497
|
│ ├── errors.ts # Pi-aligned provider error and retry classification
|
|
@@ -201,16 +201,12 @@ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node
|
|
|
201
201
|
import { basename, dirname, join } from "node:path";
|
|
202
202
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
203
203
|
var GOAL_SETTINGS_FILE = "pi-goal.json";
|
|
204
|
-
var GOAL_TOOL_VISIBILITIES = ["always", "after-first-goal"];
|
|
205
204
|
var DEFAULT_GOAL_SETTINGS = {
|
|
206
|
-
toolVisibility: "after-first-goal",
|
|
207
205
|
rpc: { enabled: false },
|
|
208
206
|
continuationLimits: { automaticTurns: 25, noProgressTurns: 3 }
|
|
209
207
|
};
|
|
210
208
|
function normalizeGoalSettings(value) {
|
|
211
209
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
212
|
-
const toolVisibility = Object.hasOwn(value, "toolVisibility") ? Reflect.get(value, "toolVisibility") : DEFAULT_GOAL_SETTINGS.toolVisibility;
|
|
213
|
-
if (!GOAL_TOOL_VISIBILITIES.includes(toolVisibility)) return void 0;
|
|
214
210
|
const rpcValue = Object.hasOwn(value, "rpc") ? Reflect.get(value, "rpc") : void 0;
|
|
215
211
|
if (rpcValue !== void 0 && (typeof rpcValue !== "object" || rpcValue === null || Array.isArray(rpcValue))) {
|
|
216
212
|
return void 0;
|
|
@@ -231,7 +227,6 @@ function normalizeGoalSettings(value) {
|
|
|
231
227
|
) : DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
|
|
232
228
|
if (automaticTurns === void 0 || noProgressTurns === void 0) return void 0;
|
|
233
229
|
return {
|
|
234
|
-
toolVisibility,
|
|
235
230
|
rpc: { enabled: rpcEnabled },
|
|
236
231
|
continuationLimits: { automaticTurns, noProgressTurns }
|
|
237
232
|
};
|
|
@@ -262,7 +257,6 @@ function saveGoalSettings(settings, settingsPath = join(getAgentDir(), GOAL_SETT
|
|
|
262
257
|
const document = `${JSON.stringify(
|
|
263
258
|
{
|
|
264
259
|
...raw,
|
|
265
|
-
toolVisibility: normalized.toolVisibility,
|
|
266
260
|
rpc: { ...rpc, enabled: normalized.rpc.enabled },
|
|
267
261
|
continuationLimits: {
|
|
268
262
|
...continuationLimits,
|
|
@@ -345,4 +339,4 @@ export {
|
|
|
345
339
|
saveGoalSettings,
|
|
346
340
|
readGoalSettings
|
|
347
341
|
};
|
|
348
|
-
//# sourceMappingURL=chunk-
|
|
342
|
+
//# sourceMappingURL=chunk-UQRRW4CY.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\tstatus: string;\n\tbaselineTokens: number;\n\ttokensUsed: number;\n\ttimeUsedSeconds: number;\n\tactiveStartedAt?: number;\n\tupdatedAt: number;\n}\n\ninterface AssistantUsageEntryLike {\n\ttype?: unknown;\n\tmessage?: unknown;\n}\n\ninterface UsageContext {\n\tsessionManager?: unknown;\n}\n\nexport function checkpointGoalActiveTime(\n\tgoal: GoalAccountingState,\n\tnow: number,\n\tcontinueClock: boolean,\n) {\n\tconst accumulated = nonNegativeFiniteNumber(goal.timeUsedSeconds);\n\tconst startedAt = goal.activeStartedAt;\n\tif (typeof startedAt === \"number\" && Number.isFinite(startedAt)) {\n\t\tgoal.timeUsedSeconds = accumulated + Math.max(0, now - startedAt) / 1000;\n\t} else {\n\t\tgoal.timeUsedSeconds = accumulated;\n\t}\n\tgoal.activeStartedAt = continueClock ? now : undefined;\n}\n\nexport function updateGoalUsage(\n\tgoal: GoalAccountingState,\n\tctx: UsageContext,\n\tcontinueClock = goal.status === \"active\",\n) {\n\tconst now = Date.now();\n\tconst baselineTokens = nonNegativeFiniteNumber(goal.baselineTokens);\n\tgoal.baselineTokens = baselineTokens;\n\tgoal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - baselineTokens);\n\tcheckpointGoalActiveTime(goal, now, continueClock);\n\tgoal.updatedAt = now;\n}\n\nexport function formatDuration(seconds: number) {\n\tconst wholeSeconds = Math.max(0, Math.floor(nonNegativeFiniteNumber(seconds)));\n\tif (wholeSeconds < 60) return `${wholeSeconds}s`;\n\tconst minutes = Math.floor(wholeSeconds / 60);\n\tif (minutes < 60) return `${minutes}m`;\n\tconst hours = Math.floor(minutes / 60);\n\treturn `${hours}h${minutes % 60}m`;\n}\n\nexport function formatTokenCount(value: number) {\n\tif (value < 1_000) return `${value}`;\n\tif (value < 1_000_000) {\n\t\treturn `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;\n\t}\n\treturn `${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\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nexport function nonNegativeFiniteNumber(value: unknown) {\n\treturn isNonNegativeFiniteNumber(value) ? value : 0;\n}\n\nexport function normalizeTokenBudget(value: unknown) {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function assistantUsageTokens(value: unknown) {\n\tif (!value || typeof value !== \"object\") return 0;\n\tconst usage = value as Partial<Usage>;\n\tif (isNonNegativeFiniteNumber(usage.totalTokens)) return usage.totalTokens;\n\treturn Math.min(\n\t\tNumber.MAX_SAFE_INTEGER,\n\t\tnonNegativeFiniteNumber(usage.input) +\n\t\t\tnonNegativeFiniteNumber(usage.output) +\n\t\t\tnonNegativeFiniteNumber(usage.cacheRead) +\n\t\t\tnonNegativeFiniteNumber(usage.cacheWrite),\n\t);\n}\n\nexport function cumulativeAssistantTokens(entries: unknown[]) {\n\tlet total = 0;\n\tfor (const entry of entries) {\n\t\tconst candidate = entry as AssistantUsageEntryLike;\n\t\tif (candidate?.type !== \"message\") continue;\n\t\tconst message = candidate.message as { role?: unknown; usage?: unknown } | undefined;\n\t\tif (message?.role !== \"assistant\") continue;\n\t\ttotal = Math.min(Number.MAX_SAFE_INTEGER, total + assistantUsageTokens(message.usage));\n\t}\n\treturn total;\n}\n\nexport function currentTokenTotal(ctx: UsageContext): number {\n\tconst sessionManager = ctx.sessionManager as { getBranch?: () => unknown[] } | undefined;\n\treturn cumulativeAssistantTokens(sessionManager?.getBranch?.() ?? []);\n}\n", "import {\n\tisContextOverflow,\n\tisRetryableAssistantError,\n\ttype AssistantMessage as PiAssistantMessage,\n\ttype 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\trole: \"assistant\";\n\tstopReason?: AgentStopReason;\n\terrorMessage?: string;\n\tcontent?: PiAssistantMessage[\"content\"];\n\tapi?: PiAssistantMessage[\"api\"];\n\tprovider?: PiAssistantMessage[\"provider\"];\n\tmodel?: string;\n\tusage?: Usage;\n\ttimestamp?: number;\n}\n\nconst USAGE_LIMIT_GOAL_ERROR_PATTERNS = [\n\t/usage[_\\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,\n\t/quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,\n\t/insufficient[_\\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,\n\t/(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,\n] as const;\nconst NON_RETRYABLE_GOAL_ERROR_RE =\n\t/multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;\nconst RETRYABLE_GOAL_ERROR_PATTERNS = [\n\t/overloaded|rate.?limit|too many requests|\\b(?:429|500|502|503|504)\\b|service.?unavailable|server.?error|internal.?error/i,\n\t/provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,\n\t/network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,\n\t/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\t/context[_\\s-]*length[_\\s-]*exceeded|input exceeds the context window/i,\n] as const;\n\nexport function safeTerminalText(value: string) {\n\treturn [...stripTerminalSequences(value)]\n\t\t.map((character) => {\n\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\tif (character === \"\\n\") return character;\n\t\t\treturn codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n\t\t})\n\t\t.join(\"\")\n\t\t.trim();\n}\n\nexport function safeGoalMenuText(value: string, maxCharacters = 120) {\n\tconst sanitized = safeTerminalText(value).replace(/\\s+/gu, \" \").trim();\n\tconst characters = [...sanitized];\n\treturn characters.length <= maxCharacters\n\t\t? sanitized\n\t\t: `${characters.slice(0, maxCharacters).join(\"\")}\u2026`;\n}\n\nexport function notifyTerminal(\n\tui: { notify: (message: string, level?: \"info\" | \"warning\" | \"error\") => void },\n\tmessage: string,\n\tlevel?: \"info\" | \"warning\" | \"error\",\n) {\n\tui.notify(safeTerminalText(message), level);\n}\n\nexport function formatError(error: unknown) {\n\treturn truncateNotification(error instanceof Error ? error.message : String(error));\n}\n\nexport function truncateNotification(value: string) {\n\tconst safe = [...safeTerminalText(value)];\n\treturn safe.length > 160 ? `${safe.slice(0, 157).join(\"\")}...` : safe.join(\"\");\n}\n\nexport function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {\n\tconst errorMessage = assistant.errorMessage;\n\treturn (\n\t\tassistant.stopReason === \"error\" &&\n\t\ttypeof errorMessage === \"string\" &&\n\t\tUSAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))\n\t);\n}\n\nexport function isRetryableGoalInterruption(assistant: AssistantMessageLike) {\n\tif (assistant.stopReason !== \"error\" || !assistant.errorMessage) return false;\n\tif (\n\t\tisUsageLimitedGoalInterruption(assistant) ||\n\t\tNON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)\n\t) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tisGoalContextOverflow(assistant) ||\n\t\tisRetryableAssistantError(toPiAssistantMessage(assistant)) ||\n\t\tRETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? \"\"))\n\t);\n}\n\nexport function isGoalContextOverflow(assistant: AssistantMessageLike) {\n\treturn isContextOverflow(toPiAssistantMessage(assistant));\n}\n\nexport function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (!message || typeof message !== \"object\") continue;\n\t\tconst candidate = message as Record<string, unknown>;\n\t\tif (candidate.role !== \"assistant\") continue;\n\t\tconst assistant: AssistantMessageLike = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,\n\t\t\terrorMessage: typeof candidate.errorMessage === \"string\" ? candidate.errorMessage : undefined,\n\t\t};\n\t\tif (Array.isArray(candidate.content)) {\n\t\t\tassistant.content = candidate.content as PiAssistantMessage[\"content\"];\n\t\t}\n\t\tif (typeof candidate.api === \"string\") assistant.api = candidate.api;\n\t\tif (typeof candidate.provider === \"string\") assistant.provider = candidate.provider;\n\t\tif (typeof candidate.model === \"string\") assistant.model = candidate.model;\n\t\tif (typeof candidate.timestamp === \"number\") assistant.timestamp = candidate.timestamp;\n\t\tconst usage = normalizeUsage(candidate.usage);\n\t\tif (usage) assistant.usage = usage;\n\t\treturn assistant;\n\t}\n\treturn undefined;\n}\n\nfunction toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: assistant.content ?? [],\n\t\tapi: assistant.api ?? \"openai-responses\",\n\t\tprovider: assistant.provider ?? \"unknown\",\n\t\tmodel: assistant.model ?? \"unknown\",\n\t\tusage: assistant.usage ?? zeroUsage(),\n\t\tstopReason: assistant.stopReason ?? \"error\",\n\t\terrorMessage: assistant.errorMessage,\n\t\ttimestamp: assistant.timestamp ?? Date.now(),\n\t};\n}\n\nfunction zeroUsage(): Usage {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n}\n\nfunction isAgentStopReason(value: unknown): value is AgentStopReason {\n\treturn [\"stop\", \"length\", \"toolUse\", \"error\", \"aborted\"].includes(String(value));\n}\n\nfunction normalizeUsage(value: unknown): Usage | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst usage = value as Partial<Usage>;\n\tif (typeof usage.input !== \"number\" || typeof usage.output !== \"number\") return undefined;\n\treturn {\n\t\tinput: nonNegativeFiniteNumber(usage.input),\n\t\toutput: nonNegativeFiniteNumber(usage.output),\n\t\tcacheRead: nonNegativeFiniteNumber(usage.cacheRead),\n\t\tcacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),\n\t\ttotalTokens: assistantUsageTokens(usage),\n\t\tcost: {\n\t\t\tinput: usage.cost?.input ?? 0,\n\t\t\toutput: usage.cost?.output ?? 0,\n\t\t\tcacheRead: usage.cost?.cacheRead ?? 0,\n\t\t\tcacheWrite: usage.cost?.cacheWrite ?? 0,\n\t\t\ttotal: usage.cost?.total ?? 0,\n\t\t},\n\t};\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\";\nexport const GOAL_TOOL_VISIBILITIES = [\"always\", \"after-first-goal\"] as const;\n\nexport type GoalToolVisibility = (typeof GOAL_TOOL_VISIBILITIES)[number];\nexport type ContinuationLimit = number | null;\n\nexport interface GoalSettings {\n\ttoolVisibility: GoalToolVisibility;\n\trpc: {\n\t\tenabled: boolean;\n\t};\n\tcontinuationLimits: {\n\t\tautomaticTurns: ContinuationLimit;\n\t\tnoProgressTurns: ContinuationLimit;\n\t};\n}\n\nexport const DEFAULT_GOAL_SETTINGS: GoalSettings = {\n\ttoolVisibility: \"after-first-goal\",\n\trpc: { enabled: false },\n\tcontinuationLimits: { automaticTurns: 25, noProgressTurns: 3 },\n};\n\nexport type GoalSettingsLoadResult =\n\t| { kind: \"missing\"; legacyExperimentalGoals: false }\n\t| { kind: \"invalid\"; reason: string }\n\t| { kind: \"loaded\"; settings: GoalSettings; legacyExperimentalGoals: boolean };\n\nexport type GoalSettingsLoadIssue = Extract<GoalSettingsLoadResult, { kind: \"invalid\" }>;\n\ninterface GoalSettingsSaveFileSystem {\n\tmkdirSync: typeof mkdirSync;\n\twriteFileSync: typeof writeFileSync;\n\trenameSync: typeof renameSync;\n\trmSync: typeof rmSync;\n}\n\nexport function normalizeGoalSettings(value: unknown): GoalSettings | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst toolVisibility = Object.hasOwn(value, \"toolVisibility\")\n\t\t? Reflect.get(value, \"toolVisibility\")\n\t\t: DEFAULT_GOAL_SETTINGS.toolVisibility;\n\tif (!GOAL_TOOL_VISIBILITIES.includes(toolVisibility as GoalToolVisibility)) return undefined;\n\n\tconst rpcValue = Object.hasOwn(value, \"rpc\") ? Reflect.get(value, \"rpc\") : undefined;\n\tif (\n\t\trpcValue !== undefined &&\n\t\t(typeof rpcValue !== \"object\" || rpcValue === null || Array.isArray(rpcValue))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst rpcEnabled =\n\t\trpcValue && Object.hasOwn(rpcValue, \"enabled\")\n\t\t\t? Reflect.get(rpcValue, \"enabled\")\n\t\t\t: DEFAULT_GOAL_SETTINGS.rpc.enabled;\n\tif (typeof rpcEnabled !== \"boolean\") return undefined;\n\n\tconst continuationLimitsValue = Object.hasOwn(value, \"continuationLimits\")\n\t\t? Reflect.get(value, \"continuationLimits\")\n\t\t: undefined;\n\tif (\n\t\tcontinuationLimitsValue !== undefined &&\n\t\t(typeof continuationLimitsValue !== \"object\" ||\n\t\t\tcontinuationLimitsValue === null ||\n\t\t\tArray.isArray(continuationLimitsValue))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst automaticTurns = continuationLimitsValue\n\t\t? normalizeContinuationLimit(\n\t\t\t\tReflect.get(continuationLimitsValue, \"automaticTurns\"),\n\t\t\t\tDEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,\n\t\t\t)\n\t\t: DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns;\n\tconst noProgressTurns = continuationLimitsValue\n\t\t? normalizeContinuationLimit(\n\t\t\t\tReflect.get(continuationLimitsValue, \"noProgressTurns\"),\n\t\t\t\tDEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns,\n\t\t\t)\n\t\t: DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;\n\tif (automaticTurns === undefined || noProgressTurns === undefined) return undefined;\n\n\treturn {\n\t\ttoolVisibility: toolVisibility as GoalToolVisibility,\n\t\trpc: { enabled: rpcEnabled },\n\t\tcontinuationLimits: { automaticTurns, noProgressTurns },\n\t};\n}\n\nfunction normalizeContinuationLimit(\n\tvalue: unknown,\n\tfallback: ContinuationLimit,\n): ContinuationLimit | undefined {\n\tif (value === undefined) return fallback;\n\tif (value === null) return null;\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function saveGoalSettings(\n\tsettings: GoalSettings,\n\tsettingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n\toverrides: Partial<GoalSettingsSaveFileSystem> = {},\n) {\n\tconst normalized = normalizeGoalSettings(settings);\n\tif (!normalized) throw new Error(\"Refusing to save invalid pi-goal settings.\");\n\n\tlet raw: Record<string, unknown> = {};\n\ttry {\n\t\tconst contents = readFileSync(settingsPath, \"utf8\");\n\t\tconst parsed = JSON.parse(contents) as unknown;\n\t\tif (!normalizeGoalSettings(parsed)) {\n\t\t\tthrow new Error(`${settingsPath}: invalid settings shape`);\n\t\t}\n\t\traw = ownRecord(parsed) ?? {};\n\t} catch (error) {\n\t\tif (!isNodeError(error) || error.code !== \"ENOENT\") {\n\t\t\tthrow new Error(`Cannot save invalid settings file: ${formatError(error)}`);\n\t\t}\n\t}\n\n\tconst rpc = ownRecord(raw.rpc) ?? {};\n\tconst continuationLimits = ownRecord(raw.continuationLimits) ?? {};\n\tconst document = `${JSON.stringify(\n\t\t{\n\t\t\t...raw,\n\t\t\ttoolVisibility: normalized.toolVisibility,\n\t\t\trpc: { ...rpc, enabled: normalized.rpc.enabled },\n\t\t\tcontinuationLimits: {\n\t\t\t\t...continuationLimits,\n\t\t\t\tautomaticTurns: normalized.continuationLimits.automaticTurns,\n\t\t\t\tnoProgressTurns: normalized.continuationLimits.noProgressTurns,\n\t\t\t},\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\\n`;\n\tconst fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };\n\tconst temporaryPath = join(\n\t\tdirname(settingsPath),\n\t\t`.${basename(settingsPath)}.${randomUUID()}.tmp`,\n\t);\n\ttry {\n\t\tfs.mkdirSync(dirname(settingsPath), { recursive: true });\n\t\tfs.writeFileSync(temporaryPath, document, { encoding: \"utf8\", flag: \"wx\" });\n\t\tfs.renameSync(temporaryPath, settingsPath);\n\t} finally {\n\t\ttry {\n\t\t\tfs.rmSync(temporaryPath, { force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup must not replace the save result.\n\t\t}\n\t}\n}\n\nexport function readGoalSettings(\n\tsettingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n): GoalSettingsLoadResult {\n\tlet contents: string;\n\ttry {\n\t\tcontents = readFileSync(settingsPath, \"utf8\");\n\t} catch (error: unknown) {\n\t\tif (isNodeError(error) && error.code === \"ENOENT\") {\n\t\t\treturn { kind: \"missing\", legacyExperimentalGoals: false };\n\t\t}\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n\t}\n\n\ttry {\n\t\tconst parsed = JSON.parse(contents) as unknown;\n\t\tconst settings = normalizeGoalSettings(parsed);\n\t\treturn settings\n\t\t\t? { kind: \"loaded\", settings, legacyExperimentalGoals: hasLegacyExperimentalGoals(parsed) }\n\t\t\t: { kind: \"invalid\", reason: `${settingsPath}: invalid settings shape` };\n\t} catch (error: unknown) {\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n\t}\n}\n\nfunction hasLegacyExperimentalGoals(value: unknown) {\n\tconst experimental = ownRecord(ownRecord(value)?.experimental);\n\treturn experimental?.goals === true;\n}\n\nfunction ownRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nfunction formatError(error: unknown) {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],
|
|
5
|
-
"mappings": ";;;;AAoBO,SAAS,yBACf,MACA,KACA,eACC;AACD,QAAM,cAAc,wBAAwB,KAAK,eAAe;AAChE,QAAM,YAAY,KAAK;AACvB,MAAI,OAAO,cAAc,YAAY,OAAO,SAAS,SAAS,GAAG;AAChE,SAAK,kBAAkB,cAAc,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI;AAAA,EACrE,OAAO;AACN,SAAK,kBAAkB;AAAA,EACxB;AACA,OAAK,kBAAkB,gBAAgB,MAAM;AAC9C;AAEO,SAAS,gBACf,MACA,KACA,gBAAgB,KAAK,WAAW,UAC/B;AACD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,iBAAiB,wBAAwB,KAAK,cAAc;AAClE,OAAK,iBAAiB;AACtB,OAAK,aAAa,KAAK,IAAI,GAAG,kBAAkB,GAAG,IAAI,cAAc;AACrE,2BAAyB,MAAM,KAAK,aAAa;AACjD,OAAK,YAAY;AAClB;AAEO,SAAS,eAAe,SAAiB;AAC/C,QAAM,eAAe,KAAK,IAAI,GAAG,KAAK,MAAM,wBAAwB,OAAO,CAAC,CAAC;AAC7E,MAAI,eAAe,GAAI,QAAO,GAAG,YAAY;AAC7C,QAAM,UAAU,KAAK,MAAM,eAAe,EAAE;AAC5C,MAAI,UAAU,GAAI,QAAO,GAAG,OAAO;AACnC,QAAM,QAAQ,KAAK,MA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9B,WAAW,MAAM,MAAM,aAAa;AAAA,MACpC,YAAY,MAAM,MAAM,cAAc;AAAA,MACtC,OAAO,MAAM,MAAM,SAAS;AAAA,IAC7B;AAAA,EACD;AACD;;;AC/KA,SAAS,kBAAkB;AAC3B,SAAS,WAAW,cAAc,YAAY,QAAQ,qBAAqB;AAC3E,SAAS,UAAU,SAAS,YAAY;AACxC,SAAS,mBAAmB;AAErB,IAAM,qBAAqB;
|
|
4
|
+
"sourcesContent": ["import type { Usage } from \"@earendil-works/pi-ai\";\n\nexport interface GoalAccountingState {\n\tstatus: string;\n\tbaselineTokens: number;\n\ttokensUsed: number;\n\ttimeUsedSeconds: number;\n\tactiveStartedAt?: number;\n\tupdatedAt: number;\n}\n\ninterface AssistantUsageEntryLike {\n\ttype?: unknown;\n\tmessage?: unknown;\n}\n\ninterface UsageContext {\n\tsessionManager?: unknown;\n}\n\nexport function checkpointGoalActiveTime(\n\tgoal: GoalAccountingState,\n\tnow: number,\n\tcontinueClock: boolean,\n) {\n\tconst accumulated = nonNegativeFiniteNumber(goal.timeUsedSeconds);\n\tconst startedAt = goal.activeStartedAt;\n\tif (typeof startedAt === \"number\" && Number.isFinite(startedAt)) {\n\t\tgoal.timeUsedSeconds = accumulated + Math.max(0, now - startedAt) / 1000;\n\t} else {\n\t\tgoal.timeUsedSeconds = accumulated;\n\t}\n\tgoal.activeStartedAt = continueClock ? now : undefined;\n}\n\nexport function updateGoalUsage(\n\tgoal: GoalAccountingState,\n\tctx: UsageContext,\n\tcontinueClock = goal.status === \"active\",\n) {\n\tconst now = Date.now();\n\tconst baselineTokens = nonNegativeFiniteNumber(goal.baselineTokens);\n\tgoal.baselineTokens = baselineTokens;\n\tgoal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - baselineTokens);\n\tcheckpointGoalActiveTime(goal, now, continueClock);\n\tgoal.updatedAt = now;\n}\n\nexport function formatDuration(seconds: number) {\n\tconst wholeSeconds = Math.max(0, Math.floor(nonNegativeFiniteNumber(seconds)));\n\tif (wholeSeconds < 60) return `${wholeSeconds}s`;\n\tconst minutes = Math.floor(wholeSeconds / 60);\n\tif (minutes < 60) return `${minutes}m`;\n\tconst hours = Math.floor(minutes / 60);\n\treturn `${hours}h${minutes % 60}m`;\n}\n\nexport function formatTokenCount(value: number) {\n\tif (value < 1_000) return `${value}`;\n\tif (value < 1_000_000) {\n\t\treturn `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;\n\t}\n\treturn `${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\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nexport function nonNegativeFiniteNumber(value: unknown) {\n\treturn isNonNegativeFiniteNumber(value) ? value : 0;\n}\n\nexport function normalizeTokenBudget(value: unknown) {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function assistantUsageTokens(value: unknown) {\n\tif (!value || typeof value !== \"object\") return 0;\n\tconst usage = value as Partial<Usage>;\n\tif (isNonNegativeFiniteNumber(usage.totalTokens)) return usage.totalTokens;\n\treturn Math.min(\n\t\tNumber.MAX_SAFE_INTEGER,\n\t\tnonNegativeFiniteNumber(usage.input) +\n\t\t\tnonNegativeFiniteNumber(usage.output) +\n\t\t\tnonNegativeFiniteNumber(usage.cacheRead) +\n\t\t\tnonNegativeFiniteNumber(usage.cacheWrite),\n\t);\n}\n\nexport function cumulativeAssistantTokens(entries: unknown[]) {\n\tlet total = 0;\n\tfor (const entry of entries) {\n\t\tconst candidate = entry as AssistantUsageEntryLike;\n\t\tif (candidate?.type !== \"message\") continue;\n\t\tconst message = candidate.message as { role?: unknown; usage?: unknown } | undefined;\n\t\tif (message?.role !== \"assistant\") continue;\n\t\ttotal = Math.min(Number.MAX_SAFE_INTEGER, total + assistantUsageTokens(message.usage));\n\t}\n\treturn total;\n}\n\nexport function currentTokenTotal(ctx: UsageContext): number {\n\tconst sessionManager = ctx.sessionManager as { getBranch?: () => unknown[] } | undefined;\n\treturn cumulativeAssistantTokens(sessionManager?.getBranch?.() ?? []);\n}\n", "import {\n\tisContextOverflow,\n\tisRetryableAssistantError,\n\ttype AssistantMessage as PiAssistantMessage,\n\ttype 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\trole: \"assistant\";\n\tstopReason?: AgentStopReason;\n\terrorMessage?: string;\n\tcontent?: PiAssistantMessage[\"content\"];\n\tapi?: PiAssistantMessage[\"api\"];\n\tprovider?: PiAssistantMessage[\"provider\"];\n\tmodel?: string;\n\tusage?: Usage;\n\ttimestamp?: number;\n}\n\nconst USAGE_LIMIT_GOAL_ERROR_PATTERNS = [\n\t/usage[_\\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,\n\t/quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,\n\t/insufficient[_\\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,\n\t/(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,\n] as const;\nconst NON_RETRYABLE_GOAL_ERROR_RE =\n\t/multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;\nconst RETRYABLE_GOAL_ERROR_PATTERNS = [\n\t/overloaded|rate.?limit|too many requests|\\b(?:429|500|502|503|504)\\b|service.?unavailable|server.?error|internal.?error/i,\n\t/provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,\n\t/network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,\n\t/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\t/context[_\\s-]*length[_\\s-]*exceeded|input exceeds the context window/i,\n] as const;\n\nexport function safeTerminalText(value: string) {\n\treturn [...stripTerminalSequences(value)]\n\t\t.map((character) => {\n\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\tif (character === \"\\n\") return character;\n\t\t\treturn codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n\t\t})\n\t\t.join(\"\")\n\t\t.trim();\n}\n\nexport function safeGoalMenuText(value: string, maxCharacters = 120) {\n\tconst sanitized = safeTerminalText(value).replace(/\\s+/gu, \" \").trim();\n\tconst characters = [...sanitized];\n\treturn characters.length <= maxCharacters\n\t\t? sanitized\n\t\t: `${characters.slice(0, maxCharacters).join(\"\")}\u2026`;\n}\n\nexport function notifyTerminal(\n\tui: { notify: (message: string, level?: \"info\" | \"warning\" | \"error\") => void },\n\tmessage: string,\n\tlevel?: \"info\" | \"warning\" | \"error\",\n) {\n\tui.notify(safeTerminalText(message), level);\n}\n\nexport function formatError(error: unknown) {\n\treturn truncateNotification(error instanceof Error ? error.message : String(error));\n}\n\nexport function truncateNotification(value: string) {\n\tconst safe = [...safeTerminalText(value)];\n\treturn safe.length > 160 ? `${safe.slice(0, 157).join(\"\")}...` : safe.join(\"\");\n}\n\nexport function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {\n\tconst errorMessage = assistant.errorMessage;\n\treturn (\n\t\tassistant.stopReason === \"error\" &&\n\t\ttypeof errorMessage === \"string\" &&\n\t\tUSAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))\n\t);\n}\n\nexport function isRetryableGoalInterruption(assistant: AssistantMessageLike) {\n\tif (assistant.stopReason !== \"error\" || !assistant.errorMessage) return false;\n\tif (\n\t\tisUsageLimitedGoalInterruption(assistant) ||\n\t\tNON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)\n\t) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tisGoalContextOverflow(assistant) ||\n\t\tisRetryableAssistantError(toPiAssistantMessage(assistant)) ||\n\t\tRETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? \"\"))\n\t);\n}\n\nexport function isGoalContextOverflow(assistant: AssistantMessageLike) {\n\treturn isContextOverflow(toPiAssistantMessage(assistant));\n}\n\nexport function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (!message || typeof message !== \"object\") continue;\n\t\tconst candidate = message as Record<string, unknown>;\n\t\tif (candidate.role !== \"assistant\") continue;\n\t\tconst assistant: AssistantMessageLike = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,\n\t\t\terrorMessage: typeof candidate.errorMessage === \"string\" ? candidate.errorMessage : undefined,\n\t\t};\n\t\tif (Array.isArray(candidate.content)) {\n\t\t\tassistant.content = candidate.content as PiAssistantMessage[\"content\"];\n\t\t}\n\t\tif (typeof candidate.api === \"string\") assistant.api = candidate.api;\n\t\tif (typeof candidate.provider === \"string\") assistant.provider = candidate.provider;\n\t\tif (typeof candidate.model === \"string\") assistant.model = candidate.model;\n\t\tif (typeof candidate.timestamp === \"number\") assistant.timestamp = candidate.timestamp;\n\t\tconst usage = normalizeUsage(candidate.usage);\n\t\tif (usage) assistant.usage = usage;\n\t\treturn assistant;\n\t}\n\treturn undefined;\n}\n\nfunction toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: assistant.content ?? [],\n\t\tapi: assistant.api ?? \"openai-responses\",\n\t\tprovider: assistant.provider ?? \"unknown\",\n\t\tmodel: assistant.model ?? \"unknown\",\n\t\tusage: assistant.usage ?? zeroUsage(),\n\t\tstopReason: assistant.stopReason ?? \"error\",\n\t\terrorMessage: assistant.errorMessage,\n\t\ttimestamp: assistant.timestamp ?? Date.now(),\n\t};\n}\n\nfunction zeroUsage(): Usage {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n}\n\nfunction isAgentStopReason(value: unknown): value is AgentStopReason {\n\treturn [\"stop\", \"length\", \"toolUse\", \"error\", \"aborted\"].includes(String(value));\n}\n\nfunction normalizeUsage(value: unknown): Usage | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst usage = value as Partial<Usage>;\n\tif (typeof usage.input !== \"number\" || typeof usage.output !== \"number\") return undefined;\n\treturn {\n\t\tinput: nonNegativeFiniteNumber(usage.input),\n\t\toutput: nonNegativeFiniteNumber(usage.output),\n\t\tcacheRead: nonNegativeFiniteNumber(usage.cacheRead),\n\t\tcacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),\n\t\ttotalTokens: assistantUsageTokens(usage),\n\t\tcost: {\n\t\t\tinput: usage.cost?.input ?? 0,\n\t\t\toutput: usage.cost?.output ?? 0,\n\t\t\tcacheRead: usage.cost?.cacheRead ?? 0,\n\t\t\tcacheWrite: usage.cost?.cacheWrite ?? 0,\n\t\t\ttotal: usage.cost?.total ?? 0,\n\t\t},\n\t};\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\trpc: {\n\t\tenabled: boolean;\n\t};\n\tcontinuationLimits: {\n\t\tautomaticTurns: ContinuationLimit;\n\t\tnoProgressTurns: ContinuationLimit;\n\t};\n}\n\nexport const DEFAULT_GOAL_SETTINGS: GoalSettings = {\n\trpc: { enabled: false },\n\tcontinuationLimits: { automaticTurns: 25, noProgressTurns: 3 },\n};\n\nexport type GoalSettingsLoadResult =\n\t| { kind: \"missing\"; legacyExperimentalGoals: false }\n\t| { kind: \"invalid\"; reason: string }\n\t| { kind: \"loaded\"; settings: GoalSettings; legacyExperimentalGoals: boolean };\n\nexport type GoalSettingsLoadIssue = Extract<GoalSettingsLoadResult, { kind: \"invalid\" }>;\n\ninterface GoalSettingsSaveFileSystem {\n\tmkdirSync: typeof mkdirSync;\n\twriteFileSync: typeof writeFileSync;\n\trenameSync: typeof renameSync;\n\trmSync: typeof rmSync;\n}\n\nexport function normalizeGoalSettings(value: unknown): GoalSettings | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\n\tconst rpcValue = Object.hasOwn(value, \"rpc\") ? Reflect.get(value, \"rpc\") : undefined;\n\tif (\n\t\trpcValue !== undefined &&\n\t\t(typeof rpcValue !== \"object\" || rpcValue === null || Array.isArray(rpcValue))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst rpcEnabled =\n\t\trpcValue && Object.hasOwn(rpcValue, \"enabled\")\n\t\t\t? Reflect.get(rpcValue, \"enabled\")\n\t\t\t: DEFAULT_GOAL_SETTINGS.rpc.enabled;\n\tif (typeof rpcEnabled !== \"boolean\") return undefined;\n\n\tconst continuationLimitsValue = Object.hasOwn(value, \"continuationLimits\")\n\t\t? Reflect.get(value, \"continuationLimits\")\n\t\t: undefined;\n\tif (\n\t\tcontinuationLimitsValue !== undefined &&\n\t\t(typeof continuationLimitsValue !== \"object\" ||\n\t\t\tcontinuationLimitsValue === null ||\n\t\t\tArray.isArray(continuationLimitsValue))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst automaticTurns = continuationLimitsValue\n\t\t? normalizeContinuationLimit(\n\t\t\t\tReflect.get(continuationLimitsValue, \"automaticTurns\"),\n\t\t\t\tDEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,\n\t\t\t)\n\t\t: DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns;\n\tconst noProgressTurns = continuationLimitsValue\n\t\t? normalizeContinuationLimit(\n\t\t\t\tReflect.get(continuationLimitsValue, \"noProgressTurns\"),\n\t\t\t\tDEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns,\n\t\t\t)\n\t\t: DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;\n\tif (automaticTurns === undefined || noProgressTurns === undefined) return undefined;\n\n\treturn {\n\t\trpc: { enabled: rpcEnabled },\n\t\tcontinuationLimits: { automaticTurns, noProgressTurns },\n\t};\n}\n\nfunction normalizeContinuationLimit(\n\tvalue: unknown,\n\tfallback: ContinuationLimit,\n): ContinuationLimit | undefined {\n\tif (value === undefined) return fallback;\n\tif (value === null) return null;\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function saveGoalSettings(\n\tsettings: GoalSettings,\n\tsettingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n\toverrides: Partial<GoalSettingsSaveFileSystem> = {},\n) {\n\tconst normalized = normalizeGoalSettings(settings);\n\tif (!normalized) throw new Error(\"Refusing to save invalid pi-goal settings.\");\n\n\tlet raw: Record<string, unknown> = {};\n\ttry {\n\t\tconst contents = readFileSync(settingsPath, \"utf8\");\n\t\tconst parsed = JSON.parse(contents) as unknown;\n\t\tif (!normalizeGoalSettings(parsed)) {\n\t\t\tthrow new Error(`${settingsPath}: invalid settings shape`);\n\t\t}\n\t\traw = ownRecord(parsed) ?? {};\n\t} catch (error) {\n\t\tif (!isNodeError(error) || error.code !== \"ENOENT\") {\n\t\t\tthrow new Error(`Cannot save invalid settings file: ${formatError(error)}`);\n\t\t}\n\t}\n\n\tconst rpc = ownRecord(raw.rpc) ?? {};\n\tconst continuationLimits = ownRecord(raw.continuationLimits) ?? {};\n\tconst document = `${JSON.stringify(\n\t\t{\n\t\t\t...raw,\n\t\t\trpc: { ...rpc, enabled: normalized.rpc.enabled },\n\t\t\tcontinuationLimits: {\n\t\t\t\t...continuationLimits,\n\t\t\t\tautomaticTurns: normalized.continuationLimits.automaticTurns,\n\t\t\t\tnoProgressTurns: normalized.continuationLimits.noProgressTurns,\n\t\t\t},\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\\n`;\n\tconst fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };\n\tconst temporaryPath = join(\n\t\tdirname(settingsPath),\n\t\t`.${basename(settingsPath)}.${randomUUID()}.tmp`,\n\t);\n\ttry {\n\t\tfs.mkdirSync(dirname(settingsPath), { recursive: true });\n\t\tfs.writeFileSync(temporaryPath, document, { encoding: \"utf8\", flag: \"wx\" });\n\t\tfs.renameSync(temporaryPath, settingsPath);\n\t} finally {\n\t\ttry {\n\t\t\tfs.rmSync(temporaryPath, { force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup must not replace the save result.\n\t\t}\n\t}\n}\n\nexport function readGoalSettings(\n\tsettingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n): GoalSettingsLoadResult {\n\tlet contents: string;\n\ttry {\n\t\tcontents = readFileSync(settingsPath, \"utf8\");\n\t} catch (error: unknown) {\n\t\tif (isNodeError(error) && error.code === \"ENOENT\") {\n\t\t\treturn { kind: \"missing\", legacyExperimentalGoals: false };\n\t\t}\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n\t}\n\n\ttry {\n\t\tconst parsed = JSON.parse(contents) as unknown;\n\t\tconst settings = normalizeGoalSettings(parsed);\n\t\treturn settings\n\t\t\t? { kind: \"loaded\", settings, legacyExperimentalGoals: hasLegacyExperimentalGoals(parsed) }\n\t\t\t: { kind: \"invalid\", reason: `${settingsPath}: invalid settings shape` };\n\t} catch (error: unknown) {\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n\t}\n}\n\nfunction hasLegacyExperimentalGoals(value: unknown) {\n\tconst experimental = ownRecord(ownRecord(value)?.experimental);\n\treturn experimental?.goals === true;\n}\n\nfunction ownRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nfunction formatError(error: unknown) {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAoBO,SAAS,yBACf,MACA,KACA,eACC;AACD,QAAM,cAAc,wBAAwB,KAAK,eAAe;AAChE,QAAM,YAAY,KAAK;AACvB,MAAI,OAAO,cAAc,YAAY,OAAO,SAAS,SAAS,GAAG;AAChE,SAAK,kBAAkB,cAAc,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI;AAAA,EACrE,OAAO;AACN,SAAK,kBAAkB;AAAA,EACxB;AACA,OAAK,kBAAkB,gBAAgB,MAAM;AAC9C;AAEO,SAAS,gBACf,MACA,KACA,gBAAgB,KAAK,WAAW,UAC/B;AACD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,iBAAiB,wBAAwB,KAAK,cAAc;AAClE,OAAK,iBAAiB;AACtB,OAAK,aAAa,KAAK,IAAI,GAAG,kBAAkB,GAAG,IAAI,cAAc;AACrE,2BAAyB,MAAM,KAAK,aAAa;AACjD,OAAK,YAAY;AAClB;AAEO,SAAS,eAAe,SAAiB;AAC/C,QAAM,eAAe,KAAK,IAAI,GAAG,KAAK,MAAM,wBAAwB,OAAO,CAAC,CAAC;AAC7E,MAAI,eAAe,GAAI,QAAO,GAAG,YAAY;AAC7C,QAAM,UAAU,KAAK,MAAM,eAAe,EAAE;AAC5C,MAAI,UAAU,GAAI,QAAO,GAAG,OAAO;AACnC,QAAM,QAAQ,KAAK,MAAM,UAAU,EAAE;AACrC,SAAO,GAAG,KAAK,IAAI,UAAU,EAAE;AAChC;AAEO,SAAS,iBAAiB,OAAe;AAC/C,MAAI,QAAQ,IAAO,QAAO,GAAG,KA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,OAAqD;AACvE,SAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAC7D,QACD;AACJ;AAEA,SAAS,YAAY,OAAgD;AACpE,SAAO,iBAAiB,SAAS,UAAU;AAC5C;AAEA,SAASA,aAAY,OAAgB;AACpC,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC7D;",
|
|
6
6
|
"names": ["formatError"]
|
|
7
7
|
}
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
safeGoalMenuText,
|
|
14
14
|
truncateNotification,
|
|
15
15
|
updateGoalUsage
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-UQRRW4CY.js";
|
|
17
17
|
|
|
18
18
|
// src/command.ts
|
|
19
19
|
var MAX_OBJECTIVE_LENGTH = 4e3;
|
|
@@ -639,146 +639,17 @@ function isRecord3(value) {
|
|
|
639
639
|
var GOAL_COMPLETE_TOOL = "goal_complete";
|
|
640
640
|
var GOAL_BLOCKED_TOOL = "goal_blocked";
|
|
641
641
|
var GOAL_WAIT_TOOL = "goal_wait";
|
|
642
|
-
var GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL, GOAL_WAIT_TOOL];
|
|
643
642
|
var REQUIRED_GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL];
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
hasHiddenTools() {
|
|
655
|
-
return this.hiddenByPolicy.size > 0;
|
|
656
|
-
}
|
|
657
|
-
isGoalToolName(name) {
|
|
658
|
-
return GOAL_TOOL_NAMES.includes(name);
|
|
659
|
-
}
|
|
660
|
-
toolsAvailable() {
|
|
661
|
-
const active = new Set(this.pi.getActiveTools());
|
|
662
|
-
return REQUIRED_GOAL_TOOL_NAMES.every((name) => active.has(name));
|
|
663
|
-
}
|
|
664
|
-
lock() {
|
|
665
|
-
this.unlocked = false;
|
|
666
|
-
}
|
|
667
|
-
unlock() {
|
|
668
|
-
this.unlocked = true;
|
|
669
|
-
}
|
|
670
|
-
unlockAndForgetHidden() {
|
|
671
|
-
this.unlocked = true;
|
|
672
|
-
this.hiddenByPolicy.clear();
|
|
673
|
-
}
|
|
674
|
-
hideIfLocked() {
|
|
675
|
-
if (this.unlocked) return;
|
|
676
|
-
const active = this.pi.getActiveTools();
|
|
677
|
-
const hidden = active.filter((name) => this.isGoalToolName(name));
|
|
678
|
-
if (hidden.length === 0) return;
|
|
679
|
-
this.pi.setActiveTools(active.filter((name) => !this.isGoalToolName(name)));
|
|
680
|
-
for (const name of hidden) this.hiddenByPolicy.add(name);
|
|
681
|
-
}
|
|
682
|
-
restoreHidden() {
|
|
683
|
-
const activeBeforeRestore = this.pi.getActiveTools();
|
|
684
|
-
const activeSet = new Set(activeBeforeRestore);
|
|
685
|
-
const missingOwnedTools = [...this.hiddenByPolicy].filter((name) => !activeSet.has(name));
|
|
686
|
-
if (missingOwnedTools.length === 0) {
|
|
687
|
-
this.hiddenByPolicy.clear();
|
|
688
|
-
return;
|
|
689
|
-
}
|
|
690
|
-
try {
|
|
691
|
-
this.pi.setActiveTools([...activeBeforeRestore, ...missingOwnedTools]);
|
|
692
|
-
const restored = new Set(this.pi.getActiveTools());
|
|
693
|
-
if (missingOwnedTools.some((name) => !restored.has(name))) {
|
|
694
|
-
throw new Error("the active tool policy rejected a previously hidden goal tool");
|
|
695
|
-
}
|
|
696
|
-
this.hiddenByPolicy.clear();
|
|
697
|
-
} catch (error) {
|
|
698
|
-
this.pi.setActiveTools(activeBeforeRestore);
|
|
699
|
-
throw error;
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
prepareActivation(visibility, ctx) {
|
|
703
|
-
if (visibility === "after-first-goal") {
|
|
704
|
-
if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
|
|
705
|
-
throw new Error("wait until Pi is idle before revealing the goal tools");
|
|
706
|
-
}
|
|
707
|
-
this.reveal();
|
|
708
|
-
return;
|
|
709
|
-
}
|
|
710
|
-
if (this.hasHiddenTools()) this.restoreHidden();
|
|
711
|
-
this.unlock();
|
|
712
|
-
this.assertAvailable();
|
|
713
|
-
}
|
|
714
|
-
prepareSessionStart(visibility, previous) {
|
|
715
|
-
if (visibility === "after-first-goal" && previous === "always") this.lock();
|
|
716
|
-
if (visibility !== "always") return;
|
|
717
|
-
try {
|
|
718
|
-
if (this.hasHiddenTools()) this.restoreHidden();
|
|
719
|
-
} finally {
|
|
720
|
-
this.unlock();
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
reconcileRestoredState(visibility, hasUnfinishedGoal) {
|
|
724
|
-
if (visibility !== "after-first-goal") return;
|
|
725
|
-
if (hasUnfinishedGoal) this.unlockAndForgetHidden();
|
|
726
|
-
else if (!this.unlocked) this.hideIfLocked();
|
|
727
|
-
}
|
|
728
|
-
applyVisibilityChange(previous, next, hasUnfinishedGoal, ctx) {
|
|
729
|
-
if (previous === next) return;
|
|
730
|
-
if (next === "always") {
|
|
731
|
-
if (this.hasHiddenTools() && ctx.isIdle?.() !== true) {
|
|
732
|
-
throw new Error("Wait for Pi to become idle before revealing Goal tools.");
|
|
733
|
-
}
|
|
734
|
-
this.restoreHidden();
|
|
735
|
-
this.unlock();
|
|
736
|
-
return;
|
|
737
|
-
}
|
|
738
|
-
if (hasUnfinishedGoal) {
|
|
739
|
-
this.unlockAndForgetHidden();
|
|
740
|
-
return;
|
|
741
|
-
}
|
|
742
|
-
if (ctx.isIdle?.() !== true) {
|
|
743
|
-
throw new Error("Wait for Pi to become idle before hiding Goal tools.");
|
|
744
|
-
}
|
|
745
|
-
this.lock();
|
|
746
|
-
this.hideIfLocked();
|
|
747
|
-
}
|
|
748
|
-
snapshot() {
|
|
749
|
-
return {
|
|
750
|
-
activeTools: this.pi.getActiveTools(),
|
|
751
|
-
goalToolsUnlocked: this.unlocked,
|
|
752
|
-
goalToolsHiddenByPolicy: [...this.hiddenByPolicy]
|
|
753
|
-
};
|
|
754
|
-
}
|
|
755
|
-
restore(snapshot) {
|
|
756
|
-
this.pi.setActiveTools(snapshot.activeTools);
|
|
757
|
-
this.unlocked = snapshot.goalToolsUnlocked;
|
|
758
|
-
this.hiddenByPolicy.clear();
|
|
759
|
-
for (const name of snapshot.goalToolsHiddenByPolicy) this.hiddenByPolicy.add(name);
|
|
760
|
-
}
|
|
761
|
-
reveal() {
|
|
762
|
-
const snapshot = this.snapshot();
|
|
763
|
-
try {
|
|
764
|
-
const active = this.pi.getActiveTools();
|
|
765
|
-
const activeSet = new Set(active);
|
|
766
|
-
const missing = GOAL_TOOL_NAMES.filter((name) => !activeSet.has(name));
|
|
767
|
-
if (missing.length > 0) this.pi.setActiveTools([...active, ...missing]);
|
|
768
|
-
this.assertAvailable();
|
|
769
|
-
this.unlockAndForgetHidden();
|
|
770
|
-
} catch (error) {
|
|
771
|
-
this.restore(snapshot);
|
|
772
|
-
throw error;
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
assertAvailable() {
|
|
776
|
-
if (this.toolsAvailable()) return;
|
|
777
|
-
throw new Error(
|
|
778
|
-
"goal_complete and goal_blocked are unavailable; include them in the active tool allowlist or leave the restrictive tool mode first."
|
|
779
|
-
);
|
|
780
|
-
}
|
|
781
|
-
};
|
|
643
|
+
function goalToolsAvailable(pi) {
|
|
644
|
+
const active = new Set(pi.getActiveTools());
|
|
645
|
+
return REQUIRED_GOAL_TOOL_NAMES.every((name) => active.has(name));
|
|
646
|
+
}
|
|
647
|
+
function assertGoalToolsAvailable(pi) {
|
|
648
|
+
if (goalToolsAvailable(pi)) return;
|
|
649
|
+
throw new Error(
|
|
650
|
+
"goal_complete and goal_blocked are unavailable; include them in the active tool allowlist or leave the restrictive tool mode first."
|
|
651
|
+
);
|
|
652
|
+
}
|
|
782
653
|
|
|
783
654
|
// src/workflow-mutex.ts
|
|
784
655
|
var WORKFLOW_MUTEX_CHANNEL = "workflow:mutex:v1";
|
|
@@ -891,7 +762,6 @@ var GoalRuntime = class {
|
|
|
891
762
|
agentRunToolAttempted = false;
|
|
892
763
|
guardAbortGoalId;
|
|
893
764
|
staleGoalToolCallsBlocked = false;
|
|
894
|
-
toolPolicy;
|
|
895
765
|
workflowMutex;
|
|
896
766
|
workflowOwner;
|
|
897
767
|
workflowSession;
|
|
@@ -907,7 +777,12 @@ var GoalRuntime = class {
|
|
|
907
777
|
constructor(pi) {
|
|
908
778
|
this.pi = pi;
|
|
909
779
|
this.workflowMutex = new WorkflowMutex(pi);
|
|
910
|
-
|
|
780
|
+
}
|
|
781
|
+
goalToolsAvailable() {
|
|
782
|
+
return goalToolsAvailable(this.pi);
|
|
783
|
+
}
|
|
784
|
+
assertGoalToolsAvailable() {
|
|
785
|
+
assertGoalToolsAvailable(this.pi);
|
|
911
786
|
}
|
|
912
787
|
bindWorkflowSession(session) {
|
|
913
788
|
this.workflowSession = session;
|
|
@@ -938,29 +813,6 @@ var GoalRuntime = class {
|
|
|
938
813
|
this.workflowMutex.release(owner);
|
|
939
814
|
if (!this.workflowMutex.isOwner(owner)) this.workflowOwner = void 0;
|
|
940
815
|
}
|
|
941
|
-
beginTemporaryWorkflowAccess(session) {
|
|
942
|
-
if (session && typeof session === "object" && this.workflowSession !== session) {
|
|
943
|
-
this.bindWorkflowSession(session);
|
|
944
|
-
}
|
|
945
|
-
const alreadyOwned = this.workflowMutex.isOwner(this.workflowOwner);
|
|
946
|
-
if (!alreadyOwned && !this.acquireWorkflow()) return void 0;
|
|
947
|
-
let released = false;
|
|
948
|
-
return () => {
|
|
949
|
-
if (released) return;
|
|
950
|
-
released = true;
|
|
951
|
-
if (!alreadyOwned) this.releaseWorkflow();
|
|
952
|
-
};
|
|
953
|
-
}
|
|
954
|
-
withTemporaryWorkflowAccess(action, session) {
|
|
955
|
-
const release = this.beginTemporaryWorkflowAccess(session);
|
|
956
|
-
if (!release) return false;
|
|
957
|
-
try {
|
|
958
|
-
action();
|
|
959
|
-
return true;
|
|
960
|
-
} finally {
|
|
961
|
-
release();
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
816
|
hasLegacyQueueInterface() {
|
|
965
817
|
return this.legacyExperimentalGoalsSetting || this.legacyQueueState !== void 0;
|
|
966
818
|
}
|
|
@@ -1049,7 +901,7 @@ var GoalRuntime = class {
|
|
|
1049
901
|
return false;
|
|
1050
902
|
}
|
|
1051
903
|
if (!intent) return false;
|
|
1052
|
-
if (this.activeGoal?.status === "active" && !this.
|
|
904
|
+
if (this.activeGoal?.status === "active" && !this.goalToolsAvailable()) {
|
|
1053
905
|
this.pauseGoalForUnavailableTools(ctx);
|
|
1054
906
|
return false;
|
|
1055
907
|
}
|
|
@@ -1731,8 +1583,7 @@ var GoalRuntime = class {
|
|
|
1731
1583
|
guardAbortGoalId: this.guardAbortGoalId,
|
|
1732
1584
|
staleGoalToolCallsBlocked: this.staleGoalToolCallsBlocked,
|
|
1733
1585
|
cancelledContinuationMarkers: [...this.cancelledContinuationMarkers],
|
|
1734
|
-
terminalDetails: this.terminalDetails ? structuredClone(this.terminalDetails) : void 0
|
|
1735
|
-
toolVisibility: this.toolPolicy.snapshot()
|
|
1586
|
+
terminalDetails: this.terminalDetails ? structuredClone(this.terminalDetails) : void 0
|
|
1736
1587
|
};
|
|
1737
1588
|
}
|
|
1738
1589
|
restoreSettingsApplicationState(snapshot) {
|
|
@@ -1751,7 +1602,6 @@ var GoalRuntime = class {
|
|
|
1751
1602
|
this.staleGoalToolCallsBlocked = snapshot.staleGoalToolCallsBlocked;
|
|
1752
1603
|
this.cancelledContinuationMarkers = new Map(snapshot.cancelledContinuationMarkers);
|
|
1753
1604
|
this.terminalDetails = snapshot.terminalDetails ? structuredClone(snapshot.terminalDetails) : void 0;
|
|
1754
|
-
this.toolPolicy.restore(snapshot.toolVisibility);
|
|
1755
1605
|
}
|
|
1756
1606
|
pauseGoalForUnavailableTools(ctx, abortTurn = true, recordUsage = true) {
|
|
1757
1607
|
const goal = this.activeGoal;
|
|
@@ -2044,4 +1894,4 @@ export {
|
|
|
2044
1894
|
isContradictoryCompletionSummary,
|
|
2045
1895
|
goalIdRejectionReason
|
|
2046
1896
|
};
|
|
2047
|
-
//# sourceMappingURL=chunk-
|
|
1897
|
+
//# sourceMappingURL=chunk-XHEFHXTF.js.map
|