@code-yeongyu/senpi 2026.7.31-2 → 2026.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/CHANGELOG.md +153 -0
  2. package/dist/core/agent-session.d.ts +1 -1
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +10 -19
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/extensions/builtin/goal/persistence.d.ts +15 -0
  7. package/dist/core/extensions/builtin/goal/persistence.d.ts.map +1 -1
  8. package/dist/core/extensions/builtin/goal/persistence.js +150 -18
  9. package/dist/core/extensions/builtin/goal/persistence.js.map +1 -1
  10. package/dist/core/extensions/builtin/gpt-apply-patch/extension.d.ts.map +1 -1
  11. package/dist/core/extensions/builtin/gpt-apply-patch/extension.js +15 -0
  12. package/dist/core/extensions/builtin/gpt-apply-patch/extension.js.map +1 -1
  13. package/dist/core/extensions/builtin/gpt-apply-patch/tool.d.ts.map +1 -1
  14. package/dist/core/extensions/builtin/gpt-apply-patch/tool.js +30 -3
  15. package/dist/core/extensions/builtin/gpt-apply-patch/tool.js.map +1 -1
  16. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-flash-0731.d.ts +3 -0
  17. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-flash-0731.d.ts.map +1 -0
  18. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-flash-0731.js +10 -0
  19. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-flash-0731.js.map +1 -0
  20. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-flash.d.ts +3 -0
  21. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-flash.d.ts.map +1 -0
  22. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-flash.js +10 -0
  23. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-flash.js.map +1 -0
  24. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-pro.d.ts +3 -0
  25. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-pro.d.ts.map +1 -0
  26. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-pro.js +11 -0
  27. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-pro.js.map +1 -0
  28. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4.d.ts +13 -0
  29. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4.d.ts.map +1 -0
  30. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4.js +60 -0
  31. package/dist/core/extensions/builtin/prompt-preset/deepseek-v4.js.map +1 -0
  32. package/dist/core/extensions/builtin/prompt-preset/presets.d.ts.map +1 -1
  33. package/dist/core/extensions/builtin/prompt-preset/presets.js +42 -0
  34. package/dist/core/extensions/builtin/prompt-preset/presets.js.map +1 -1
  35. package/dist/core/extensions/builtin/prompt-preset/settings.d.ts +1 -1
  36. package/dist/core/extensions/builtin/prompt-preset/settings.d.ts.map +1 -1
  37. package/dist/core/extensions/builtin/prompt-preset/settings.js +3 -0
  38. package/dist/core/extensions/builtin/prompt-preset/settings.js.map +1 -1
  39. package/dist/core/extensions/builtin/recommended-models/index.d.ts.map +1 -1
  40. package/dist/core/extensions/builtin/recommended-models/index.js +2 -1
  41. package/dist/core/extensions/builtin/recommended-models/index.js.map +1 -1
  42. package/dist/core/extensions/builtin/terminal/monitor-notify.d.ts.map +1 -1
  43. package/dist/core/extensions/builtin/terminal/monitor-notify.js +42 -5
  44. package/dist/core/extensions/builtin/terminal/monitor-notify.js.map +1 -1
  45. package/dist/core/extensions/builtin/terminal/tools/monitor.js +1 -1
  46. package/dist/core/extensions/builtin/terminal/tools/monitor.js.map +1 -1
  47. package/dist/core/extensions/builtin/todotools/commands.d.ts +2 -2
  48. package/dist/core/extensions/builtin/todotools/commands.d.ts.map +1 -1
  49. package/dist/core/extensions/builtin/todotools/commands.js.map +1 -1
  50. package/dist/core/extensions/builtin/todotools/index.d.ts.map +1 -1
  51. package/dist/core/extensions/builtin/todotools/index.js +6 -3
  52. package/dist/core/extensions/builtin/todotools/index.js.map +1 -1
  53. package/dist/core/extensions/builtin/todotools/state.d.ts +1 -1
  54. package/dist/core/extensions/builtin/todotools/state.d.ts.map +1 -1
  55. package/dist/core/extensions/builtin/todotools/state.js +1 -1
  56. package/dist/core/extensions/builtin/todotools/state.js.map +1 -1
  57. package/dist/core/extensions/builtin/todotools/todo-widget-component.d.ts +19 -0
  58. package/dist/core/extensions/builtin/todotools/todo-widget-component.d.ts.map +1 -0
  59. package/dist/core/extensions/builtin/todotools/todo-widget-component.js +78 -0
  60. package/dist/core/extensions/builtin/todotools/todo-widget-component.js.map +1 -0
  61. package/dist/core/extensions/builtin/todotools/todo-widget.d.ts +13 -1
  62. package/dist/core/extensions/builtin/todotools/todo-widget.d.ts.map +1 -1
  63. package/dist/core/extensions/builtin/todotools/todo-widget.js +32 -14
  64. package/dist/core/extensions/builtin/todotools/todo-widget.js.map +1 -1
  65. package/dist/core/extensions/builtin/todotools/tools/todo.d.ts +2 -2
  66. package/dist/core/extensions/builtin/todotools/tools/todo.d.ts.map +1 -1
  67. package/dist/core/extensions/builtin/todotools/tools/todo.js +1 -1
  68. package/dist/core/extensions/builtin/todotools/tools/todo.js.map +1 -1
  69. package/dist/core/extensions/builtin/tps.d.ts.map +1 -1
  70. package/dist/core/extensions/builtin/tps.js +5 -2
  71. package/dist/core/extensions/builtin/tps.js.map +1 -1
  72. package/dist/core/extensions/builtin/websearch/websearch/config.d.ts.map +1 -1
  73. package/dist/core/extensions/builtin/websearch/websearch/config.js +1 -0
  74. package/dist/core/extensions/builtin/websearch/websearch/config.js.map +1 -1
  75. package/dist/core/extensions/builtin/websearch/websearch/native.d.ts.map +1 -1
  76. package/dist/core/extensions/builtin/websearch/websearch/native.js +16 -5
  77. package/dist/core/extensions/builtin/websearch/websearch/native.js.map +1 -1
  78. package/dist/core/extensions/builtin/websearch/websearch/provider-endpoints.d.ts.map +1 -1
  79. package/dist/core/extensions/builtin/websearch/websearch/provider-endpoints.js +1 -0
  80. package/dist/core/extensions/builtin/websearch/websearch/provider-endpoints.js.map +1 -1
  81. package/dist/core/extensions/builtin/websearch/websearch/providers/anthropic.d.ts +4 -1
  82. package/dist/core/extensions/builtin/websearch/websearch/providers/anthropic.d.ts.map +1 -1
  83. package/dist/core/extensions/builtin/websearch/websearch/providers/anthropic.js +44 -37
  84. package/dist/core/extensions/builtin/websearch/websearch/providers/anthropic.js.map +1 -1
  85. package/dist/core/extensions/builtin/websearch/websearch/providers/deepseek.d.ts +3 -0
  86. package/dist/core/extensions/builtin/websearch/websearch/providers/deepseek.d.ts.map +1 -0
  87. package/dist/core/extensions/builtin/websearch/websearch/providers/deepseek.js +12 -0
  88. package/dist/core/extensions/builtin/websearch/websearch/providers/deepseek.js.map +1 -0
  89. package/dist/core/extensions/builtin/websearch/websearch/providers.d.ts.map +1 -1
  90. package/dist/core/extensions/builtin/websearch/websearch/providers.js +2 -0
  91. package/dist/core/extensions/builtin/websearch/websearch/providers.js.map +1 -1
  92. package/dist/core/extensions/builtin/websearch/websearch/renderers.d.ts.map +1 -1
  93. package/dist/core/extensions/builtin/websearch/websearch/renderers.js +2 -2
  94. package/dist/core/extensions/builtin/websearch/websearch/renderers.js.map +1 -1
  95. package/dist/core/extensions/builtin/websearch/websearch/tool.js +2 -2
  96. package/dist/core/extensions/builtin/websearch/websearch/tool.js.map +1 -1
  97. package/dist/core/extensions/builtin/websearch/websearch/types.d.ts +1 -1
  98. package/dist/core/extensions/builtin/websearch/websearch/types.d.ts.map +1 -1
  99. package/dist/core/extensions/builtin/websearch/websearch/types.js.map +1 -1
  100. package/dist/core/model-resolver.js +2 -2
  101. package/dist/core/model-resolver.js.map +1 -1
  102. package/dist/core/thinking-levels.d.ts +5 -0
  103. package/dist/core/thinking-levels.d.ts.map +1 -1
  104. package/dist/core/thinking-levels.js +9 -59
  105. package/dist/core/thinking-levels.js.map +1 -1
  106. package/dist/modes/interactive/interactive-mode.js +1 -1
  107. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  108. package/dist/modes/interactive/risky-main-model-warning.d.ts +1 -1
  109. package/dist/modes/interactive/risky-main-model-warning.d.ts.map +1 -1
  110. package/dist/modes/interactive/risky-main-model-warning.js +1 -1
  111. package/dist/modes/interactive/risky-main-model-warning.js.map +1 -1
  112. package/docs/settings.md +1 -1
  113. package/examples/extensions/overlay-test.ts +1 -1
  114. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +18 -0
  115. package/node_modules/@code-yeongyu/senpi-codemode/README.md +6 -3
  116. package/node_modules/@code-yeongyu/senpi-codemode/package.json +3 -3
  117. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-execution.ts +146 -0
  118. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-handler.ts +21 -119
  119. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-runtime.ts +157 -0
  120. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-manager.ts +55 -210
  121. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-notification.ts +98 -0
  122. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-snapshot.ts +81 -0
  123. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-state.ts +24 -0
  124. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-eval-result.ts +140 -0
  125. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-notification-queue.ts +53 -0
  126. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-request.ts +45 -0
  127. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool-options.ts +45 -0
  128. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +20 -342
  129. package/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  130. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses/fallback-state.d.ts +24 -0
  131. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses/fallback-state.d.ts.map +1 -0
  132. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses/fallback-state.js +70 -0
  133. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses/fallback-state.js.map +1 -0
  134. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.d.ts +2 -16
  135. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.d.ts.map +1 -1
  136. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +8 -56
  137. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js.map +1 -1
  138. package/node_modules/@earendil-works/pi-ai/dist/api/openai-prompt-cache.d.ts +1 -0
  139. package/node_modules/@earendil-works/pi-ai/dist/api/openai-prompt-cache.d.ts.map +1 -1
  140. package/node_modules/@earendil-works/pi-ai/dist/api/openai-prompt-cache.js +7 -0
  141. package/node_modules/@earendil-works/pi-ai/dist/api/openai-prompt-cache.js.map +1 -1
  142. package/node_modules/@earendil-works/pi-ai/dist/model.d.ts +2 -1
  143. package/node_modules/@earendil-works/pi-ai/dist/model.d.ts.map +1 -1
  144. package/node_modules/@earendil-works/pi-ai/dist/model.js.map +1 -1
  145. package/node_modules/@earendil-works/pi-ai/dist/models.d.ts +13 -0
  146. package/node_modules/@earendil-works/pi-ai/dist/models.d.ts.map +1 -1
  147. package/node_modules/@earendil-works/pi-ai/dist/models.js +71 -45
  148. package/node_modules/@earendil-works/pi-ai/dist/models.js.map +1 -1
  149. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  150. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  151. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  152. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  153. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
  154. package/node_modules/@earendil-works/pi-ai/package.json +1 -1
  155. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  156. package/node_modules/@earendil-works/pi-tui/dist/mux.js +1 -1
  157. package/node_modules/@earendil-works/pi-tui/dist/mux.js.map +1 -1
  158. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +1 -0
  159. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts.map +1 -1
  160. package/node_modules/@earendil-works/pi-tui/dist/tui.js +17 -3
  161. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
  162. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  163. package/package.json +6 -6
@@ -2,6 +2,21 @@ import type { Goal, GoalStoreRef } from "./types.ts";
2
2
  export declare function encodedThreadId(ref: GoalStoreRef): string;
3
3
  export declare function goalFilePath(ref: GoalStoreRef): string;
4
4
  export declare function readGoalFile(ref: GoalStoreRef): Promise<Goal | null>;
5
+ /**
6
+ * Imports legacy standalone `pi-goal` state into the current budget-free store.
7
+ *
8
+ * The current store always wins and legacy normalization is confined to this path.
9
+ * Invalid, unsupported, or malformed legacy files are best-effort dead-data imports:
10
+ * they remain untouched and do not block the live current store. Unexpected filesystem
11
+ * failures still propagate.
12
+ *
13
+ * Session-backed stores use their stable thread id. No-session stores enumerate the
14
+ * cwd-keyed legacy bucket because each ephemeral run receives a new thread id, and they
15
+ * inspect both the redirected Senpi-root sibling and the standalone pi agent root.
16
+ * Multiple valid live candidates are reported as a conflict rather than guessed.
17
+ *
18
+ * Returns the imported goal, or null when nothing was migrated.
19
+ */
5
20
  export declare function migrateLegacyGoalFile(ref: GoalStoreRef): Promise<Goal | null>;
6
21
  export declare function writeGoalFile(ref: GoalStoreRef, goal: Goal | null): Promise<void>;
7
22
  //# sourceMappingURL=persistence.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"persistence.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/persistence.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,IAAI,EAAwB,YAAY,EAAE,MAAM,YAAY,CAAC;AAM3E,wBAAgB,eAAe,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAEzD;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAEtD;AAED,wBAAsB,YAAY,CAAC,GAAG,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAO1E;AAED,wBAAsB,qBAAqB,CAAC,GAAG,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAmBnF;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAIvF"}
1
+ {"version":3,"file":"persistence.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/persistence.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,IAAI,EAAwB,YAAY,EAAE,MAAM,YAAY,CAAC;AAS3E,wBAAgB,eAAe,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAEzD;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAEtD;AAED,wBAAsB,YAAY,CAAC,GAAG,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAO1E;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,qBAAqB,CAAC,GAAG,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAmBnF;AA0GD,wBAAsB,aAAa,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAIvF"}
@@ -1,10 +1,14 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
- import { dirname, join } from "node:path";
2
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, sep } from "node:path";
4
5
  import { InvalidGoalStoreError, UnsupportedGoalStoreVersionError } from "./errors.js";
5
6
  import { isRecord } from "./types.js";
6
7
  import { isGoalStatus, isNonNegativeSafeInteger } from "./validation.js";
7
8
  const STORE_VERSION = 1;
9
+ const CURRENT_STORE_DIRECTORY = "goal";
10
+ const LEGACY_STORE_DIRECTORY = "pi-goal";
11
+ const LEGACY_BUDGET_LIMITED_STATUSES = ["budgetLimited", "budget_limited"];
8
12
  export function encodedThreadId(ref) {
9
13
  return encodeURIComponent(ref.threadId);
10
14
  }
@@ -21,6 +25,21 @@ export async function readGoalFile(ref) {
21
25
  throw error;
22
26
  }
23
27
  }
28
+ /**
29
+ * Imports legacy standalone `pi-goal` state into the current budget-free store.
30
+ *
31
+ * The current store always wins and legacy normalization is confined to this path.
32
+ * Invalid, unsupported, or malformed legacy files are best-effort dead-data imports:
33
+ * they remain untouched and do not block the live current store. Unexpected filesystem
34
+ * failures still propagate.
35
+ *
36
+ * Session-backed stores use their stable thread id. No-session stores enumerate the
37
+ * cwd-keyed legacy bucket because each ephemeral run receives a new thread id, and they
38
+ * inspect both the redirected Senpi-root sibling and the standalone pi agent root.
39
+ * Multiple valid live candidates are reported as a conflict rather than guessed.
40
+ *
41
+ * Returns the imported goal, or null when nothing was migrated.
42
+ */
24
43
  export async function migrateLegacyGoalFile(ref) {
25
44
  try {
26
45
  await readFile(goalFilePath(ref), "utf8");
@@ -30,20 +49,114 @@ export async function migrateLegacyGoalFile(ref) {
30
49
  if (!isMissingFile(error))
31
50
  throw error;
32
51
  }
33
- const legacyRef = { ...ref, baseDir: join(dirname(ref.baseDir), "pi-goal") };
34
- let legacyGoal;
52
+ const legacyCandidates = await readLegacyGoalCandidates(ref);
53
+ if (legacyCandidates.length > 1) {
54
+ throw new Error(`multiple legacy goals found for no-session store: ${legacyCandidates.map(({ path }) => path).join(", ")}`);
55
+ }
56
+ const candidate = legacyCandidates[0];
57
+ if (candidate === undefined)
58
+ return null;
59
+ const published = await publishMigratedGoalFile(ref, candidate.goal);
60
+ await retireLegacyGoalFile(candidate.path);
61
+ return published ? candidate.goal : null;
62
+ }
63
+ async function readLegacyGoalCandidates(ref) {
64
+ const legacyBaseDir = legacyBaseDirFor(ref.baseDir);
65
+ if (legacyBaseDir === undefined)
66
+ return [];
67
+ const cwdKey = noSessionCwdKey(ref.baseDir);
68
+ if (cwdKey === undefined) {
69
+ const candidate = await readLegacyGoalCandidate(goalFilePath({ ...ref, baseDir: legacyBaseDir }));
70
+ return candidate === null ? [] : [candidate];
71
+ }
72
+ const standaloneAgentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
73
+ const baseDirs = new Set([
74
+ legacyBaseDir,
75
+ join(standaloneAgentDir, "extensions", LEGACY_STORE_DIRECTORY, "no-session", cwdKey),
76
+ ]);
77
+ const candidatePaths = [];
78
+ for (const baseDir of baseDirs) {
79
+ let entries;
80
+ try {
81
+ entries = await readdir(baseDir, { withFileTypes: true });
82
+ }
83
+ catch (error) {
84
+ if (isMissingFile(error))
85
+ continue;
86
+ throw error;
87
+ }
88
+ for (const entry of entries) {
89
+ if (entry.isFile() && entry.name.endsWith(".json"))
90
+ candidatePaths.push(join(baseDir, entry.name));
91
+ }
92
+ }
93
+ const candidates = [];
94
+ for (const path of candidatePaths.sort()) {
95
+ const candidate = await readLegacyGoalCandidate(path);
96
+ if (candidate !== null)
97
+ candidates.push(candidate);
98
+ }
99
+ return candidates;
100
+ }
101
+ async function readLegacyGoalCandidate(path) {
102
+ let goal;
35
103
  try {
36
- legacyGoal = parseGoalFile(await readFile(goalFilePath(legacyRef), "utf8")).goal;
104
+ goal = parseGoalFile(await readFile(path, "utf8"), { legacy: true }).goal;
37
105
  }
38
106
  catch (error) {
39
- if (isMissingFile(error))
107
+ if (isMissingFile(error) || isIgnoredLegacyStoreError(error))
40
108
  return null;
41
109
  throw error;
42
110
  }
43
- if (legacyGoal === null)
111
+ if (goal === null) {
112
+ await retireLegacyGoalFile(path);
44
113
  return null;
45
- await writeGoalFile(ref, legacyGoal);
46
- return legacyGoal;
114
+ }
115
+ return { path, goal };
116
+ }
117
+ async function retireLegacyGoalFile(path) {
118
+ try {
119
+ await rename(path, `${path}.migrated`);
120
+ }
121
+ catch {
122
+ // Retirement is best-effort: a preserved legacy file must never fail live migration.
123
+ }
124
+ }
125
+ function isIgnoredLegacyStoreError(error) {
126
+ return (error instanceof InvalidGoalStoreError ||
127
+ error instanceof UnsupportedGoalStoreVersionError ||
128
+ error instanceof SyntaxError);
129
+ }
130
+ /**
131
+ * Maps a current goal-store directory to its legacy `pi-goal` counterpart by replacing
132
+ * the `goal` path segment itself.
133
+ *
134
+ * Both store layouts must map correctly:
135
+ * <sessionDir>/extensions/goal -> <sessionDir>/extensions/pi-goal
136
+ * <agentDir>/extensions/goal/no-session/<cwdKey>
137
+ * -> <agentDir>/extensions/pi-goal/no-session/<cwdKey>
138
+ *
139
+ * Swapping `dirname(baseDir)` only works for the first layout; in the no-session
140
+ * fallback it points inside the current store tree, which both misses real legacy
141
+ * state and can import an unrelated nested directory.
142
+ */
143
+ function legacyBaseDirFor(baseDir) {
144
+ const segments = pathSegments(baseDir);
145
+ const goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);
146
+ if (goalIndex === -1)
147
+ return undefined;
148
+ segments[goalIndex] = LEGACY_STORE_DIRECTORY;
149
+ return segments.join(sep);
150
+ }
151
+ function noSessionCwdKey(baseDir) {
152
+ const segments = pathSegments(baseDir);
153
+ const goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);
154
+ if (goalIndex === -1 || segments[goalIndex + 1] !== "no-session")
155
+ return undefined;
156
+ return segments[goalIndex + 2];
157
+ }
158
+ function pathSegments(path) {
159
+ return path.split(/[\\/]/);
47
160
  }
48
161
  export async function writeGoalFile(ref, goal) {
49
162
  const filePath = goalFilePath(ref);
@@ -66,19 +179,30 @@ async function writeGoalFileAtomic(filePath, contents) {
66
179
  throw error;
67
180
  }
68
181
  }
69
- function parseGoalFile(raw) {
182
+ async function publishMigratedGoalFile(ref, goal) {
183
+ const filePath = goalFilePath(ref);
184
+ await mkdir(dirname(filePath), { recursive: true });
185
+ const contents = `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\n`;
186
+ try {
187
+ await writeFile(filePath, contents, { encoding: "utf8", mode: 0o600, flag: "wx" });
188
+ return true;
189
+ }
190
+ catch (error) {
191
+ if (isFileSystemError(error, "EEXIST"))
192
+ return false;
193
+ throw error;
194
+ }
195
+ }
196
+ function parseGoalFile(raw, { legacy = false } = {}) {
70
197
  const parsed = parseGoalFileJson(raw);
71
198
  if (!isRecord(parsed))
72
199
  throw new InvalidGoalStoreError("goal store must be a JSON object");
73
200
  if (parsed.version !== STORE_VERSION)
74
201
  throw new UnsupportedGoalStoreVersionError("unsupported goal store version");
75
- const normalizedGoal = normalizeLegacyGoal(parsed.goal);
76
- if (normalizedGoal !== null && !isGoal(normalizedGoal))
202
+ const goal = legacy ? normalizeLegacyGoal(parsed.goal) : parsed.goal;
203
+ if (goal !== null && !isGoal(goal))
77
204
  throw new InvalidGoalStoreError("goal store contains an invalid goal");
78
- return {
79
- version: STORE_VERSION,
80
- goal: normalizedGoal === null ? null : sanitizeContinuationState(normalizedGoal),
81
- };
205
+ return { version: STORE_VERSION, goal: goal === null ? null : sanitizeContinuationState(goal) };
82
206
  }
83
207
  function parseGoalFileJson(raw) {
84
208
  let parsed;
@@ -100,12 +224,17 @@ function parseGoalFileJson(raw) {
100
224
  }
101
225
  return parsed;
102
226
  }
227
+ /**
228
+ * Drops legacy budget enforcement: `tokenBudget` is a budgeting input in `pi-goal`, and
229
+ * `budgetLimited` is a status this fork removed, so a budget-limited legacy goal resumes
230
+ * as `active`. This runs only on the legacy import path.
231
+ */
103
232
  function normalizeLegacyGoal(value) {
104
233
  if (!isRecord(value))
105
234
  return value;
106
235
  const normalized = { ...value };
107
236
  delete normalized.tokenBudget;
108
- if (normalized.status === "budgetLimited" || normalized.status === "budget_limited") {
237
+ if (typeof normalized.status === "string" && LEGACY_BUDGET_LIMITED_STATUSES.includes(normalized.status)) {
109
238
  normalized.status = "active";
110
239
  }
111
240
  return normalized;
@@ -186,6 +315,9 @@ function sanitizeContinuationState(goal) {
186
315
  return next;
187
316
  }
188
317
  function isMissingFile(error) {
189
- return error instanceof Error && "code" in error && error.code === "ENOENT";
318
+ return isFileSystemError(error, "ENOENT");
319
+ }
320
+ function isFileSystemError(error, code) {
321
+ return error instanceof Error && "code" in error && error.code === code;
190
322
  }
191
323
  //# sourceMappingURL=persistence.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"persistence.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,qBAAqB,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAEtF,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEzE,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB,MAAM,UAAU,eAAe,CAAC,GAAiB;IAChD,OAAO,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAAiB;IAC7C,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC1D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,GAAiB;IACnD,IAAI,CAAC;QACJ,OAAO,aAAa,C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AC,CAAC;QACpF,CAAC,KAAK,CAAC,WAAW,KAAK,SAAS,IAAI,wBAAwB,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAChF,CAAC;AACH,CAAC;AAED,SAAS,qBAAqB,CAAC,KAA8B,EAAE,MAAkB;IAChF,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QAC1B,OAAO,CACN,OAAO,KAAK,CAAC,aAAa,KAAK,QAAQ;YACvC,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;YACrC,wBAAwB,CAAC,KAAK,CAAC,SAAS,CAAC,CACzC,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC,aAAa,KAAK,SAAS,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CAAC;AAC3E,CAAC;AAED,SAAS,yBAAyB,CAAC,IAAU;IAC5C,MAAM,IAAI,GAAS,EAAE,GAAG,IAAI,EAAE,CAAC;IAC/B,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,wBAAwB,CAAC;QAAE,OAAO,IAAI,CAAC,wBAAwB,CAAC;IACnG,IAAI,OAAO,IAAI,CAAC,yBAAyB,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,yBAAyB,CAAC;IAC9F,OAAO,IAAI,CAAC;AACb,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;AAC7E,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { InvalidGoalStoreError, UnsupportedGoalStoreVersionError } from \"./errors.ts\";\nimport type { Goal, GoalFile, GoalStatus, GoalStoreRef } from \"./types.ts\";\nimport { isRecord } from \"./types.ts\";\nimport { isGoalStatus, isNonNegativeSafeInteger } from \"./validation.ts\";\n\nconst STORE_VERSION = 1;\n\nexport function encodedThreadId(ref: GoalStoreRef): string {\n\treturn encodeURIComponent(ref.threadId);\n}\n\nexport function goalFilePath(ref: GoalStoreRef): string {\n\treturn join(ref.baseDir, `${encodedThreadId(ref)}.json`);\n}\n\nexport async function readGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\treturn parseGoalFile(await readFile(goalFilePath(ref), \"utf8\")).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error)) return null;\n\t\tthrow error;\n\t}\n}\n\nexport async function migrateLegacyGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\tawait readFile(goalFilePath(ref), \"utf8\");\n\t\treturn null;\n\t} catch (error) {\n\t\tif (!isMissingFile(error)) throw error;\n\t}\n\n\tconst legacyRef = { ...ref, baseDir: join(dirname(ref.baseDir), \"pi-goal\") };\n\tlet legacyGoal: Goal | null;\n\ttry {\n\t\tlegacyGoal = parseGoalFile(await readFile(goalFilePath(legacyRef), \"utf8\")).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error)) return null;\n\t\tthrow error;\n\t}\n\tif (legacyGoal === null) return null;\n\tawait writeGoalFile(ref, legacyGoal);\n\treturn legacyGoal;\n}\n\nexport async function writeGoalFile(ref: GoalStoreRef, goal: Goal | null): Promise<void> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tawait writeGoalFileAtomic(filePath, `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`);\n}\n\nasync function writeGoalFileAtomic(filePath: string, contents: string): Promise<void> {\n\tconst tempPath = join(dirname(filePath), `.goal-${randomUUID()}.tmp`);\n\ttry {\n\t\tawait writeFile(tempPath, contents, { encoding: \"utf8\", mode: 0o600 });\n\t\tawait rename(tempPath, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait rm(tempPath, { force: true });\n\t\t} catch (cleanupError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[error, cleanupError],\n\t\t\t\t\"goal store write failed and its temporary file could not be removed\",\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction parseGoalFile(raw: string): GoalFile {\n\tconst parsed = parseGoalFileJson(raw);\n\tif (!isRecord(parsed)) throw new InvalidGoalStoreError(\"goal store must be a JSON object\");\n\tif (parsed.version !== STORE_VERSION) throw new UnsupportedGoalStoreVersionError(\"unsupported goal store version\");\n\tconst normalizedGoal = normalizeLegacyGoal(parsed.goal);\n\tif (normalizedGoal !== null && !isGoal(normalizedGoal))\n\t\tthrow new InvalidGoalStoreError(\"goal store contains an invalid goal\");\n\treturn {\n\t\tversion: STORE_VERSION,\n\t\tgoal: normalizedGoal === null ? null : sanitizeContinuationState(normalizedGoal),\n\t};\n}\n\nfunction parseGoalFileJson(raw: string): unknown {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (error) {\n\t\tif (!(error instanceof SyntaxError)) throw error;\n\t\tconst recovered = recoverGoalFileWithStaleClosingBraces(raw);\n\t\tif (recovered === undefined) throw error;\n\t\ttry {\n\t\t\tparsed = JSON.parse(recovered);\n\t\t} catch {\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn parsed;\n}\n\nfunction normalizeLegacyGoal(value: unknown): unknown {\n\tif (!isRecord(value)) return value;\n\tconst normalized = { ...value };\n\tdelete normalized.tokenBudget;\n\tif (normalized.status === \"budgetLimited\" || normalized.status === \"budget_limited\") {\n\t\tnormalized.status = \"active\";\n\t}\n\treturn normalized;\n}\n\nfunction recoverGoalFileWithStaleClosingBraces(raw: string): string | undefined {\n\tlet rootStart = 0;\n\twhile (rootStart < raw.length && /[\\t\\n\\r ]/.test(raw[rootStart] ?? \"\")) rootStart += 1;\n\tif (raw[rootStart] !== \"{\") return undefined;\n\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (let index = rootStart; index < raw.length; index += 1) {\n\t\tconst character = raw[index];\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\telse if (character === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') inString = true;\n\t\telse if (character === \"{\" || character === \"[\") depth += 1;\n\t\telse if (character === \"}\" || character === \"]\") {\n\t\t\tdepth -= 1;\n\t\t\tif (depth < 0) return undefined;\n\t\t\tif (depth === 0) {\n\t\t\t\tlet hasStaleClosingBrace = false;\n\t\t\t\tfor (let suffixIndex = index + 1; suffixIndex < raw.length; suffixIndex += 1) {\n\t\t\t\t\tconst suffix = raw[suffixIndex];\n\t\t\t\t\tif (suffix === \"}\") hasStaleClosingBrace = true;\n\t\t\t\t\telse if (suffix !== \" \" && suffix !== \"\\t\" && suffix !== \"\\n\" && suffix !== \"\\r\") return undefined;\n\t\t\t\t}\n\t\t\t\treturn hasStaleClosingBrace ? raw.slice(0, index + 1) : undefined;\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isGoal(value: unknown): value is Goal {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.threadId === \"string\" &&\n\t\ttypeof value.objective === \"string\" &&\n\t\tisGoalStatus(value.status) &&\n\t\t(value.tokenBudget === undefined || isNonNegativeSafeInteger(value.tokenBudget)) &&\n\t\thasValidBlockedFields(value, value.status) &&\n\t\tisNonNegativeSafeInteger(value.tokensUsed) &&\n\t\tisNonNegativeSafeInteger(value.timeUsedSeconds) &&\n\t\tisNonNegativeSafeInteger(value.createdAt) &&\n\t\tisNonNegativeSafeInteger(value.updatedAt) &&\n\t\t(value.lastStartedAt === undefined || isNonNegativeSafeInteger(value.lastStartedAt)) &&\n\t\t(value.completedAt === undefined || isNonNegativeSafeInteger(value.completedAt))\n\t);\n}\n\nfunction hasValidBlockedFields(value: Record<string, unknown>, status: GoalStatus): boolean {\n\tif (status === \"blocked\") {\n\t\treturn (\n\t\t\ttypeof value.blockedReason === \"string\" &&\n\t\t\tvalue.blockedReason.trim().length > 0 &&\n\t\t\tisNonNegativeSafeInteger(value.blockedAt)\n\t\t);\n\t}\n\treturn value.blockedReason === undefined && value.blockedAt === undefined;\n}\n\nfunction sanitizeContinuationState(goal: Goal): Goal {\n\tconst next: Goal = { ...goal };\n\tif (!isNonNegativeSafeInteger(next.consecutiveContinuations)) delete next.consecutiveContinuations;\n\tif (typeof next.lastContinuationSignature !== \"string\") delete next.lastContinuationSignature;\n\treturn next;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"ENOENT\";\n}\n"]}
1
+ {"version":3,"file":"persistence.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAEtF,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEzE,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,uBAAuB,GAAG,MAAM,CAAC;AACvC,MAAM,sBAAsB,GAAG,SAAS,CAAC;AACzC,MAAM,8BAA8B,GAAG,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;AAE3E,MAAM,UAAU,eAAe,CAAC,GAAiB;IAChD,OAAO,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AACzC,CAAC;AAED,MAAM,UAAU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AAC;IACD,OAAO,KAAK,CAAC,aAAa,KAAK,SAAS,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CAAC;AAC3E,CAAC;AAED,SAAS,yBAAyB,CAAC,IAAU;IAC5C,MAAM,IAAI,GAAS,EAAE,GAAG,IAAI,EAAE,CAAC;IAC/B,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,wBAAwB,CAAC;QAAE,OAAO,IAAI,CAAC,wBAAwB,CAAC;IACnG,IAAI,OAAO,IAAI,CAAC,yBAAyB,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,yBAAyB,CAAC;IAC9F,OAAO,IAAI,CAAC;AACb,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;AAC3C,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAE,IAAY;IACtD,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AACzE,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Dirent } from \"node:fs\";\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, sep } from \"node:path\";\nimport { InvalidGoalStoreError, UnsupportedGoalStoreVersionError } from \"./errors.ts\";\nimport type { Goal, GoalFile, GoalStatus, GoalStoreRef } from \"./types.ts\";\nimport { isRecord } from \"./types.ts\";\nimport { isGoalStatus, isNonNegativeSafeInteger } from \"./validation.ts\";\n\nconst STORE_VERSION = 1;\nconst CURRENT_STORE_DIRECTORY = \"goal\";\nconst LEGACY_STORE_DIRECTORY = \"pi-goal\";\nconst LEGACY_BUDGET_LIMITED_STATUSES = [\"budgetLimited\", \"budget_limited\"];\n\nexport function encodedThreadId(ref: GoalStoreRef): string {\n\treturn encodeURIComponent(ref.threadId);\n}\n\nexport function goalFilePath(ref: GoalStoreRef): string {\n\treturn join(ref.baseDir, `${encodedThreadId(ref)}.json`);\n}\n\nexport async function readGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\treturn parseGoalFile(await readFile(goalFilePath(ref), \"utf8\")).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error)) return null;\n\t\tthrow error;\n\t}\n}\n\n/**\n * Imports legacy standalone `pi-goal` state into the current budget-free store.\n *\n * The current store always wins and legacy normalization is confined to this path.\n * Invalid, unsupported, or malformed legacy files are best-effort dead-data imports:\n * they remain untouched and do not block the live current store. Unexpected filesystem\n * failures still propagate.\n *\n * Session-backed stores use their stable thread id. No-session stores enumerate the\n * cwd-keyed legacy bucket because each ephemeral run receives a new thread id, and they\n * inspect both the redirected Senpi-root sibling and the standalone pi agent root.\n * Multiple valid live candidates are reported as a conflict rather than guessed.\n *\n * Returns the imported goal, or null when nothing was migrated.\n */\nexport async function migrateLegacyGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\tawait readFile(goalFilePath(ref), \"utf8\");\n\t\treturn null;\n\t} catch (error) {\n\t\tif (!isMissingFile(error)) throw error;\n\t}\n\n\tconst legacyCandidates = await readLegacyGoalCandidates(ref);\n\tif (legacyCandidates.length > 1) {\n\t\tthrow new Error(\n\t\t\t`multiple legacy goals found for no-session store: ${legacyCandidates.map(({ path }) => path).join(\", \")}`,\n\t\t);\n\t}\n\tconst candidate = legacyCandidates[0];\n\tif (candidate === undefined) return null;\n\tconst published = await publishMigratedGoalFile(ref, candidate.goal);\n\tawait retireLegacyGoalFile(candidate.path);\n\treturn published ? candidate.goal : null;\n}\n\ninterface LegacyGoalCandidate {\n\tpath: string;\n\tgoal: Goal;\n}\n\nasync function readLegacyGoalCandidates(ref: GoalStoreRef): Promise<LegacyGoalCandidate[]> {\n\tconst legacyBaseDir = legacyBaseDirFor(ref.baseDir);\n\tif (legacyBaseDir === undefined) return [];\n\tconst cwdKey = noSessionCwdKey(ref.baseDir);\n\tif (cwdKey === undefined) {\n\t\tconst candidate = await readLegacyGoalCandidate(goalFilePath({ ...ref, baseDir: legacyBaseDir }));\n\t\treturn candidate === null ? [] : [candidate];\n\t}\n\n\tconst standaloneAgentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), \".pi\", \"agent\");\n\tconst baseDirs = new Set([\n\t\tlegacyBaseDir,\n\t\tjoin(standaloneAgentDir, \"extensions\", LEGACY_STORE_DIRECTORY, \"no-session\", cwdKey),\n\t]);\n\tconst candidatePaths: string[] = [];\n\tfor (const baseDir of baseDirs) {\n\t\tlet entries: Dirent<string>[];\n\t\ttry {\n\t\t\tentries = await readdir(baseDir, { withFileTypes: true });\n\t\t} catch (error) {\n\t\t\tif (isMissingFile(error)) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isFile() && entry.name.endsWith(\".json\")) candidatePaths.push(join(baseDir, entry.name));\n\t\t}\n\t}\n\n\tconst candidates: LegacyGoalCandidate[] = [];\n\tfor (const path of candidatePaths.sort()) {\n\t\tconst candidate = await readLegacyGoalCandidate(path);\n\t\tif (candidate !== null) candidates.push(candidate);\n\t}\n\treturn candidates;\n}\n\nasync function readLegacyGoalCandidate(path: string): Promise<LegacyGoalCandidate | null> {\n\tlet goal: Goal | null;\n\ttry {\n\t\tgoal = parseGoalFile(await readFile(path, \"utf8\"), { legacy: true }).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error) || isIgnoredLegacyStoreError(error)) return null;\n\t\tthrow error;\n\t}\n\tif (goal === null) {\n\t\tawait retireLegacyGoalFile(path);\n\t\treturn null;\n\t}\n\treturn { path, goal };\n}\n\nasync function retireLegacyGoalFile(path: string): Promise<void> {\n\ttry {\n\t\tawait rename(path, `${path}.migrated`);\n\t} catch {\n\t\t// Retirement is best-effort: a preserved legacy file must never fail live migration.\n\t}\n}\n\nfunction isIgnoredLegacyStoreError(error: unknown): boolean {\n\treturn (\n\t\terror instanceof InvalidGoalStoreError ||\n\t\terror instanceof UnsupportedGoalStoreVersionError ||\n\t\terror instanceof SyntaxError\n\t);\n}\n\n/**\n * Maps a current goal-store directory to its legacy `pi-goal` counterpart by replacing\n * the `goal` path segment itself.\n *\n * Both store layouts must map correctly:\n * <sessionDir>/extensions/goal -> <sessionDir>/extensions/pi-goal\n * <agentDir>/extensions/goal/no-session/<cwdKey>\n * -> <agentDir>/extensions/pi-goal/no-session/<cwdKey>\n *\n * Swapping `dirname(baseDir)` only works for the first layout; in the no-session\n * fallback it points inside the current store tree, which both misses real legacy\n * state and can import an unrelated nested directory.\n */\nfunction legacyBaseDirFor(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1) return undefined;\n\tsegments[goalIndex] = LEGACY_STORE_DIRECTORY;\n\treturn segments.join(sep);\n}\n\nfunction noSessionCwdKey(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1 || segments[goalIndex + 1] !== \"no-session\") return undefined;\n\treturn segments[goalIndex + 2];\n}\n\nfunction pathSegments(path: string): string[] {\n\treturn path.split(/[\\\\/]/);\n}\n\nexport async function writeGoalFile(ref: GoalStoreRef, goal: Goal | null): Promise<void> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tawait writeGoalFileAtomic(filePath, `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`);\n}\n\nasync function writeGoalFileAtomic(filePath: string, contents: string): Promise<void> {\n\tconst tempPath = join(dirname(filePath), `.goal-${randomUUID()}.tmp`);\n\ttry {\n\t\tawait writeFile(tempPath, contents, { encoding: \"utf8\", mode: 0o600 });\n\t\tawait rename(tempPath, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait rm(tempPath, { force: true });\n\t\t} catch (cleanupError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[error, cleanupError],\n\t\t\t\t\"goal store write failed and its temporary file could not be removed\",\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function publishMigratedGoalFile(ref: GoalStoreRef, goal: Goal): Promise<boolean> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tconst contents = `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`;\n\ttry {\n\t\tawait writeFile(filePath, contents, { encoding: \"utf8\", mode: 0o600, flag: \"wx\" });\n\t\treturn true;\n\t} catch (error) {\n\t\tif (isFileSystemError(error, \"EEXIST\")) return false;\n\t\tthrow error;\n\t}\n}\n\nfunction parseGoalFile(raw: string, { legacy = false }: { legacy?: boolean } = {}): GoalFile {\n\tconst parsed = parseGoalFileJson(raw);\n\tif (!isRecord(parsed)) throw new InvalidGoalStoreError(\"goal store must be a JSON object\");\n\tif (parsed.version !== STORE_VERSION) throw new UnsupportedGoalStoreVersionError(\"unsupported goal store version\");\n\tconst goal = legacy ? normalizeLegacyGoal(parsed.goal) : parsed.goal;\n\tif (goal !== null && !isGoal(goal)) throw new InvalidGoalStoreError(\"goal store contains an invalid goal\");\n\treturn { version: STORE_VERSION, goal: goal === null ? null : sanitizeContinuationState(goal) };\n}\n\nfunction parseGoalFileJson(raw: string): unknown {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (error) {\n\t\tif (!(error instanceof SyntaxError)) throw error;\n\t\tconst recovered = recoverGoalFileWithStaleClosingBraces(raw);\n\t\tif (recovered === undefined) throw error;\n\t\ttry {\n\t\t\tparsed = JSON.parse(recovered);\n\t\t} catch {\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn parsed;\n}\n\n/**\n * Drops legacy budget enforcement: `tokenBudget` is a budgeting input in `pi-goal`, and\n * `budgetLimited` is a status this fork removed, so a budget-limited legacy goal resumes\n * as `active`. This runs only on the legacy import path.\n */\nfunction normalizeLegacyGoal(value: unknown): unknown {\n\tif (!isRecord(value)) return value;\n\tconst normalized = { ...value };\n\tdelete normalized.tokenBudget;\n\tif (typeof normalized.status === \"string\" && LEGACY_BUDGET_LIMITED_STATUSES.includes(normalized.status)) {\n\t\tnormalized.status = \"active\";\n\t}\n\treturn normalized;\n}\n\nfunction recoverGoalFileWithStaleClosingBraces(raw: string): string | undefined {\n\tlet rootStart = 0;\n\twhile (rootStart < raw.length && /[\\t\\n\\r ]/.test(raw[rootStart] ?? \"\")) rootStart += 1;\n\tif (raw[rootStart] !== \"{\") return undefined;\n\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (let index = rootStart; index < raw.length; index += 1) {\n\t\tconst character = raw[index];\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\telse if (character === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') inString = true;\n\t\telse if (character === \"{\" || character === \"[\") depth += 1;\n\t\telse if (character === \"}\" || character === \"]\") {\n\t\t\tdepth -= 1;\n\t\t\tif (depth < 0) return undefined;\n\t\t\tif (depth === 0) {\n\t\t\t\tlet hasStaleClosingBrace = false;\n\t\t\t\tfor (let suffixIndex = index + 1; suffixIndex < raw.length; suffixIndex += 1) {\n\t\t\t\t\tconst suffix = raw[suffixIndex];\n\t\t\t\t\tif (suffix === \"}\") hasStaleClosingBrace = true;\n\t\t\t\t\telse if (suffix !== \" \" && suffix !== \"\\t\" && suffix !== \"\\n\" && suffix !== \"\\r\") return undefined;\n\t\t\t\t}\n\t\t\t\treturn hasStaleClosingBrace ? raw.slice(0, index + 1) : undefined;\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isGoal(value: unknown): value is Goal {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.threadId === \"string\" &&\n\t\ttypeof value.objective === \"string\" &&\n\t\tisGoalStatus(value.status) &&\n\t\t(value.tokenBudget === undefined || isNonNegativeSafeInteger(value.tokenBudget)) &&\n\t\thasValidBlockedFields(value, value.status) &&\n\t\tisNonNegativeSafeInteger(value.tokensUsed) &&\n\t\tisNonNegativeSafeInteger(value.timeUsedSeconds) &&\n\t\tisNonNegativeSafeInteger(value.createdAt) &&\n\t\tisNonNegativeSafeInteger(value.updatedAt) &&\n\t\t(value.lastStartedAt === undefined || isNonNegativeSafeInteger(value.lastStartedAt)) &&\n\t\t(value.completedAt === undefined || isNonNegativeSafeInteger(value.completedAt))\n\t);\n}\n\nfunction hasValidBlockedFields(value: Record<string, unknown>, status: GoalStatus): boolean {\n\tif (status === \"blocked\") {\n\t\treturn (\n\t\t\ttypeof value.blockedReason === \"string\" &&\n\t\t\tvalue.blockedReason.trim().length > 0 &&\n\t\t\tisNonNegativeSafeInteger(value.blockedAt)\n\t\t);\n\t}\n\treturn value.blockedReason === undefined && value.blockedAt === undefined;\n}\n\nfunction sanitizeContinuationState(goal: Goal): Goal {\n\tconst next: Goal = { ...goal };\n\tif (!isNonNegativeSafeInteger(next.consecutiveContinuations)) delete next.consecutiveContinuations;\n\tif (typeof next.lastContinuationSignature !== \"string\") delete next.lastContinuationSignature;\n\treturn next;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n\treturn isFileSystemError(error, \"ENOENT\");\n}\n\nfunction isFileSystemError(error: unknown, code: string): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === code;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"extension.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/gpt-apply-patch/extension.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAO,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,KAAK,EACX,sBAAsB,EAGtB,kBAAkB,EAClB,MAAM,YAAY,CAAC;AAepB,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,GAAG,SAAS,GAAG,kBAAkB,CAK9G;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,GAAG,SAAS,GAAG,OAAO,CAE9F;AAkDD,wBAAgB,2BAA2B,CAAC,EAAE,EAAE,sBAAsB,GAAG,IAAI,CAc5E;eAEc,2BAA2B"}
1
+ {"version":3,"file":"extension.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/gpt-apply-patch/extension.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAO,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,KAAK,EACX,sBAAsB,EAGtB,kBAAkB,EAClB,MAAM,YAAY,CAAC;AAepB,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,GAAG,SAAS,GAAG,kBAAkB,CAK9G;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,GAAG,SAAS,GAAG,OAAO,CAE9F;AA0DD,wBAAgB,2BAA2B,CAAC,EAAE,EAAE,sBAAsB,GAAG,IAAI,CAoB5E;eAEc,2BAA2B"}
@@ -37,6 +37,15 @@ function replaceEditToolsWithApplyPatch(toolNames) {
37
37
  const at = insertIndex === -1 ? filteredToolNames.length : Math.min(insertIndex, filteredToolNames.length);
38
38
  return [...filteredToolNames.slice(0, at), APPLY_PATCH_NAME, ...filteredToolNames.slice(at)];
39
39
  }
40
+ function hasApplyPatchFailures(details) {
41
+ if (typeof details !== "object" || details === null)
42
+ return false;
43
+ const result = Reflect.get(details, "result");
44
+ if (typeof result !== "object" || result === null)
45
+ return false;
46
+ const failures = Reflect.get(result, "failures");
47
+ return Array.isArray(failures) && failures.length > 0;
48
+ }
40
49
  function syncToolset(pi, model, state, variants) {
41
50
  const mode = getApplyPatchWireMode(model);
42
51
  const currentToolNames = pi.getActiveTools();
@@ -70,6 +79,12 @@ export function registerApplyPatchExtension(pi) {
70
79
  };
71
80
  state.activeVariant = "freeform";
72
81
  pi.registerTool(variants.freeform);
82
+ pi.on("tool_result", async (event) => {
83
+ if (event.toolName !== APPLY_PATCH_NAME || event.isError || !hasApplyPatchFailures(event.details)) {
84
+ return undefined;
85
+ }
86
+ return { isError: true };
87
+ });
73
88
  pi.on("session_start", async (_event, ctx) => {
74
89
  syncToolset(pi, ctx.model, state, variants);
75
90
  });
@@ -1 +1 @@
1
- {"version":3,"file":"extension.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/gpt-apply-patch/extension.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAQjD,MAAM,yBAAyB,GAAG,IAAI,GAAG,CAAM;IAC9C,kBAAkB;IAClB,wBAAwB;IACxB,wBAAwB;CACxB,CAAC,CAAC;AACH,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAM,CAAC,oBAAoB,CAAC,CAAC,CAAC;AACnE,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;AACnD,MAAM,gBAAgB,GAAG,aAAa,CAAC;AAEvC,SAAS,OAAO,CAAC,KAAoD;IACpE,OAAO,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC;AAC9C,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAAoD;IACzF,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,MAAM,CAAC;IACnC,IAAI,yBAAyB,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC;QAAE,OAAO,UAAU,CAAC;IAChE,IAAI,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,C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AAC,CAAC,QAAQ,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;IAClG,MAAM,QAAQ,GAAG,CAAC,GAAG,iBAAiB,CAAC,gBAAgB,CAAC,EAAE,GAAG,UAAU,CAAC,CAAC;IACzE,KAAK,CAAC,oBAAoB,GAAG,EAAE,CAAC;IAChC,EAAE,CAAC,cAAc,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,2BAA2B,CAAC,EAA0B;IACrE,MAAM,KAAK,GAAuE,EAAE,oBAAoB,EAAE,EAAE,EAAE,CAAC;IAC/G,MAAM,QAAQ,GAAG;QAChB,QAAQ,EAAE,oBAAoB,CAAC,UAAU,CAAC;QAC1C,IAAI,EAAE,oBAAoB,CAAC,MAAM,CAAC;KACzB,CAAC;IACX,KAAK,CAAC,aAAa,GAAG,UAAU,CAAC;IACjC,EAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IACnC,EAAE,CAAC,EAAE,CAAC,eAAe,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE;QAC5C,WAAW,CAAC,EAAE,EAAE,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC7C,CAAC,CAAC,CAAC;IACH,EAAE,CAAC,EAAE,CAAC,cAAc,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;QACrC,WAAW,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC/C,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,eAAe,2BAA2B,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { createApplyPatchTool } from \"./tool.ts\";\nimport type {\n\tApplyPatchExtensionAPI,\n\tApplyPatchToolsetState,\n\tApplyPatchToolVariant,\n\tApplyPatchWireMode,\n} from \"./types.ts\";\n\nconst APPLY_PATCH_FREEFORM_APIS = new Set<Api>([\n\t\"openai-responses\",\n\t\"azure-openai-responses\",\n\t\"openai-codex-responses\",\n]);\nconst APPLY_PATCH_JSON_APIS = new Set<Api>([\"openai-completions\"]);\nconst EDIT_TOOL_NAMES = new Set([\"write\", \"edit\"]);\nconst APPLY_PATCH_NAME = \"apply_patch\";\n\nfunction isGptId(model: Pick<Model<string>, \"api\" | \"id\"> | undefined): model is Pick<Model<string>, \"api\" | \"id\"> {\n\treturn model?.id.startsWith(\"gpt-\") ?? false;\n}\n\nexport function getApplyPatchWireMode(model: Pick<Model<string>, \"api\" | \"id\"> | undefined): ApplyPatchWireMode {\n\tif (!isGptId(model)) return \"none\";\n\tif (APPLY_PATCH_FREEFORM_APIS.has(model.api)) return \"freeform\";\n\tif (APPLY_PATCH_JSON_APIS.has(model.api)) return \"json\";\n\treturn \"none\";\n}\n\nexport function isOpenAIGptModel(model: Pick<Model<string>, \"api\" | \"id\"> | undefined): boolean {\n\treturn getApplyPatchWireMode(model) === \"freeform\";\n}\n\nfunction hasEditTools(toolNames: string[]): boolean {\n\treturn toolNames.some((toolName) => EDIT_TOOL_NAMES.has(toolName));\n}\n\nfunction withoutApplyPatch(toolNames: string[]): string[] {\n\treturn toolNames.filter((toolName) => toolName !== APPLY_PATCH_NAME);\n}\n\nfunction replaceEditToolsWithApplyPatch(toolNames: string[]): string[] {\n\tconst hadApplyPatch = toolNames.includes(APPLY_PATCH_NAME);\n\tconst insertIndex = toolNames.findIndex(\n\t\t(toolName) => EDIT_TOOL_NAMES.has(toolName) || toolName === APPLY_PATCH_NAME,\n\t);\n\tconst filteredToolNames = withoutApplyPatch(toolNames).filter((toolName) => !EDIT_TOOL_NAMES.has(toolName));\n\tif (!hasEditTools(toolNames) && !hadApplyPatch) return filteredToolNames;\n\tconst at = insertIndex === -1 ? filteredToolNames.length : Math.min(insertIndex, filteredToolNames.length);\n\treturn [...filteredToolNames.slice(0, at), APPLY_PATCH_NAME, ...filteredToolNames.slice(at)];\n}\n\nfunction syncToolset(\n\tpi: ApplyPatchExtensionAPI,\n\tmodel: Model<string> | undefined,\n\tstate: ApplyPatchToolsetState & { activeVariant?: ApplyPatchToolVariant },\n\tvariants: Readonly<Record<ApplyPatchToolVariant, ReturnType<typeof createApplyPatchTool>>>,\n): void {\n\tconst mode = getApplyPatchWireMode(model);\n\tconst currentToolNames = pi.getActiveTools();\n\tif (mode !== \"none\") {\n\t\tif (state.activeVariant !== mode) {\n\t\t\tpi.registerTool(variants[mode]);\n\t\t\tstate.activeVariant = mode;\n\t\t}\n\t\tconst activeEdit = currentToolNames.filter((toolName) => EDIT_TOOL_NAMES.has(toolName));\n\t\tif (activeEdit.length > 0) state.removedEditToolNames = activeEdit;\n\t\tpi.setActiveTools(replaceEditToolsWithApplyPatch(currentToolNames));\n\t\treturn;\n\t}\n\tif (state.removedEditToolNames.length === 0) {\n\t\tif (currentToolNames.includes(APPLY_PATCH_NAME)) pi.setActiveTools(withoutApplyPatch(currentToolNames));\n\t\treturn;\n\t}\n\tconst registeredNames = new Set(pi.getAllTools().map((tool) => tool.name));\n\tconst restorable = state.removedEditToolNames.filter((toolName) => registeredNames.has(toolName));\n\tconst restored = [...withoutApplyPatch(currentToolNames), ...restorable];\n\tstate.removedEditToolNames = [];\n\tpi.setActiveTools([...new Set(restored)]);\n}\n\nexport function registerApplyPatchExtension(pi: ApplyPatchExtensionAPI): void {\n\tconst state: ApplyPatchToolsetState & { activeVariant?: ApplyPatchToolVariant } = { removedEditToolNames: [] };\n\tconst variants = {\n\t\tfreeform: createApplyPatchTool(\"freeform\"),\n\t\tjson: createApplyPatchTool(\"json\"),\n\t} as const;\n\tstate.activeVariant = \"freeform\";\n\tpi.registerTool(variants.freeform);\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\tsyncToolset(pi, ctx.model, state, variants);\n\t});\n\tpi.on(\"model_select\", async (event) => {\n\t\tsyncToolset(pi, event.model, state, variants);\n\t});\n}\n\nexport default registerApplyPatchExtension;\n"]}
1
+ {"version":3,"file":"extension.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/gpt-apply-patch/extension.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAQjD,MAAM,yBAAyB,GAAG,IAAI,GAAG,CAAM;IAC9C,kBAAkB;IAClB,wBAAwB;IACxB,wBAAwB;CACxB,CAAC,CAAC;AACH,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAM,CAAC,oBAAoB,CAAC,CAAC,CAAC;AACnE,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;AACnD,MAAM,gBAAgB,GAAG,aAAa,CAAC;AAEvC,SAAS,OAAO,CAAC,KAAoD;IACpE,OAAO,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC;AAC9C,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAAoD;IACzF,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,MAAM,CAAC;IACnC,IAAI,yBAAyB,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC;QAAE,OAAO,UAAU,CAAC;IAChE,IAAI,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC;QAAE,OAAO,MAAM,CAAC;IACxD,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,KAAoD;IACpF,OAAO,qBAAqB,CAAC,KAAK,CAAC,KAAK,UAAU,CAAC;AACpD,CAAC;AAED,SAAS,YAAY,CAAC,SAAmB;IACxC,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;AACpE,CAAC;AAED,SAAS,iBAAiB,CAAC,SAAmB;IAC7C,OAA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,CAAC,CAAC;IAC7C,CAAC,CAAC,CAAC;IACH,EAAE,CAAC,EAAE,CAAC,cAAc,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;QACrC,WAAW,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC/C,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,eAAe,2BAA2B,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { createApplyPatchTool } from \"./tool.ts\";\nimport type {\n\tApplyPatchExtensionAPI,\n\tApplyPatchToolsetState,\n\tApplyPatchToolVariant,\n\tApplyPatchWireMode,\n} from \"./types.ts\";\n\nconst APPLY_PATCH_FREEFORM_APIS = new Set<Api>([\n\t\"openai-responses\",\n\t\"azure-openai-responses\",\n\t\"openai-codex-responses\",\n]);\nconst APPLY_PATCH_JSON_APIS = new Set<Api>([\"openai-completions\"]);\nconst EDIT_TOOL_NAMES = new Set([\"write\", \"edit\"]);\nconst APPLY_PATCH_NAME = \"apply_patch\";\n\nfunction isGptId(model: Pick<Model<string>, \"api\" | \"id\"> | undefined): model is Pick<Model<string>, \"api\" | \"id\"> {\n\treturn model?.id.startsWith(\"gpt-\") ?? false;\n}\n\nexport function getApplyPatchWireMode(model: Pick<Model<string>, \"api\" | \"id\"> | undefined): ApplyPatchWireMode {\n\tif (!isGptId(model)) return \"none\";\n\tif (APPLY_PATCH_FREEFORM_APIS.has(model.api)) return \"freeform\";\n\tif (APPLY_PATCH_JSON_APIS.has(model.api)) return \"json\";\n\treturn \"none\";\n}\n\nexport function isOpenAIGptModel(model: Pick<Model<string>, \"api\" | \"id\"> | undefined): boolean {\n\treturn getApplyPatchWireMode(model) === \"freeform\";\n}\n\nfunction hasEditTools(toolNames: string[]): boolean {\n\treturn toolNames.some((toolName) => EDIT_TOOL_NAMES.has(toolName));\n}\n\nfunction withoutApplyPatch(toolNames: string[]): string[] {\n\treturn toolNames.filter((toolName) => toolName !== APPLY_PATCH_NAME);\n}\n\nfunction replaceEditToolsWithApplyPatch(toolNames: string[]): string[] {\n\tconst hadApplyPatch = toolNames.includes(APPLY_PATCH_NAME);\n\tconst insertIndex = toolNames.findIndex(\n\t\t(toolName) => EDIT_TOOL_NAMES.has(toolName) || toolName === APPLY_PATCH_NAME,\n\t);\n\tconst filteredToolNames = withoutApplyPatch(toolNames).filter((toolName) => !EDIT_TOOL_NAMES.has(toolName));\n\tif (!hasEditTools(toolNames) && !hadApplyPatch) return filteredToolNames;\n\tconst at = insertIndex === -1 ? filteredToolNames.length : Math.min(insertIndex, filteredToolNames.length);\n\treturn [...filteredToolNames.slice(0, at), APPLY_PATCH_NAME, ...filteredToolNames.slice(at)];\n}\n\nfunction hasApplyPatchFailures(details: unknown): boolean {\n\tif (typeof details !== \"object\" || details === null) return false;\n\tconst result = Reflect.get(details, \"result\");\n\tif (typeof result !== \"object\" || result === null) return false;\n\tconst failures = Reflect.get(result, \"failures\");\n\treturn Array.isArray(failures) && failures.length > 0;\n}\n\nfunction syncToolset(\n\tpi: ApplyPatchExtensionAPI,\n\tmodel: Model<string> | undefined,\n\tstate: ApplyPatchToolsetState & { activeVariant?: ApplyPatchToolVariant },\n\tvariants: Readonly<Record<ApplyPatchToolVariant, ReturnType<typeof createApplyPatchTool>>>,\n): void {\n\tconst mode = getApplyPatchWireMode(model);\n\tconst currentToolNames = pi.getActiveTools();\n\tif (mode !== \"none\") {\n\t\tif (state.activeVariant !== mode) {\n\t\t\tpi.registerTool(variants[mode]);\n\t\t\tstate.activeVariant = mode;\n\t\t}\n\t\tconst activeEdit = currentToolNames.filter((toolName) => EDIT_TOOL_NAMES.has(toolName));\n\t\tif (activeEdit.length > 0) state.removedEditToolNames = activeEdit;\n\t\tpi.setActiveTools(replaceEditToolsWithApplyPatch(currentToolNames));\n\t\treturn;\n\t}\n\tif (state.removedEditToolNames.length === 0) {\n\t\tif (currentToolNames.includes(APPLY_PATCH_NAME)) pi.setActiveTools(withoutApplyPatch(currentToolNames));\n\t\treturn;\n\t}\n\tconst registeredNames = new Set(pi.getAllTools().map((tool) => tool.name));\n\tconst restorable = state.removedEditToolNames.filter((toolName) => registeredNames.has(toolName));\n\tconst restored = [...withoutApplyPatch(currentToolNames), ...restorable];\n\tstate.removedEditToolNames = [];\n\tpi.setActiveTools([...new Set(restored)]);\n}\n\nexport function registerApplyPatchExtension(pi: ApplyPatchExtensionAPI): void {\n\tconst state: ApplyPatchToolsetState & { activeVariant?: ApplyPatchToolVariant } = { removedEditToolNames: [] };\n\tconst variants = {\n\t\tfreeform: createApplyPatchTool(\"freeform\"),\n\t\tjson: createApplyPatchTool(\"json\"),\n\t} as const;\n\tstate.activeVariant = \"freeform\";\n\tpi.registerTool(variants.freeform);\n\tpi.on(\"tool_result\", async (event) => {\n\t\tif (event.toolName !== APPLY_PATCH_NAME || event.isError || !hasApplyPatchFailures(event.details)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn { isError: true };\n\t});\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\tsyncToolset(pi, ctx.model, state, variants);\n\t});\n\tpi.on(\"model_select\", async (event) => {\n\t\tsyncToolset(pi, event.model, state, variants);\n\t});\n}\n\nexport default registerApplyPatchExtension;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/gpt-apply-patch/tool.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAKX,wBAAwB,EAGxB,MAAM,YAAY,CAAC;AAiDpB,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,UAAU,GAAG,MAAmB,GAAG,wBAAwB,CA4FxG"}
1
+ {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/gpt-apply-patch/tool.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAKX,wBAAwB,EAGxB,MAAM,YAAY,CAAC;AA+EpB,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,UAAU,GAAG,MAAmB,GAAG,wBAAwB,CA+FxG"}
@@ -35,13 +35,37 @@ function renderPreviewBox(title, details, isPartial, cwd, expanded, theme) {
35
35
  }
36
36
  function renderTextResult(result, theme) {
37
37
  const component = new Container();
38
- const text = result.content
38
+ const text = resultText(result);
39
+ if (text)
40
+ component.addChild(new Text(theme.fg("toolOutput", text), 0, 0));
41
+ return component;
42
+ }
43
+ function resultText(result) {
44
+ return result.content
39
45
  .filter((block) => block.type === "text")
40
46
  .map((block) => block.text)
41
47
  .filter((value) => typeof value === "string" && value.length > 0)
42
48
  .join("\n");
43
- if (text)
44
- component.addChild(new Text(theme.fg("toolOutput", text), 0, 0));
49
+ }
50
+ function renderFailureBox(result, cwd, expanded, theme) {
51
+ const patchResult = result.details?.result;
52
+ if (!patchResult)
53
+ return renderTextResult(result, theme);
54
+ const component = new Container();
55
+ const appliedCount = patchResult.appliedFiles.length;
56
+ const title = appliedCount > 0 ? "Patch partially failed" : "Patch failed";
57
+ const box = new Box(1, 1, (text) => theme.bg("toolErrorBg", text));
58
+ box.addChild(new Text(theme.fg("toolTitle", theme.bold(title)), 0, 0));
59
+ if (result.details.preview) {
60
+ box.addChild(new Spacer(1));
61
+ box.addChild(new Text(renderPatchPreview(result.details.preview, cwd, theme, expanded), 0, 0));
62
+ }
63
+ const text = resultText(result);
64
+ if (text) {
65
+ box.addChild(new Spacer(1));
66
+ box.addChild(new Text(theme.fg("toolOutput", text), 0, 0));
67
+ }
68
+ component.addChild(box);
45
69
  return component;
46
70
  }
47
71
  export function createApplyPatchTool(variant = "freeform") {
@@ -101,6 +125,9 @@ export function createApplyPatchTool(variant = "freeform") {
101
125
  return new Text(theme.fg("toolTitle", theme.bold(text)), 0, 0);
102
126
  },
103
127
  renderResult(result, options, theme, context) {
128
+ if (context.isError && result.details?.result?.failures.length) {
129
+ return renderFailureBox(result, context.cwd, true, theme);
130
+ }
104
131
  if (result.details?.preview) {
105
132
  const expanded = true;
106
133
  return renderPreviewBox(options.isPartial ? "Applying patch" : "Applied patch", result.details, options.isPartial, context.cwd, expanded, theme);
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/gpt-apply-patch/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAEtE,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACzE,OAAO,EACN,gCAAgC,EAChC,4BAA4B,EAC5B,wBAAwB,EACxB,kBAAkB,GAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACnF,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAWjE,SAAS,cAAc,CAAC,MAAwB;IAC/C,MAAM,KAAK,GAAG,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC;SACjD,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;SACjE,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACxC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACzC,OAAO;QACN,KAAK;QACL,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC,CAA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,CAAC,CAAC;gBAClF,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC5B,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;oBAC5B,MAAM,QAAQ,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC,CAAC;oBACvE,GAAG,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;gBACxG,CAAC;gBACD,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACxB,OAAO,SAAS,CAAC;YAClB,CAAC;YACD,OAAO,gBAAgB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QACxC,CAAC;KACD,CAAC,CAAC;IAEH,IAAI,OAAO,KAAK,MAAM;QAAE,OAAO,IAAI,CAAC;IACpC,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QAC1B,QAAQ,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,wBAAwB,EAA+B;KAChH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { Box, Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { AgentToolResult, ToolRenderContext } from \"../../types.ts\";\nimport { defineTool } from \"../../types.ts\";\nimport { applyPatchDetailed, buildPartialFailureText } from \"./apply.ts\";\nimport {\n\tAPPLY_PATCH_FREEFORM_DESCRIPTION,\n\tAPPLY_PATCH_JSON_DESCRIPTION,\n\tAPPLY_PATCH_LARK_GRAMMAR,\n\tAPPLY_PATCH_PARAMS,\n} from \"./constants.ts\";\nimport { normalizeApplyPatchArguments } from \"./params.ts\";\nimport { parsePatch } from \"./parser.ts\";\nimport { createPendingPatchUpdate } from \"./preview.ts\";\nimport { getApplyPatchRenderState, renderPatchPreview } from \"./preview-format.ts\";\nimport { renderStreamingPatchCall } from \"./streaming-render.ts\";\nimport type {\n\tApplyPatchPreview,\n\tApplyPatchRenderState,\n\tApplyPatchResult,\n\tApplyPatchTheme,\n\tApplyPatchToolDefinition,\n\tApplyPatchToolDetails,\n\tFreeformToolFormat,\n} from \"./types.ts\";\n\nfunction appliedPreview(result: ApplyPatchResult): ApplyPatchPreview | undefined {\n\tconst files = [...result.details.appliedOperations]\n\t\t.sort((left, right) => left.operationIndex - right.operationIndex)\n\t\t.map((operation) => operation.preview);\n\tif (files.length === 0) return undefined;\n\treturn {\n\t\tfiles,\n\t\tadded: files.reduce((total, file) => total + file.added, 0),\n\t\tremoved: files.reduce((total, file) => total + file.removed, 0),\n\t};\n}\n\nfunction renderPreviewBox(\n\ttitle: string,\n\tdetails: ApplyPatchToolDetails,\n\tisPartial: boolean,\n\tcwd: string,\n\texpanded: boolean,\n\ttheme: ApplyPatchTheme,\n): Container {\n\tconst component = new Container();\n\tif (!details.preview) return component;\n\tconst bgName = isPartial ? \"toolPendingBg\" : \"toolSuccessBg\";\n\tconst progress = details.progress;\n\tconst renderedTitle = progress ? `Applying patch (${progress.applied + progress.failed}/${progress.total})` : title;\n\tconst box = new Box(1, 1, (text: string) => theme.bg(bgName, text));\n\tbox.addChild(new Text(theme.fg(\"toolTitle\", theme.bold(renderedTitle)), 0, 0));\n\tbox.addChild(new Spacer(1));\n\tbox.addChild(new Text(renderPatchPreview(details.preview, cwd, theme, expanded), 0, 0));\n\tcomponent.addChild(box);\n\treturn component;\n}\n\nfunction renderTextResult(\n\tresult: AgentToolResult<ApplyPatchToolDetails | undefined>,\n\ttheme: ApplyPatchTheme,\n): Container {\n\tconst component = new Container();\n\tconst text = result.content\n\t\t.filter((block) => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.filter((value) => typeof value === \"string\" && value.length > 0)\n\t\t.join(\"\\n\");\n\tif (text) component.addChild(new Text(theme.fg(\"toolOutput\", text), 0, 0));\n\treturn component;\n}\n\nexport function createApplyPatchTool(variant: \"freeform\" | \"json\" = \"freeform\"): ApplyPatchToolDefinition {\n\tconst tool = defineTool<typeof APPLY_PATCH_PARAMS, ApplyPatchToolDetails | undefined, ApplyPatchRenderState>({\n\t\tname: \"apply_patch\",\n\t\tlabel: \"ApplyPatch\",\n\t\tdescription: variant === \"json\" ? APPLY_PATCH_JSON_DESCRIPTION : APPLY_PATCH_FREEFORM_DESCRIPTION,\n\t\tparameters: APPLY_PATCH_PARAMS,\n\t\tprepareArguments: normalizeApplyPatchArguments,\n\t\tpromptSnippet: \"Apply Codex-format file patches with apply_patch\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use apply_patch for file edits instead of mutating files through bash, Python scripts, heredocs, or shell redirection.\",\n\t\t\t\"After apply_patch succeeds, do not re-read the edited files just to confirm the patch applied.\",\n\t\t],\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\tparams,\n\t\t\t_signal,\n\t\t\tonUpdate,\n\t\t\tctx,\n\t\t): Promise<AgentToolResult<ApplyPatchToolDetails | undefined>> {\n\t\t\tconst normalizedParams = normalizeApplyPatchArguments(params);\n\t\t\tif (!normalizedParams.input) throw new Error(\"input is required\");\n\t\t\tlet totalOperations = 0;\n\t\t\ttry {\n\t\t\t\ttotalOperations = parsePatch(normalizedParams.input).length;\n\t\t\t} catch {\n\t\t\t\t// createPendingPatchUpdate keeps incomplete or invalid patch text renderable.\n\t\t\t}\n\t\t\tconst initialProgress = totalOperations > 0 ? { applied: 0, failed: 0, total: totalOperations } : undefined;\n\t\t\tconst pendingUpdate = await createPendingPatchUpdate(ctx.cwd, normalizedParams.input, initialProgress);\n\t\t\tonUpdate?.({ content: [{ type: \"text\", text: pendingUpdate.text }], details: pendingUpdate.details });\n\t\t\tconst preview = pendingUpdate.details?.preview;\n\t\t\tconst result = await applyPatchDetailed(ctx.cwd, normalizedParams.input, async (progress) => {\n\t\t\t\tconst progressUpdate = await createPendingPatchUpdate(ctx.cwd, normalizedParams.input, progress, preview);\n\t\t\t\tonUpdate?.({ content: [{ type: \"text\", text: progressUpdate.text }], details: progressUpdate.details });\n\t\t\t});\n\t\t\tconst resultPreview = appliedPreview(result);\n\t\t\tif (result.failures.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: buildPartialFailureText(result) }],\n\t\t\t\t\tdetails: resultPreview ? { preview: resultPreview, result } : { result },\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: result.summaries.join(\"\\n\") }],\n\t\t\t\tdetails: resultPreview ? { preview: resultPreview, result } : { result },\n\t\t\t};\n\t\t},\n\t\trenderCall(args, theme, context: ToolRenderContext<ApplyPatchRenderState, { input: string }>) {\n\t\t\tif (!context.executionStarted) {\n\t\t\t\tconst streaming = renderStreamingPatchCall(normalizeApplyPatchArguments(args), theme, context.state);\n\t\t\t\tif (streaming) return streaming;\n\t\t\t}\n\t\t\tif (!context.argsComplete) return new Text(theme.fg(\"toolTitle\", theme.bold(\"apply_patch: Patching\")), 0, 0);\n\t\t\tconst normalizedArgs = normalizeApplyPatchArguments(args);\n\t\t\tconst renderState = getApplyPatchRenderState(context.toolCallId, context.cwd, normalizedArgs.input);\n\t\t\tconst text = renderState.callText?.length ? `apply_patch: ${renderState.callText}` : \"apply_patch\";\n\t\t\treturn new Text(theme.fg(\"toolTitle\", theme.bold(text)), 0, 0);\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tif (result.details?.preview) {\n\t\t\t\tconst expanded = true;\n\t\t\t\treturn renderPreviewBox(\n\t\t\t\t\toptions.isPartial ? \"Applying patch\" : \"Applied patch\",\n\t\t\t\t\tresult.details,\n\t\t\t\t\toptions.isPartial,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t\texpanded,\n\t\t\t\t\ttheme,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (result.details?.result) {\n\t\t\t\tconst component = new Container();\n\t\t\t\tconst box = new Box(1, 1, (text: string) =>\n\t\t\t\t\ttheme.bg(options.isPartial ? \"toolPendingBg\" : \"toolSuccessBg\", text),\n\t\t\t\t);\n\t\t\t\tbox.addChild(new Text(theme.fg(\"toolTitle\", theme.bold(\"Applying patch\")), 0, 0));\n\t\t\t\tbox.addChild(new Spacer(1));\n\t\t\t\tif (result.details.preview) {\n\t\t\t\t\tconst expanded = options.isPartial ? true : (options.expanded ?? true);\n\t\t\t\t\tbox.addChild(new Text(renderPatchPreview(result.details.preview, context.cwd, theme, expanded), 0, 0));\n\t\t\t\t}\n\t\t\t\tcomponent.addChild(box);\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\treturn renderTextResult(result, theme);\n\t\t},\n\t});\n\n\tif (variant === \"json\") return tool;\n\treturn Object.assign(tool, {\n\t\tfreeform: { type: \"grammar\", syntax: \"lark\", definition: APPLY_PATCH_LARK_GRAMMAR } satisfies FreeformToolFormat,\n\t});\n}\n"]}
1
+ {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/gpt-apply-patch/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAEtE,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACzE,OAAO,EACN,gCAAgC,EAChC,4BAA4B,EAC5B,wBAAwB,EACxB,kBAAkB,GAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,wBA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B,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;oBAC5B,MAAM,QAAQ,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC,CAAC;oBACvE,GAAG,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;gBACxG,CAAC;gBACD,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACxB,OAAO,SAAS,CAAC;YAClB,CAAC;YACD,OAAO,gBAAgB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QACxC,CAAC;KACD,CAAC,CAAC;IAEH,IAAI,OAAO,KAAK,MAAM;QAAE,OAAO,IAAI,CAAC;IACpC,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QAC1B,QAAQ,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,wBAAwB,EAA+B;KAChH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { Box, Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { AgentToolResult, ToolRenderContext } from \"../../types.ts\";\nimport { defineTool } from \"../../types.ts\";\nimport { applyPatchDetailed, buildPartialFailureText } from \"./apply.ts\";\nimport {\n\tAPPLY_PATCH_FREEFORM_DESCRIPTION,\n\tAPPLY_PATCH_JSON_DESCRIPTION,\n\tAPPLY_PATCH_LARK_GRAMMAR,\n\tAPPLY_PATCH_PARAMS,\n} from \"./constants.ts\";\nimport { normalizeApplyPatchArguments } from \"./params.ts\";\nimport { parsePatch } from \"./parser.ts\";\nimport { createPendingPatchUpdate } from \"./preview.ts\";\nimport { getApplyPatchRenderState, renderPatchPreview } from \"./preview-format.ts\";\nimport { renderStreamingPatchCall } from \"./streaming-render.ts\";\nimport type {\n\tApplyPatchPreview,\n\tApplyPatchRenderState,\n\tApplyPatchResult,\n\tApplyPatchTheme,\n\tApplyPatchToolDefinition,\n\tApplyPatchToolDetails,\n\tFreeformToolFormat,\n} from \"./types.ts\";\n\nfunction appliedPreview(result: ApplyPatchResult): ApplyPatchPreview | undefined {\n\tconst files = [...result.details.appliedOperations]\n\t\t.sort((left, right) => left.operationIndex - right.operationIndex)\n\t\t.map((operation) => operation.preview);\n\tif (files.length === 0) return undefined;\n\treturn {\n\t\tfiles,\n\t\tadded: files.reduce((total, file) => total + file.added, 0),\n\t\tremoved: files.reduce((total, file) => total + file.removed, 0),\n\t};\n}\n\nfunction renderPreviewBox(\n\ttitle: string,\n\tdetails: ApplyPatchToolDetails,\n\tisPartial: boolean,\n\tcwd: string,\n\texpanded: boolean,\n\ttheme: ApplyPatchTheme,\n): Container {\n\tconst component = new Container();\n\tif (!details.preview) return component;\n\tconst bgName = isPartial ? \"toolPendingBg\" : \"toolSuccessBg\";\n\tconst progress = details.progress;\n\tconst renderedTitle = progress ? `Applying patch (${progress.applied + progress.failed}/${progress.total})` : title;\n\tconst box = new Box(1, 1, (text: string) => theme.bg(bgName, text));\n\tbox.addChild(new Text(theme.fg(\"toolTitle\", theme.bold(renderedTitle)), 0, 0));\n\tbox.addChild(new Spacer(1));\n\tbox.addChild(new Text(renderPatchPreview(details.preview, cwd, theme, expanded), 0, 0));\n\tcomponent.addChild(box);\n\treturn component;\n}\n\nfunction renderTextResult(\n\tresult: AgentToolResult<ApplyPatchToolDetails | undefined>,\n\ttheme: ApplyPatchTheme,\n): Container {\n\tconst component = new Container();\n\tconst text = resultText(result);\n\tif (text) component.addChild(new Text(theme.fg(\"toolOutput\", text), 0, 0));\n\treturn component;\n}\n\nfunction resultText(result: AgentToolResult<ApplyPatchToolDetails | undefined>): string {\n\treturn result.content\n\t\t.filter((block) => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.filter((value) => typeof value === \"string\" && value.length > 0)\n\t\t.join(\"\\n\");\n}\n\nfunction renderFailureBox(\n\tresult: AgentToolResult<ApplyPatchToolDetails>,\n\tcwd: string,\n\texpanded: boolean,\n\ttheme: ApplyPatchTheme,\n): Container {\n\tconst patchResult = result.details?.result;\n\tif (!patchResult) return renderTextResult(result, theme);\n\tconst component = new Container();\n\tconst appliedCount = patchResult.appliedFiles.length;\n\tconst title = appliedCount > 0 ? \"Patch partially failed\" : \"Patch failed\";\n\tconst box = new Box(1, 1, (text: string) => theme.bg(\"toolErrorBg\", text));\n\tbox.addChild(new Text(theme.fg(\"toolTitle\", theme.bold(title)), 0, 0));\n\tif (result.details.preview) {\n\t\tbox.addChild(new Spacer(1));\n\t\tbox.addChild(new Text(renderPatchPreview(result.details.preview, cwd, theme, expanded), 0, 0));\n\t}\n\tconst text = resultText(result);\n\tif (text) {\n\t\tbox.addChild(new Spacer(1));\n\t\tbox.addChild(new Text(theme.fg(\"toolOutput\", text), 0, 0));\n\t}\n\tcomponent.addChild(box);\n\treturn component;\n}\n\nexport function createApplyPatchTool(variant: \"freeform\" | \"json\" = \"freeform\"): ApplyPatchToolDefinition {\n\tconst tool = defineTool<typeof APPLY_PATCH_PARAMS, ApplyPatchToolDetails | undefined, ApplyPatchRenderState>({\n\t\tname: \"apply_patch\",\n\t\tlabel: \"ApplyPatch\",\n\t\tdescription: variant === \"json\" ? APPLY_PATCH_JSON_DESCRIPTION : APPLY_PATCH_FREEFORM_DESCRIPTION,\n\t\tparameters: APPLY_PATCH_PARAMS,\n\t\tprepareArguments: normalizeApplyPatchArguments,\n\t\tpromptSnippet: \"Apply Codex-format file patches with apply_patch\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use apply_patch for file edits instead of mutating files through bash, Python scripts, heredocs, or shell redirection.\",\n\t\t\t\"After apply_patch succeeds, do not re-read the edited files just to confirm the patch applied.\",\n\t\t],\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\tparams,\n\t\t\t_signal,\n\t\t\tonUpdate,\n\t\t\tctx,\n\t\t): Promise<AgentToolResult<ApplyPatchToolDetails | undefined>> {\n\t\t\tconst normalizedParams = normalizeApplyPatchArguments(params);\n\t\t\tif (!normalizedParams.input) throw new Error(\"input is required\");\n\t\t\tlet totalOperations = 0;\n\t\t\ttry {\n\t\t\t\ttotalOperations = parsePatch(normalizedParams.input).length;\n\t\t\t} catch {\n\t\t\t\t// createPendingPatchUpdate keeps incomplete or invalid patch text renderable.\n\t\t\t}\n\t\t\tconst initialProgress = totalOperations > 0 ? { applied: 0, failed: 0, total: totalOperations } : undefined;\n\t\t\tconst pendingUpdate = await createPendingPatchUpdate(ctx.cwd, normalizedParams.input, initialProgress);\n\t\t\tonUpdate?.({ content: [{ type: \"text\", text: pendingUpdate.text }], details: pendingUpdate.details });\n\t\t\tconst preview = pendingUpdate.details?.preview;\n\t\t\tconst result = await applyPatchDetailed(ctx.cwd, normalizedParams.input, async (progress) => {\n\t\t\t\tconst progressUpdate = await createPendingPatchUpdate(ctx.cwd, normalizedParams.input, progress, preview);\n\t\t\t\tonUpdate?.({ content: [{ type: \"text\", text: progressUpdate.text }], details: progressUpdate.details });\n\t\t\t});\n\t\t\tconst resultPreview = appliedPreview(result);\n\t\t\tif (result.failures.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: buildPartialFailureText(result) }],\n\t\t\t\t\tdetails: resultPreview ? { preview: resultPreview, result } : { result },\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: result.summaries.join(\"\\n\") }],\n\t\t\t\tdetails: resultPreview ? { preview: resultPreview, result } : { result },\n\t\t\t};\n\t\t},\n\t\trenderCall(args, theme, context: ToolRenderContext<ApplyPatchRenderState, { input: string }>) {\n\t\t\tif (!context.executionStarted) {\n\t\t\t\tconst streaming = renderStreamingPatchCall(normalizeApplyPatchArguments(args), theme, context.state);\n\t\t\t\tif (streaming) return streaming;\n\t\t\t}\n\t\t\tif (!context.argsComplete) return new Text(theme.fg(\"toolTitle\", theme.bold(\"apply_patch: Patching\")), 0, 0);\n\t\t\tconst normalizedArgs = normalizeApplyPatchArguments(args);\n\t\t\tconst renderState = getApplyPatchRenderState(context.toolCallId, context.cwd, normalizedArgs.input);\n\t\t\tconst text = renderState.callText?.length ? `apply_patch: ${renderState.callText}` : \"apply_patch\";\n\t\t\treturn new Text(theme.fg(\"toolTitle\", theme.bold(text)), 0, 0);\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tif (context.isError && result.details?.result?.failures.length) {\n\t\t\t\treturn renderFailureBox(result as AgentToolResult<ApplyPatchToolDetails>, context.cwd, true, theme);\n\t\t\t}\n\t\t\tif (result.details?.preview) {\n\t\t\t\tconst expanded = true;\n\t\t\t\treturn renderPreviewBox(\n\t\t\t\t\toptions.isPartial ? \"Applying patch\" : \"Applied patch\",\n\t\t\t\t\tresult.details,\n\t\t\t\t\toptions.isPartial,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t\texpanded,\n\t\t\t\t\ttheme,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (result.details?.result) {\n\t\t\t\tconst component = new Container();\n\t\t\t\tconst box = new Box(1, 1, (text: string) =>\n\t\t\t\t\ttheme.bg(options.isPartial ? \"toolPendingBg\" : \"toolSuccessBg\", text),\n\t\t\t\t);\n\t\t\t\tbox.addChild(new Text(theme.fg(\"toolTitle\", theme.bold(\"Applying patch\")), 0, 0));\n\t\t\t\tbox.addChild(new Spacer(1));\n\t\t\t\tif (result.details.preview) {\n\t\t\t\t\tconst expanded = options.isPartial ? true : (options.expanded ?? true);\n\t\t\t\t\tbox.addChild(new Text(renderPatchPreview(result.details.preview, context.cwd, theme, expanded), 0, 0));\n\t\t\t\t}\n\t\t\t\tcomponent.addChild(box);\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\treturn renderTextResult(result, theme);\n\t\t},\n\t});\n\n\tif (variant === \"json\") return tool;\n\treturn Object.assign(tool, {\n\t\tfreeform: { type: \"grammar\", syntax: \"lark\", definition: APPLY_PATCH_LARK_GRAMMAR } satisfies FreeformToolFormat,\n\t});\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import { type BuildDynamicSystemPromptOptions } from "../../../dynamic-prompt/build.ts";
2
+ export declare function buildDeepseekV4Flash0731Prompt(options: BuildDynamicSystemPromptOptions): string;
3
+ //# sourceMappingURL=deepseek-v4-flash-0731.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deepseek-v4-flash-0731.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/prompt-preset/deepseek-v4-flash-0731.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,+BAA+B,EAA4B,MAAM,kCAAkC,CAAC;AAGlH,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,+BAA+B,GAAG,MAAM,CAS/F"}
@@ -0,0 +1,10 @@
1
+ import { buildDynamicSystemPrompt } from "../../../dynamic-prompt/build.js";
2
+ import { buildDeepseekV4FlashIntro, buildDeepseekV4Tuning } from "./deepseek-v4.js";
3
+ export function buildDeepseekV4Flash0731Prompt(options) {
4
+ return buildDynamicSystemPrompt({
5
+ ...options,
6
+ tuningSection: buildDeepseekV4Tuning("deepseek-v4-flash-0731", buildDeepseekV4FlashIntro("DeepSeek V4 Flash (0731 snapshot)")),
7
+ workstationDialect: "claude",
8
+ });
9
+ }
10
+ //# sourceMappingURL=deepseek-v4-flash-0731.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deepseek-v4-flash-0731.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/prompt-preset/deepseek-v4-flash-0731.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwC,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAClH,OAAO,EAAE,yBAAyB,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEpF,MAAM,UAAU,8BAA8B,CAAC,OAAwC;IACtF,OAAO,wBAAwB,CAAC;QAC/B,GAAG,OAAO;QACV,aAAa,EAAE,qBAAqB,CACnC,wBAAwB,EACxB,yBAAyB,CAAC,mCAAmC,CAAC,CAC9D;QACD,kBAAkB,EAAE,QAAQ;KAC5B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { type BuildDynamicSystemPromptOptions, buildDynamicSystemPrompt } from \"../../../dynamic-prompt/build.ts\";\nimport { buildDeepseekV4FlashIntro, buildDeepseekV4Tuning } from \"./deepseek-v4.ts\";\n\nexport function buildDeepseekV4Flash0731Prompt(options: BuildDynamicSystemPromptOptions): string {\n\treturn buildDynamicSystemPrompt({\n\t\t...options,\n\t\ttuningSection: buildDeepseekV4Tuning(\n\t\t\t\"deepseek-v4-flash-0731\",\n\t\t\tbuildDeepseekV4FlashIntro(\"DeepSeek V4 Flash (0731 snapshot)\"),\n\t\t),\n\t\tworkstationDialect: \"claude\",\n\t});\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import { type BuildDynamicSystemPromptOptions } from "../../../dynamic-prompt/build.ts";
2
+ export declare function buildDeepseekV4FlashPrompt(options: BuildDynamicSystemPromptOptions): string;
3
+ //# sourceMappingURL=deepseek-v4-flash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deepseek-v4-flash.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/prompt-preset/deepseek-v4-flash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,+BAA+B,EAA4B,MAAM,kCAAkC,CAAC;AAGlH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,+BAA+B,GAAG,MAAM,CAM3F"}
@@ -0,0 +1,10 @@
1
+ import { buildDynamicSystemPrompt } from "../../../dynamic-prompt/build.js";
2
+ import { buildDeepseekV4FlashIntro, buildDeepseekV4Tuning } from "./deepseek-v4.js";
3
+ export function buildDeepseekV4FlashPrompt(options) {
4
+ return buildDynamicSystemPrompt({
5
+ ...options,
6
+ tuningSection: buildDeepseekV4Tuning("deepseek-v4-flash", buildDeepseekV4FlashIntro("DeepSeek V4 Flash")),
7
+ workstationDialect: "claude",
8
+ });
9
+ }
10
+ //# sourceMappingURL=deepseek-v4-flash.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deepseek-v4-flash.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/prompt-preset/deepseek-v4-flash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwC,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAClH,OAAO,EAAE,yBAAyB,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEpF,MAAM,UAAU,0BAA0B,CAAC,OAAwC;IAClF,OAAO,wBAAwB,CAAC;QAC/B,GAAG,OAAO;QACV,aAAa,EAAE,qBAAqB,CAAC,mBAAmB,EAAE,yBAAyB,CAAC,mBAAmB,CAAC,CAAC;QACzG,kBAAkB,EAAE,QAAQ;KAC5B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { type BuildDynamicSystemPromptOptions, buildDynamicSystemPrompt } from \"../../../dynamic-prompt/build.ts\";\nimport { buildDeepseekV4FlashIntro, buildDeepseekV4Tuning } from \"./deepseek-v4.ts\";\n\nexport function buildDeepseekV4FlashPrompt(options: BuildDynamicSystemPromptOptions): string {\n\treturn buildDynamicSystemPrompt({\n\t\t...options,\n\t\ttuningSection: buildDeepseekV4Tuning(\"deepseek-v4-flash\", buildDeepseekV4FlashIntro(\"DeepSeek V4 Flash\")),\n\t\tworkstationDialect: \"claude\",\n\t});\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import { type BuildDynamicSystemPromptOptions } from "../../../dynamic-prompt/build.ts";
2
+ export declare function buildDeepseekV4ProPrompt(options: BuildDynamicSystemPromptOptions): string;
3
+ //# sourceMappingURL=deepseek-v4-pro.d.ts.map