@bastani/atomic 0.9.35-alpha.2 → 0.9.35-alpha.4

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 (229) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/builtin/intercom/package.json +2 -2
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +3 -3
  5. package/dist/builtin/web-access/package.json +2 -2
  6. package/dist/builtin/workflows/CHANGELOG.md +13 -0
  7. package/dist/builtin/workflows/builtin/{chunk-s7y3hw0n.js → chunk-3xffzzbg.js} +1 -1
  8. package/dist/builtin/workflows/builtin/{chunk-0d0pd4fz.js → chunk-7fvrnzhb.js} +1 -1
  9. package/dist/builtin/workflows/builtin/{chunk-119gt64q.js → chunk-8c3ae7tt.js} +8 -1
  10. package/dist/builtin/workflows/builtin/{chunk-y68758re.js → chunk-rhkg3d8e.js} +1 -1
  11. package/dist/builtin/workflows/builtin/goal.js +2 -2
  12. package/dist/builtin/workflows/builtin/index.js +3 -3
  13. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  14. package/dist/builtin/workflows/package.json +2 -2
  15. package/dist/builtin/workflows/src/extension/index.bundle.mjs +510 -35
  16. package/dist/builtin/workflows/src/index.js +87 -29
  17. package/dist/codemode-worker.js +222 -78
  18. package/dist/config.d.ts +1 -0
  19. package/dist/config.d.ts.map +1 -1
  20. package/dist/config.js +1 -0
  21. package/dist/config.js.map +1 -1
  22. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  23. package/dist/core/agent-session-accessors.js +7 -1
  24. package/dist/core/agent-session-accessors.js.map +1 -1
  25. package/dist/core/agent-session-custom-message-commit.js +15 -15
  26. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  27. package/dist/core/agent-session-events.d.ts.map +1 -1
  28. package/dist/core/agent-session-events.js +4 -0
  29. package/dist/core/agent-session-events.js.map +1 -1
  30. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  31. package/dist/core/agent-session-extension-bindings.js +61 -1
  32. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  33. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  34. package/dist/core/agent-session-message-queue.js +3 -1
  35. package/dist/core/agent-session-message-queue.js.map +1 -1
  36. package/dist/core/agent-session-methods.d.ts +5 -3
  37. package/dist/core/agent-session-methods.d.ts.map +1 -1
  38. package/dist/core/agent-session-methods.js.map +1 -1
  39. package/dist/core/agent-session-persistent-custom-messages.js +1 -1
  40. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  41. package/dist/core/agent-session-prompt.d.ts +3 -1
  42. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  43. package/dist/core/agent-session-prompt.js +79 -9
  44. package/dist/core/agent-session-prompt.js.map +1 -1
  45. package/dist/core/agent-session-summary.d.ts.map +1 -1
  46. package/dist/core/agent-session-summary.js +17 -2
  47. package/dist/core/agent-session-summary.js.map +1 -1
  48. package/dist/core/agent-session-tree.js +1 -1
  49. package/dist/core/agent-session-tree.js.map +1 -1
  50. package/dist/core/agent-session.d.ts +1 -0
  51. package/dist/core/agent-session.d.ts.map +1 -1
  52. package/dist/core/agent-session.js +1 -0
  53. package/dist/core/agent-session.js.map +1 -1
  54. package/dist/core/auth-storage-backends.d.ts +1 -0
  55. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  56. package/dist/core/auth-storage-backends.js +37 -23
  57. package/dist/core/auth-storage-backends.js.map +1 -1
  58. package/dist/core/compaction/session-summarization.d.ts +1 -0
  59. package/dist/core/compaction/session-summarization.d.ts.map +1 -1
  60. package/dist/core/compaction/session-summarization.js +7 -1
  61. package/dist/core/compaction/session-summarization.js.map +1 -1
  62. package/dist/core/extensions/agent-events.d.ts +15 -7
  63. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  64. package/dist/core/extensions/agent-events.js.map +1 -1
  65. package/dist/core/extensions/context-types.d.ts +6 -0
  66. package/dist/core/extensions/context-types.d.ts.map +1 -1
  67. package/dist/core/extensions/context-types.js.map +1 -1
  68. package/dist/core/extensions/index.d.ts +1 -1
  69. package/dist/core/extensions/index.d.ts.map +1 -1
  70. package/dist/core/extensions/index.js.map +1 -1
  71. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  72. package/dist/core/extensions/loader-virtual-modules.js +2 -0
  73. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  74. package/dist/core/extensions/runner-context.d.ts +4 -0
  75. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  76. package/dist/core/extensions/runner-context.js +8 -0
  77. package/dist/core/extensions/runner-context.js.map +1 -1
  78. package/dist/core/extensions/runner-events.d.ts +1 -1
  79. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  80. package/dist/core/extensions/runner-events.js +4 -3
  81. package/dist/core/extensions/runner-events.js.map +1 -1
  82. package/dist/core/extensions/runner.d.ts +3 -1
  83. package/dist/core/extensions/runner.d.ts.map +1 -1
  84. package/dist/core/extensions/runner.js +8 -2
  85. package/dist/core/extensions/runner.js.map +1 -1
  86. package/dist/core/extensions/runtime-types.d.ts +4 -0
  87. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  88. package/dist/core/extensions/runtime-types.js.map +1 -1
  89. package/dist/core/extensions/workflow-run-control.d.ts +12 -2
  90. package/dist/core/extensions/workflow-run-control.d.ts.map +1 -1
  91. package/dist/core/extensions/workflow-run-control.js.map +1 -1
  92. package/dist/core/model-runtime.d.ts.map +1 -1
  93. package/dist/core/model-runtime.js +11 -6
  94. package/dist/core/model-runtime.js.map +1 -1
  95. package/dist/core/package-manager-resource-patterns.d.ts.map +1 -1
  96. package/dist/core/package-manager-resource-patterns.js +4 -2
  97. package/dist/core/package-manager-resource-patterns.js.map +1 -1
  98. package/dist/core/remote-catalog-provider.d.ts +12 -1
  99. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  100. package/dist/core/remote-catalog-provider.js +85 -24
  101. package/dist/core/remote-catalog-provider.js.map +1 -1
  102. package/dist/core/session-manager-archive.d.ts +2 -0
  103. package/dist/core/session-manager-archive.d.ts.map +1 -1
  104. package/dist/core/session-manager-archive.js +41 -19
  105. package/dist/core/session-manager-archive.js.map +1 -1
  106. package/dist/core/session-manager-core.d.ts +1 -0
  107. package/dist/core/session-manager-core.d.ts.map +1 -1
  108. package/dist/core/session-manager-core.js +8 -4
  109. package/dist/core/session-manager-core.js.map +1 -1
  110. package/dist/core/session-manager-list.d.ts.map +1 -1
  111. package/dist/core/session-manager-list.js +4 -10
  112. package/dist/core/session-manager-list.js.map +1 -1
  113. package/dist/core/session-manager-types.d.ts +2 -1
  114. package/dist/core/session-manager-types.d.ts.map +1 -1
  115. package/dist/core/session-manager-types.js.map +1 -1
  116. package/dist/core/session-manager.d.ts +1 -1
  117. package/dist/core/session-manager.d.ts.map +1 -1
  118. package/dist/core/session-manager.js.map +1 -1
  119. package/dist/core/tools/bash.d.ts +2 -6
  120. package/dist/core/tools/bash.d.ts.map +1 -1
  121. package/dist/core/tools/bash.js +9 -39
  122. package/dist/core/tools/bash.js.map +1 -1
  123. package/dist/core/tools/powershell.d.ts +2 -10
  124. package/dist/core/tools/powershell.d.ts.map +1 -1
  125. package/dist/core/tools/render-utils.d.ts +15 -0
  126. package/dist/core/tools/render-utils.d.ts.map +1 -1
  127. package/dist/core/tools/render-utils.js +46 -0
  128. package/dist/core/tools/render-utils.js.map +1 -1
  129. package/dist/core/workflow-summary-lifecycle.d.ts +4 -0
  130. package/dist/core/workflow-summary-lifecycle.d.ts.map +1 -0
  131. package/dist/core/workflow-summary-lifecycle.js +40 -0
  132. package/dist/core/workflow-summary-lifecycle.js.map +1 -0
  133. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  134. package/dist/extensions/codemode/execute.js +22 -6
  135. package/dist/extensions/codemode/execute.js.map +1 -1
  136. package/dist/extensions/codemode/renderer.d.ts +7 -1
  137. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  138. package/dist/extensions/codemode/renderer.js +12 -1
  139. package/dist/extensions/codemode/renderer.js.map +1 -1
  140. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  141. package/dist/extensions/codemode/tool.js +25 -12
  142. package/dist/extensions/codemode/tool.js.map +1 -1
  143. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  144. package/dist/extensions/mcp/cli.js +4 -7
  145. package/dist/extensions/mcp/cli.js.map +1 -1
  146. package/dist/extensions/mcp/client/client.d.ts.map +1 -1
  147. package/dist/extensions/mcp/client/client.js +5 -4
  148. package/dist/extensions/mcp/client/client.js.map +1 -1
  149. package/dist/extensions/mcp/client/index.d.ts +2 -2
  150. package/dist/extensions/mcp/client/index.d.ts.map +1 -1
  151. package/dist/extensions/mcp/client/index.js.map +1 -1
  152. package/dist/extensions/mcp/client/protocol/content.d.ts +4 -1
  153. package/dist/extensions/mcp/client/protocol/content.d.ts.map +1 -1
  154. package/dist/extensions/mcp/client/protocol/content.js.map +1 -1
  155. package/dist/extensions/mcp/client/transports/streamable-http.d.ts +2 -2
  156. package/dist/extensions/mcp/client/transports/streamable-http.d.ts.map +1 -1
  157. package/dist/extensions/mcp/client/transports/streamable-http.js +7 -5
  158. package/dist/extensions/mcp/client/transports/streamable-http.js.map +1 -1
  159. package/dist/extensions/mcp/client/transports/transport.d.ts +4 -1
  160. package/dist/extensions/mcp/client/transports/transport.d.ts.map +1 -1
  161. package/dist/extensions/mcp/client/transports/transport.js.map +1 -1
  162. package/dist/extensions/mcp/index.d.ts.map +1 -1
  163. package/dist/extensions/mcp/index.js +2 -4
  164. package/dist/extensions/mcp/index.js.map +1 -1
  165. package/dist/extensions/mcp/runtime.d.ts +1 -8
  166. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  167. package/dist/extensions/mcp/runtime.js +2 -41
  168. package/dist/extensions/mcp/runtime.js.map +1 -1
  169. package/dist/extensions/mcp/tools.d.ts +2 -3
  170. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  171. package/dist/extensions/mcp/tools.js +62 -6
  172. package/dist/extensions/mcp/tools.js.map +1 -1
  173. package/dist/index-extensions.d.ts +1 -1
  174. package/dist/index-extensions.d.ts.map +1 -1
  175. package/dist/index-extensions.js.map +1 -1
  176. package/dist/index.d.ts +1 -1
  177. package/dist/index.d.ts.map +1 -1
  178. package/dist/index.js.map +1 -1
  179. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  180. package/dist/modes/interactive/components/custom-editor.js +2 -2
  181. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  182. package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
  183. package/dist/modes/interactive/components/session-selector-list.js +2 -1
  184. package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
  185. package/dist/modes/interactive/components/settings-selector-items.js +1 -1
  186. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  187. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  188. package/dist/modes/interactive/components/tool-execution.js +1 -0
  189. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  190. package/dist/modes/print-mode.d.ts.map +1 -1
  191. package/dist/modes/print-mode.js +5 -0
  192. package/dist/modes/print-mode.js.map +1 -1
  193. package/dist/modes/rpc/rpc-client-api.d.ts +7 -2
  194. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  195. package/dist/modes/rpc/rpc-client-api.js +13 -0
  196. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  197. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  198. package/dist/modes/rpc/rpc-command-handler.js +19 -0
  199. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  200. package/dist/modes/rpc/rpc-types.d.ts +50 -1
  201. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  202. package/dist/modes/rpc/rpc-types.js.map +1 -1
  203. package/dist/utils/clipboard.d.ts.map +1 -1
  204. package/dist/utils/clipboard.js +10 -1
  205. package/dist/utils/clipboard.js.map +1 -1
  206. package/docs/codemode.md +2 -2
  207. package/docs/environment-variables.md +1 -0
  208. package/docs/extensions/authoring.md +2 -0
  209. package/docs/extensions/events.md +9 -3
  210. package/docs/getting-started/installation.md +1 -1
  211. package/docs/guides/non-interactive.md +2 -0
  212. package/docs/keybindings.md +1 -1
  213. package/docs/mcp-servers.md +2 -0
  214. package/docs/packages/reference.md +2 -0
  215. package/docs/providers.md +20 -0
  216. package/docs/rpc/protocol.md +15 -0
  217. package/docs/rpc.md +1 -0
  218. package/docs/sdk.md +11 -7
  219. package/docs/sessions.md +2 -2
  220. package/docs/settings.md +1 -1
  221. package/docs/tui/reference.md +5 -3
  222. package/docs/workflows/operations.md +11 -3
  223. package/examples/extensions/overlay-test.ts +2 -2
  224. package/npm-shrinkwrap.json +53 -550
  225. package/package.json +6 -12
  226. package/dist/client/index.d.ts +0 -2
  227. package/dist/client/index.d.ts.map +0 -1
  228. package/dist/client/index.js +0 -2
  229. package/dist/client/index.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { type ModelType, type Provider } from "@bastani/pi-ai";
1
+ import { type AnyModel, type ModelType, type Provider, type RefreshModelsContext } from "@bastani/pi-ai";
2
2
  export declare const REMOTE_CATALOG_REFRESH_INTERVAL_MS: number;
3
3
  /**
4
4
  * Model types this client can consume. Sent as `?types=` so the catalog server
@@ -7,6 +7,17 @@ export declare const REMOTE_CATALOG_REFRESH_INTERVAL_MS: number;
7
7
  * the chat-only shard, which this client handles unchanged.
8
8
  */
9
9
  export declare const REMOTE_CATALOG_MODEL_TYPES: readonly ModelType[];
10
+ /** Replaces the catalog with a credential-specific model list. */
11
+ export type PersonalizeCatalog = (catalog: readonly AnyModel[], context: RefreshModelsContext) => Promise<readonly AnyModel[]>;
10
12
  /** Add a persisted pi.dev catalog overlay to a static built-in provider. */
11
13
  export declare function withRemoteCatalog(provider: Provider, catalogBaseUrl?: string, localGeneratedAt?: number): Provider;
14
+ /**
15
+ * Like `withRemoteCatalog`, but on each network refresh the catalog (built-in models plus a newer
16
+ * pi.dev catalog) is passed through `personalize` and the result is saved. The saved entry holds
17
+ * the personalized list, not the pi.dev catalog, and replaces the catalog, including offline.
18
+ * The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an
19
+ * empty catalog saved by an older version after a failed or missing pi.dev catalog) falls back to
20
+ * the built-in models.
21
+ */
22
+ export declare function withPersonalizedCatalog(provider: Provider, personalize: PersonalizeCatalog, catalogBaseUrl?: string, localGeneratedAt?: number): Provider;
12
23
  //# sourceMappingURL=remote-catalog-provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"remote-catalog-provider.d.ts","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,MAAM,gBAAgB,CAAC;AAOxB,eAAO,MAAM,kCAAkC,QAAqB,CAAC;AACrE;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,EAAE,SAAS,SAAS,EAAoC,CAAC;AAmEhG,4EAA4E;AAC5E,wBAAgB,iBAAiB,CAChC,QAAQ,EAAE,QAAQ,EAClB,cAAc,GAAE,MAAiC,EACjD,gBAAgB,CAAC,EAAE,MAAM,GACvB,QAAQ,CAsGV"}
1
+ {"version":3,"file":"remote-catalog-provider.d.ts","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,QAAQ,EAIb,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,oBAAoB,EACzB,MAAM,gBAAgB,CAAC;AAOxB,eAAO,MAAM,kCAAkC,QAAqB,CAAC;AACrE;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,EAAE,SAAS,SAAS,EAAoC,CAAC;AAuGhG,kEAAkE;AAClE,MAAM,MAAM,kBAAkB,GAAG,CAChC,OAAO,EAAE,SAAS,QAAQ,EAAE,EAC5B,OAAO,EAAE,oBAAoB,KACzB,OAAO,CAAC,SAAS,QAAQ,EAAE,CAAC,CAAC;AAElC,4EAA4E;AAC5E,wBAAgB,iBAAiB,CAChC,QAAQ,EAAE,QAAQ,EAClB,cAAc,GAAE,MAAiC,EACjD,gBAAgB,CAAC,EAAE,MAAM,GACvB,QAAQ,CAsFV;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CACtC,QAAQ,EAAE,QAAQ,EAClB,WAAW,EAAE,kBAAkB,EAC/B,cAAc,GAAE,MAAiC,EACjD,gBAAgB,CAAC,EAAE,MAAM,GACvB,QAAQ,CA6CV"}
@@ -64,13 +64,33 @@ function parseCatalog(providerId, value) {
64
64
  .filter(hasOperationShape)
65
65
  .map((model) => ({ ...model, provider: providerId }));
66
66
  }
67
+ /** Read a successful pi.dev catalog response. A missing or invalid Last-Modified header is 0. */
68
+ async function readCatalog(providerId, response) {
69
+ const lastModified = Date.parse(response.headers.get("last-modified") ?? "");
70
+ return {
71
+ models: parseCatalog(providerId, await response.json()),
72
+ lastModified: Number.isNaN(lastModified) ? 0 : lastModified,
73
+ etag: response.headers.get("etag") ?? undefined,
74
+ };
75
+ }
76
+ /** Whether a pi.dev catalog is newer than the model data shipped with Atomic. */
77
+ function isNewer(lastModified, localGeneratedAt) {
78
+ return localGeneratedAt === undefined || (lastModified !== undefined && lastModified > localGeneratedAt);
79
+ }
67
80
  function remoteModels(entry, localGeneratedAt) {
68
- if (!entry)
69
- return [];
70
- if (localGeneratedAt !== undefined && (entry.lastModified === undefined || entry.lastModified <= localGeneratedAt)) {
71
- return [];
72
- }
73
- return entry.models;
81
+ return entry && isNewer(entry.lastModified, localGeneratedAt) ? entry.models : [];
82
+ }
83
+ function requestCatalog(providerId, catalogBaseUrl, signal, validator) {
84
+ const url = new URL(`/api/models/providers/${encodeURIComponent(providerId)}`, catalogBaseUrl);
85
+ url.searchParams.set("types", REMOTE_CATALOG_MODEL_TYPES.join(","));
86
+ return fetchWithRetry(url, {
87
+ headers: {
88
+ accept: "application/json",
89
+ "User-Agent": getPiUserAgent(VERSION),
90
+ ...(validator ? { "if-none-match": validator } : {}),
91
+ },
92
+ signal,
93
+ }, { attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS });
74
94
  }
75
95
  /** Add a persisted pi.dev catalog overlay to a static built-in provider. */
76
96
  export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BASE_URL, localGeneratedAt) {
@@ -98,6 +118,9 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
98
118
  }
99
119
  if (!context.allowNetwork || context.signal.aborted)
100
120
  return;
121
+ // Skip the request if pi.dev was checked less than REMOTE_CATALOG_REFRESH_INTERVAL_MS ago.
122
+ // An entry without lastModified (saved by an older version, or after a failed first request) is
123
+ // always refetched: remoteModels() ignores it, so waiting would leave the overlay empty.
101
124
  if (!context.force &&
102
125
  stored?.checkedAt !== undefined &&
103
126
  stored.lastModified !== undefined &&
@@ -107,16 +130,7 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
107
130
  // Only revalidate when a cached body backs the validator, so a 304 can never
108
131
  // leave the overlay empty.
109
132
  const validator = stored && stored.models.length > 0 ? stored.etag : undefined;
110
- const url = new URL(`/api/models/providers/${encodeURIComponent(provider.id)}`, catalogBaseUrl);
111
- url.searchParams.set("types", REMOTE_CATALOG_MODEL_TYPES.join(","));
112
- const response = await fetchWithRetry(url, {
113
- headers: {
114
- accept: "application/json",
115
- "User-Agent": getPiUserAgent(VERSION),
116
- ...(validator ? { "if-none-match": validator } : {}),
117
- },
118
- signal: context.signal,
119
- }, { attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS });
133
+ const response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, validator);
120
134
  if (context.signal.aborted)
121
135
  return;
122
136
  const checkedAt = Date.now();
@@ -143,16 +157,10 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
143
157
  await context.publish({ persist: { ...(stored ?? { models: [] }), checkedAt } });
144
158
  throw new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);
145
159
  }
146
- const refreshed = parseCatalog(provider.id, await response.json());
147
- const lastModified = Date.parse(response.headers.get("last-modified") ?? "");
160
+ const catalog = await readCatalog(provider.id, response);
148
161
  if (context.signal.aborted)
149
162
  return;
150
- const entry = {
151
- models: refreshed,
152
- checkedAt,
153
- lastModified: Number.isNaN(lastModified) ? 0 : lastModified,
154
- etag: response.headers.get("etag") ?? undefined,
155
- };
163
+ const entry = { ...catalog, checkedAt };
156
164
  const published = remoteModels(entry, localGeneratedAt);
157
165
  await context.publish({
158
166
  persist: entry,
@@ -163,4 +171,57 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
163
171
  },
164
172
  };
165
173
  }
174
+ /**
175
+ * Like `withRemoteCatalog`, but on each network refresh the catalog (built-in models plus a newer
176
+ * pi.dev catalog) is passed through `personalize` and the result is saved. The saved entry holds
177
+ * the personalized list, not the pi.dev catalog, and replaces the catalog, including offline.
178
+ * The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an
179
+ * empty catalog saved by an older version after a failed or missing pi.dev catalog) falls back to
180
+ * the built-in models.
181
+ */
182
+ export function withPersonalizedCatalog(provider, personalize, catalogBaseUrl = DEFAULT_CATALOG_BASE_URL, localGeneratedAt) {
183
+ let personalModels = [];
184
+ const builtinModels = () => provider.getAllModels?.() ?? provider.getModels();
185
+ const getAllModels = () => (personalModels.length > 0 ? personalModels : builtinModels());
186
+ return {
187
+ ...provider,
188
+ getModels: () => getAllModels().filter((model) => isModelType(model, "chat")),
189
+ getAllModels,
190
+ refreshModels: async (context) => {
191
+ const restored = (context.stored?.models ?? []).filter((model) => model.provider === provider.id && hasOperationShape(model));
192
+ if (!(await context.publish({
193
+ update: () => {
194
+ personalModels = restored;
195
+ },
196
+ }))) {
197
+ return;
198
+ }
199
+ if (!context.allowNetwork || context.signal.aborted)
200
+ return;
201
+ let remote = [];
202
+ try {
203
+ const response = await requestCatalog(provider.id, catalogBaseUrl, context.signal);
204
+ if (response.ok) {
205
+ const catalog = await readCatalog(provider.id, response);
206
+ if (isNewer(catalog.lastModified, localGeneratedAt))
207
+ remote = catalog.models;
208
+ }
209
+ }
210
+ catch {
211
+ remote = [];
212
+ }
213
+ if (context.signal.aborted)
214
+ return;
215
+ const personalized = await personalize(mergeModels(builtinModels(), remote), context);
216
+ if (context.signal.aborted)
217
+ return;
218
+ await context.publish({
219
+ persist: { models: personalized, checkedAt: Date.now() },
220
+ update: () => {
221
+ personalModels = personalized;
222
+ },
223
+ });
224
+ },
225
+ };
226
+ }
166
227
  //# sourceMappingURL=remote-catalog-provider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"remote-catalog-provider.js","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,YAAY,EACZ,WAAW,GAIX,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,MAAM,wBAAwB,GAAG,gBAAgB,CAAC;AAClD,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAChD,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACrE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAyB,CAAC,MAAM,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC;AAEhG,SAAS,oBAAoB,CAAC,KAAyB;IACtD,OAAO,CACN,KAAK,CAAC,IAAI,KAAK,SAAS;QACxB,CAAC,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,0BAA0B,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAiB,CAAC,CAAC,CAChG,CAAC;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc;IACxC,IAAI,OAAO,KAAK,KAAK,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;YACD,MAAM,SAAS,GAAG,YAAY,CAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;YACnE,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,EAAE,CAAC,CAAC;YAC7E,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO;YACnC,MAAM,KAAK,GAAqB;gBAC/B,MAAM,EAAE,SAAS;gBACjB,SAAS;gBACT,YAAY,EAAE,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY;gBAC3D,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,SAAS;aAC/C,CAAC;YACF,MAAM,SAAS,GAAG,YAAY,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;YACxD,MAAM,OAAO,CAAC,OAAO,CAAC;gBACrB,OAAO,EAAE,KAAK;gBACd,MAAM,EAAE,GAAG,EAAE;oBACZ,aAAa,GAAG,SAAS,CAAC;gBAC3B,CAAC;aACD,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype AnyModel,\n\tgetModelType,\n\tisModelType,\n\ttype ModelsStoreEntry,\n\ttype ModelType,\n\ttype Provider,\n} from \"@bastani/pi-ai\";\nimport { VERSION } from \"../config.js\";\nimport { fetchWithRetry } from \"../utils/management-http.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\n\nconst DEFAULT_CATALOG_BASE_URL = \"https://pi.dev\";\nconst REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS = 4_000;\nexport const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;\n/**\n * Model types this client can consume. Sent as `?types=` so the catalog server\n * returns the full-type shard instead of the chat-only one served to clients\n * that predate model types. A server that ignores the parameter still returns\n * the chat-only shard, which this client handles unchanged.\n */\nexport const REMOTE_CATALOG_MODEL_TYPES: readonly ModelType[] = [\"chat\", \"image\", \"classifier\"];\n\nfunction isSupportedModelType(model: { type?: unknown }): boolean {\n\treturn (\n\t\tmodel.type === undefined ||\n\t\t(typeof model.type === \"string\" && REMOTE_CATALOG_MODEL_TYPES.includes(model.type as ModelType))\n\t);\n}\n\nfunction hasOperationShape(model: unknown): boolean {\n\tif (typeof model !== \"object\" || model === null) return false;\n\tif (!(\"type\" in model) || (model.type !== \"image\" && model.type !== \"classifier\")) return true;\n\tif (!(\"cost\" in model)) return false;\n\tconst cost = model.cost;\n\treturn (\n\t\t\"id\" in model &&\n\t\ttypeof model.id === \"string\" &&\n\t\tmodel.id.length > 0 &&\n\t\t\"name\" in model &&\n\t\ttypeof model.name === \"string\" &&\n\t\t\"api\" in model &&\n\t\ttypeof model.api === \"string\" &&\n\t\t\"baseUrl\" in model &&\n\t\ttypeof model.baseUrl === \"string\" &&\n\t\t\"input\" in model &&\n\t\tArray.isArray(model.input) &&\n\t\tcost !== null &&\n\t\ttypeof cost === \"object\" &&\n\t\t[\"input\", \"output\", \"cacheRead\", \"cacheWrite\"].every(\n\t\t\t(key) => key in cost && typeof (cost as Record<string, unknown>)[key] === \"number\",\n\t\t) &&\n\t\t(model.type === \"image\"\n\t\t\t? \"output\" in model && Array.isArray(model.output) && model.output.includes(\"image\")\n\t\t\t: \"contextWindow\" in model && typeof model.contextWindow === \"number\" && model.contextWindow > 0)\n\t);\n}\n\nfunction mergeModels<TModel extends AnyModel>(baseline: readonly TModel[], dynamic: readonly TModel[]): TModel[] {\n\tconst merged = new Map<string, TModel>();\n\tfor (const model of [...baseline, ...dynamic]) merged.set(`${getModelType(model)}\\0${model.id}`, model);\n\treturn [...merged.values()];\n}\n\nfunction parseCatalog(providerId: string, value: unknown): AnyModel[] {\n\tconst entries = Array.isArray(value)\n\t\t? value\n\t\t: typeof value === \"object\" && value !== null && \"models\" in value && Array.isArray(value.models)\n\t\t\t? value.models\n\t\t\t: typeof value === \"object\" && value !== null\n\t\t\t\t? Object.values(value)\n\t\t\t\t: undefined;\n\tif (!entries) throw new Error(`Invalid model catalog for provider \"${providerId}\"`);\n\treturn entries\n\t\t.filter((entry): entry is Record<string, unknown> => typeof entry === \"object\" && entry !== null && \"id\" in entry)\n\t\t.filter(isSupportedModelType)\n\t\t.filter(hasOperationShape)\n\t\t.map((model) => ({ ...model, provider: providerId }) as AnyModel);\n}\n\nfunction remoteModels(entry: ModelsStoreEntry | undefined, localGeneratedAt: number | undefined): readonly AnyModel[] {\n\tif (!entry) return [];\n\tif (localGeneratedAt !== undefined && (entry.lastModified === undefined || entry.lastModified <= localGeneratedAt)) {\n\t\treturn [];\n\t}\n\treturn entry.models;\n}\n\n/** Add a persisted pi.dev catalog overlay to a static built-in provider. */\nexport function withRemoteCatalog(\n\tprovider: Provider,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tconst models = provider.getAllModels?.() ?? provider.getModels();\n\tif (models.length > 0 && !models.some(isSupportedModelType)) return provider;\n\n\tlet dynamicModels: readonly AnyModel[] = [];\n\n\treturn {\n\t\t...provider,\n\t\tgetModels: () =>\n\t\t\tmergeModels(\n\t\t\t\tprovider.getModels(),\n\t\t\t\tdynamicModels.filter((model) => isModelType(model, \"chat\")),\n\t\t\t),\n\t\tgetAllModels: () => mergeModels(provider.getAllModels?.() ?? provider.getModels(), dynamicModels),\n\t\trefreshModels: async (context) => {\n\t\t\t// 0.84.1 hands the snapshot in directly and coalesces concurrent refreshes\n\t\t\t// itself, so the old inflight-promise dedup is gone. Every mutation of\n\t\t\t// dynamicModels now runs inside a generation-checked publish; a false return\n\t\t\t// means a newer refresh already superseded this pass, so it must not continue.\n\t\t\tconst stored = context.stored;\n\t\t\tconst restored = remoteModels(stored, localGeneratedAt).filter(\n\t\t\t\t(model) => model.provider === provider.id && hasOperationShape(model),\n\t\t\t);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tdynamicModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\tif (\n\t\t\t\t!context.force &&\n\t\t\t\tstored?.checkedAt !== undefined &&\n\t\t\t\tstored.lastModified !== undefined &&\n\t\t\t\tDate.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Only revalidate when a cached body backs the validator, so a 304 can never\n\t\t\t// leave the overlay empty.\n\t\t\tconst validator = stored && stored.models.length > 0 ? stored.etag : undefined;\n\t\t\tconst url = new URL(`/api/models/providers/${encodeURIComponent(provider.id)}`, catalogBaseUrl);\n\t\t\turl.searchParams.set(\"types\", REMOTE_CATALOG_MODEL_TYPES.join(\",\"));\n\t\t\tconst response = await fetchWithRetry(\n\t\t\t\turl,\n\t\t\t\t{\n\t\t\t\t\theaders: {\n\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t\t\t\t...(validator ? { \"if-none-match\": validator } : {}),\n\t\t\t\t\t},\n\t\t\t\t\tsignal: context.signal,\n\t\t\t\t},\n\t\t\t\t{ attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS },\n\t\t\t);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst checkedAt = Date.now();\n\t\t\t// Unchanged: dynamicModels already holds the stored overlay, so only the\n\t\t\t// freshness window moves.\n\t\t\tif (response.status === 304 && stored) {\n\t\t\t\tawait context.publish({ persist: { ...stored, checkedAt } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.status === 404 || response.status === 501) {\n\t\t\t\tawait context.publish({\n\t\t\t\t\tpersist: {\n\t\t\t\t\t\t...(stored ?? { models: [] }),\n\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\tlastModified: 0,\n\t\t\t\t\t\tetag: undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\t// Transient failure: the cached body and its validator stay valid, so keep the\n\t\t\t\t// etag and let the next refresh revalidate instead of downloading the catalog.\n\t\t\t\tawait context.publish({ persist: { ...(stored ?? { models: [] }), checkedAt } });\n\t\t\t\tthrow new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);\n\t\t\t}\n\t\t\tconst refreshed = parseCatalog(provider.id, await response.json());\n\t\t\tconst lastModified = Date.parse(response.headers.get(\"last-modified\") ?? \"\");\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst entry: ModelsStoreEntry = {\n\t\t\t\tmodels: refreshed,\n\t\t\t\tcheckedAt,\n\t\t\t\tlastModified: Number.isNaN(lastModified) ? 0 : lastModified,\n\t\t\t\tetag: response.headers.get(\"etag\") ?? undefined,\n\t\t\t};\n\t\t\tconst published = remoteModels(entry, localGeneratedAt);\n\t\t\tawait context.publish({\n\t\t\t\tpersist: entry,\n\t\t\t\tupdate: () => {\n\t\t\t\t\tdynamicModels = published;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"remote-catalog-provider.js","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,YAAY,EACZ,WAAW,GAKX,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,MAAM,wBAAwB,GAAG,gBAAgB,CAAC;AAClD,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAChD,MA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AC;aACD,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype AnyModel,\n\tgetModelType,\n\tisModelType,\n\ttype ModelsStoreEntry,\n\ttype ModelType,\n\ttype Provider,\n\ttype RefreshModelsContext,\n} from \"@bastani/pi-ai\";\nimport { VERSION } from \"../config.js\";\nimport { fetchWithRetry } from \"../utils/management-http.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\n\nconst DEFAULT_CATALOG_BASE_URL = \"https://pi.dev\";\nconst REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS = 4_000;\nexport const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;\n/**\n * Model types this client can consume. Sent as `?types=` so the catalog server\n * returns the full-type shard instead of the chat-only one served to clients\n * that predate model types. A server that ignores the parameter still returns\n * the chat-only shard, which this client handles unchanged.\n */\nexport const REMOTE_CATALOG_MODEL_TYPES: readonly ModelType[] = [\"chat\", \"image\", \"classifier\"];\n\nfunction isSupportedModelType(model: { type?: unknown }): boolean {\n\treturn (\n\t\tmodel.type === undefined ||\n\t\t(typeof model.type === \"string\" && REMOTE_CATALOG_MODEL_TYPES.includes(model.type as ModelType))\n\t);\n}\n\nfunction hasOperationShape(model: unknown): boolean {\n\tif (typeof model !== \"object\" || model === null) return false;\n\tif (!(\"type\" in model) || (model.type !== \"image\" && model.type !== \"classifier\")) return true;\n\tif (!(\"cost\" in model)) return false;\n\tconst cost = model.cost;\n\treturn (\n\t\t\"id\" in model &&\n\t\ttypeof model.id === \"string\" &&\n\t\tmodel.id.length > 0 &&\n\t\t\"name\" in model &&\n\t\ttypeof model.name === \"string\" &&\n\t\t\"api\" in model &&\n\t\ttypeof model.api === \"string\" &&\n\t\t\"baseUrl\" in model &&\n\t\ttypeof model.baseUrl === \"string\" &&\n\t\t\"input\" in model &&\n\t\tArray.isArray(model.input) &&\n\t\tcost !== null &&\n\t\ttypeof cost === \"object\" &&\n\t\t[\"input\", \"output\", \"cacheRead\", \"cacheWrite\"].every(\n\t\t\t(key) => key in cost && typeof (cost as Record<string, unknown>)[key] === \"number\",\n\t\t) &&\n\t\t(model.type === \"image\"\n\t\t\t? \"output\" in model && Array.isArray(model.output) && model.output.includes(\"image\")\n\t\t\t: \"contextWindow\" in model && typeof model.contextWindow === \"number\" && model.contextWindow > 0)\n\t);\n}\n\nfunction mergeModels<TModel extends AnyModel>(baseline: readonly TModel[], dynamic: readonly TModel[]): TModel[] {\n\tconst merged = new Map<string, TModel>();\n\tfor (const model of [...baseline, ...dynamic]) merged.set(`${getModelType(model)}\\0${model.id}`, model);\n\treturn [...merged.values()];\n}\n\nfunction parseCatalog(providerId: string, value: unknown): AnyModel[] {\n\tconst entries = Array.isArray(value)\n\t\t? value\n\t\t: typeof value === \"object\" && value !== null && \"models\" in value && Array.isArray(value.models)\n\t\t\t? value.models\n\t\t\t: typeof value === \"object\" && value !== null\n\t\t\t\t? Object.values(value)\n\t\t\t\t: undefined;\n\tif (!entries) throw new Error(`Invalid model catalog for provider \"${providerId}\"`);\n\treturn entries\n\t\t.filter((entry): entry is Record<string, unknown> => typeof entry === \"object\" && entry !== null && \"id\" in entry)\n\t\t.filter(isSupportedModelType)\n\t\t.filter(hasOperationShape)\n\t\t.map((model) => ({ ...model, provider: providerId }) as AnyModel);\n}\n\n/** Read a successful pi.dev catalog response. A missing or invalid Last-Modified header is 0. */\nasync function readCatalog(\n\tproviderId: string,\n\tresponse: Response,\n): Promise<{ models: AnyModel[]; lastModified: number; etag: string | undefined }> {\n\tconst lastModified = Date.parse(response.headers.get(\"last-modified\") ?? \"\");\n\treturn {\n\t\tmodels: parseCatalog(providerId, await response.json()),\n\t\tlastModified: Number.isNaN(lastModified) ? 0 : lastModified,\n\t\tetag: response.headers.get(\"etag\") ?? undefined,\n\t};\n}\n\n/** Whether a pi.dev catalog is newer than the model data shipped with Atomic. */\nfunction isNewer(lastModified: number | undefined, localGeneratedAt: number | undefined): boolean {\n\treturn localGeneratedAt === undefined || (lastModified !== undefined && lastModified > localGeneratedAt);\n}\n\nfunction remoteModels(entry: ModelsStoreEntry | undefined, localGeneratedAt: number | undefined): readonly AnyModel[] {\n\treturn entry && isNewer(entry.lastModified, localGeneratedAt) ? entry.models : [];\n}\n\nfunction requestCatalog(\n\tproviderId: string,\n\tcatalogBaseUrl: string,\n\tsignal: AbortSignal,\n\tvalidator?: string,\n): Promise<Response> {\n\tconst url = new URL(`/api/models/providers/${encodeURIComponent(providerId)}`, catalogBaseUrl);\n\turl.searchParams.set(\"types\", REMOTE_CATALOG_MODEL_TYPES.join(\",\"));\n\treturn fetchWithRetry(\n\t\turl,\n\t\t{\n\t\t\theaders: {\n\t\t\t\taccept: \"application/json\",\n\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t\t...(validator ? { \"if-none-match\": validator } : {}),\n\t\t\t},\n\t\t\tsignal,\n\t\t},\n\t\t{ attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS },\n\t);\n}\n\n/** Replaces the catalog with a credential-specific model list. */\nexport type PersonalizeCatalog = (\n\tcatalog: readonly AnyModel[],\n\tcontext: RefreshModelsContext,\n) => Promise<readonly AnyModel[]>;\n\n/** Add a persisted pi.dev catalog overlay to a static built-in provider. */\nexport function withRemoteCatalog(\n\tprovider: Provider,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tconst models = provider.getAllModels?.() ?? provider.getModels();\n\tif (models.length > 0 && !models.some(isSupportedModelType)) return provider;\n\n\tlet dynamicModels: readonly AnyModel[] = [];\n\n\treturn {\n\t\t...provider,\n\t\tgetModels: () =>\n\t\t\tmergeModels(\n\t\t\t\tprovider.getModels(),\n\t\t\t\tdynamicModels.filter((model) => isModelType(model, \"chat\")),\n\t\t\t),\n\t\tgetAllModels: () => mergeModels(provider.getAllModels?.() ?? provider.getModels(), dynamicModels),\n\t\trefreshModels: async (context) => {\n\t\t\t// 0.84.1 hands the snapshot in directly and coalesces concurrent refreshes\n\t\t\t// itself, so the old inflight-promise dedup is gone. Every mutation of\n\t\t\t// dynamicModels now runs inside a generation-checked publish; a false return\n\t\t\t// means a newer refresh already superseded this pass, so it must not continue.\n\t\t\tconst stored = context.stored;\n\t\t\tconst restored = remoteModels(stored, localGeneratedAt).filter(\n\t\t\t\t(model) => model.provider === provider.id && hasOperationShape(model),\n\t\t\t);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tdynamicModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\t// Skip the request if pi.dev was checked less than REMOTE_CATALOG_REFRESH_INTERVAL_MS ago.\n\t\t\t// An entry without lastModified (saved by an older version, or after a failed first request) is\n\t\t\t// always refetched: remoteModels() ignores it, so waiting would leave the overlay empty.\n\t\t\tif (\n\t\t\t\t!context.force &&\n\t\t\t\tstored?.checkedAt !== undefined &&\n\t\t\t\tstored.lastModified !== undefined &&\n\t\t\t\tDate.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Only revalidate when a cached body backs the validator, so a 304 can never\n\t\t\t// leave the overlay empty.\n\t\t\tconst validator = stored && stored.models.length > 0 ? stored.etag : undefined;\n\t\t\tconst response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, validator);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst checkedAt = Date.now();\n\t\t\t// Unchanged: dynamicModels already holds the stored overlay, so only the\n\t\t\t// freshness window moves.\n\t\t\tif (response.status === 304 && stored) {\n\t\t\t\tawait context.publish({ persist: { ...stored, checkedAt } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.status === 404 || response.status === 501) {\n\t\t\t\tawait context.publish({\n\t\t\t\t\tpersist: {\n\t\t\t\t\t\t...(stored ?? { models: [] }),\n\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\tlastModified: 0,\n\t\t\t\t\t\tetag: undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\t// Transient failure: the cached body and its validator stay valid, so keep the\n\t\t\t\t// etag and let the next refresh revalidate instead of downloading the catalog.\n\t\t\t\tawait context.publish({ persist: { ...(stored ?? { models: [] }), checkedAt } });\n\t\t\t\tthrow new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);\n\t\t\t}\n\t\t\tconst catalog = await readCatalog(provider.id, response);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst entry: ModelsStoreEntry = { ...catalog, checkedAt };\n\t\t\tconst published = remoteModels(entry, localGeneratedAt);\n\t\t\tawait context.publish({\n\t\t\t\tpersist: entry,\n\t\t\t\tupdate: () => {\n\t\t\t\t\tdynamicModels = published;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * Like `withRemoteCatalog`, but on each network refresh the catalog (built-in models plus a newer\n * pi.dev catalog) is passed through `personalize` and the result is saved. The saved entry holds\n * the personalized list, not the pi.dev catalog, and replaces the catalog, including offline.\n * The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an\n * empty catalog saved by an older version after a failed or missing pi.dev catalog) falls back to\n * the built-in models.\n */\nexport function withPersonalizedCatalog(\n\tprovider: Provider,\n\tpersonalize: PersonalizeCatalog,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tlet personalModels: readonly AnyModel[] = [];\n\tconst builtinModels = (): readonly AnyModel[] => provider.getAllModels?.() ?? provider.getModels();\n\tconst getAllModels = (): readonly AnyModel[] => (personalModels.length > 0 ? personalModels : builtinModels());\n\n\treturn {\n\t\t...provider,\n\t\tgetModels: () => getAllModels().filter((model) => isModelType(model, \"chat\")),\n\t\tgetAllModels,\n\t\trefreshModels: async (context) => {\n\t\t\tconst restored = (context.stored?.models ?? []).filter(\n\t\t\t\t(model) => model.provider === provider.id && hasOperationShape(model),\n\t\t\t);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tpersonalModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\n\t\t\tlet remote: readonly AnyModel[] = [];\n\t\t\ttry {\n\t\t\t\tconst response = await requestCatalog(provider.id, catalogBaseUrl, context.signal);\n\t\t\t\tif (response.ok) {\n\t\t\t\t\tconst catalog = await readCatalog(provider.id, response);\n\t\t\t\t\tif (isNewer(catalog.lastModified, localGeneratedAt)) remote = catalog.models;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tremote = [];\n\t\t\t}\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst personalized = await personalize(mergeModels(builtinModels(), remote), context);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tawait context.publish({\n\t\t\t\tpersist: { models: personalized, checkedAt: Date.now() },\n\t\t\t\tupdate: () => {\n\t\t\t\t\tpersonalModels = personalized;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
@@ -23,6 +23,8 @@ export interface ForkedSessionFile {
23
23
  cwd: string;
24
24
  sessionDir: string;
25
25
  sessionFile: string;
26
+ fileEntries: FileEntry[];
26
27
  }
27
28
  export declare function forkSessionFromFile(sourcePath: string, targetCwd: string, sessionDir?: string, options?: NewSessionOptions): ForkedSessionFile;
29
+ export declare function forkSessionFromFileAsync(sourcePath: string, targetCwd: string, sessionDir?: string, options?: NewSessionOptions): Promise<ForkedSessionFile>;
28
30
  //# sourceMappingURL=session-manager-archive.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-manager-archive.d.ts","sourceRoot":"","sources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 {"version":3,"file":"session-manager-archive.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-archive.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EACX,SAAS,EAET,iBAAiB,EACjB,YAAY,EAEZ,uBAAuB,EACvB,MAAM,4BAA4B,CAAC;AAGpC,wBAAgB,oBAAoB,CACnC,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,OAAO,EAAE,SAAS,EAAE,EACpB,KAAK,SAAY,GACf,MAAM,GAAG,SAAS,CAWpB;AAED,MAAM,WAAW,yBAAyB;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,mBAAmB,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,QAAQ,CAAC,EAAE,uBAAuB,CAAC;IACnC,IAAI,EAAE,YAAY,EAAE,CAAC;IACrB,UAAU,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,mBAAmB,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjD;AAED,MAAM,WAAW,oBAAoB;IACpC,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,WAAW,EAAE,SAAS,EAAE,CAAC;IACzB,iBAAiB,EAAE,OAAO,CAAC;IAC3B,OAAO,CAAC,EAAE,OAAO,CAAC;CAClB;AAsDD,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,yBAAyB,GAAG,oBAAoB,CAmEjG;AAED,MAAM,WAAW,iBAAiB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,SAAS,EAAE,CAAC;CACzB;AAED,wBAAgB,mBAAmB,CAClC,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,UAAU,CAAC,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,iBAAiB,GACzB,iBAAiB,CAMnB;AAED,wBAAsB,wBAAwB,CAC7C,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,UAAU,CAAC,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,iBAAiB,GACzB,OAAO,CAAC,iBAAiB,CAAC,CAc5B"}
@@ -1,8 +1,12 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import { createInterface } from "node:readline";
1
4
  import { join } from "path";
2
5
  import { normalizePath, resolvePath } from "../utils/paths.js";
3
6
  import { createLabelEntry, createSessionFilePath, createSessionHeader } from "./session-manager-entries.js";
4
- import { getDefaultSessionDir } from "./session-manager-paths.js";
5
- import { appendSessionEntry, ensureDirectory, hasConversationMessage, loadEntriesFromFile, writeSessionEntries, } from "./session-manager-storage.js";
7
+ import { migrateToCurrentVersion, parseSessionEntries } from "./session-manager-migrations.js";
8
+ import { getDefaultSessionDirPath } from "./session-manager-paths.js";
9
+ import { ensureDirectory, hasConversationMessage, loadEntriesFromFile, serializeSessionEntries, writeSessionEntries, } from "./session-manager-storage.js";
6
10
  import { assertValidSessionId, createSessionId, generateId } from "./session-manager-validation.js";
7
11
  export function createBackupSnapshot(sessionFile, entries, label = "compact") {
8
12
  if (!sessionFile)
@@ -109,34 +113,52 @@ export function createBranchedSessionState(input) {
109
113
  };
110
114
  }
111
115
  export function forkSessionFromFile(sourcePath, targetCwd, sessionDir, options) {
116
+ const sourceEntries = loadEntriesFromFile(resolvePath(sourcePath));
117
+ const forked = prepareFork(sourcePath, targetCwd, sourceEntries, sessionDir, options);
118
+ ensureDirectory(forked.sessionDir);
119
+ writeSessionEntries(forked.sessionFile, forked.fileEntries);
120
+ return forked;
121
+ }
122
+ export async function forkSessionFromFileAsync(sourcePath, targetCwd, sessionDir, options) {
123
+ const sourceEntries = [];
124
+ const input = createReadStream(resolvePath(sourcePath), { encoding: "utf8" });
125
+ const lines = createInterface({ input, crlfDelay: Infinity });
126
+ try {
127
+ for await (const line of lines)
128
+ sourceEntries.push(...parseSessionEntries(line));
129
+ }
130
+ finally {
131
+ lines.close();
132
+ input.destroy();
133
+ }
134
+ const forked = prepareFork(sourcePath, targetCwd, sourceEntries, sessionDir, options);
135
+ await mkdir(forked.sessionDir, { recursive: true });
136
+ await writeFile(forked.sessionFile, serializeSessionEntries(forked.fileEntries));
137
+ return forked;
138
+ }
139
+ function prepareFork(sourcePath, targetCwd, sourceEntries, sessionDir, options) {
112
140
  const resolvedSourcePath = resolvePath(sourcePath);
113
141
  const resolvedTargetCwd = resolvePath(targetCwd);
114
- const sourceEntries = loadEntriesFromFile(resolvedSourcePath);
115
142
  if (sourceEntries.length === 0) {
116
143
  throw new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);
117
144
  }
118
- const sourceHeader = sourceEntries.find((entry) => entry.type === "session");
119
- if (!sourceHeader) {
145
+ const sourceHeader = sourceEntries[0];
146
+ if (sourceHeader.type !== "session" || typeof sourceHeader.id !== "string") {
120
147
  throw new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);
121
148
  }
122
- const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(resolvedTargetCwd);
123
- ensureDirectory(dir);
124
- // Create new session file with new ID but forked content
125
- if (options?.id !== undefined) {
149
+ migrateToCurrentVersion(sourceEntries);
150
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDirPath(resolvedTargetCwd);
151
+ if (options?.id !== undefined)
126
152
  assertValidSessionId(options.id);
127
- }
128
153
  const newSessionId = options?.id ?? createSessionId();
129
154
  const timestamp = new Date().toISOString();
130
155
  const newSessionFile = join(dir, `${timestamp.replace(/[:.]/g, "-")}_${newSessionId}.jsonl`);
131
- // Write new header pointing to source as parent, with updated cwd
132
156
  const newHeader = createSessionHeader(newSessionId, resolvedTargetCwd, timestamp, resolvedSourcePath, options?.internal, options?.workflow);
133
- appendSessionEntry(newSessionFile, newHeader);
134
- // Copy all non-header entries from source
135
- for (const entry of sourceEntries) {
136
- if (entry.type !== "session") {
137
- appendSessionEntry(newSessionFile, entry);
138
- }
139
- }
140
- return { cwd: resolvedTargetCwd, sessionDir: dir, sessionFile: newSessionFile };
157
+ return {
158
+ cwd: resolvedTargetCwd,
159
+ sessionDir: dir,
160
+ sessionFile: newSessionFile,
161
+ fileEntries: [newHeader, ...sourceEntries.filter((entry) => entry.type !== "session")],
162
+ };
141
163
  }
142
164
  //# sourceMappingURL=session-manager-archive.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-manager-archive.js","sourceRoot":"","sources":["../../src/core/session-manager-archive.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAC5G,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EACN,kBAAkB,EAClB,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,GACnB,MAAM,8BAA8B,CAAC;AAStC,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAEpG,MAAM,UAAU,oBAAoB,CACnC,WAA+B,EAC/B,OAAoB,EACpB,KAAK,GAAG,SAAS;IAEjB,IAAI,CAAC,WAAW;QAAE,OAAO,SAAS,CAAC;IACnC,MAAM,SAAS,GACd,KAAK;SACH,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC;SAC7B,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,QAAQ,CAAC;IACrC,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EA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B,EAAE,UAAU,EAAE,GAAG,EAAE,WAAW,EAAE,cAAc,EAAE,CAAC;AACjF,CAAC","sourcesContent":["import { join } from \"path\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport { createLabelEntry, createSessionFilePath, createSessionHeader } from \"./session-manager-entries.ts\";\nimport { getDefaultSessionDir } from \"./session-manager-paths.ts\";\nimport {\n\tappendSessionEntry,\n\tensureDirectory,\n\thasConversationMessage,\n\tloadEntriesFromFile,\n\twriteSessionEntries,\n} from \"./session-manager-storage.ts\";\nimport type {\n\tFileEntry,\n\tLabelEntry,\n\tNewSessionOptions,\n\tSessionEntry,\n\tSessionHeader,\n\tSessionWorkflowMetadata,\n} from \"./session-manager-types.ts\";\nimport { assertValidSessionId, createSessionId, generateId } from \"./session-manager-validation.ts\";\n\nexport function createBackupSnapshot(\n\tsessionFile: string | undefined,\n\tentries: FileEntry[],\n\tlabel = \"compact\",\n): string | undefined {\n\tif (!sessionFile) return undefined;\n\tconst safeLabel =\n\t\tlabel\n\t\t\t.replace(/[^a-z0-9_-]/gi, \"-\")\n\t\t\t.replace(/-+/g, \"-\")\n\t\t\t.replace(/^-|-$/g, \"\") || \"backup\";\n\tconst timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n\tconst backupPath = `${sessionFile}.${timestamp}.${safeLabel}.bak`;\n\twriteSessionEntries(backupPath, entries);\n\treturn backupPath;\n}\n\nexport interface BranchedSessionStateInput {\n\tleafId: string;\n\tpersist: boolean;\n\tsessionDir: string;\n\tcwd: string;\n\tpreviousSessionFile: string | undefined;\n\tworkflow?: SessionWorkflowMetadata;\n\tpath: SessionEntry[];\n\tlabelsById: ReadonlyMap<string, string>;\n\tlabelTimestampsById: ReadonlyMap<string, string>;\n}\n\nexport interface BranchedSessionState {\n\tsessionId: string;\n\tsessionFile: string | undefined;\n\tfileEntries: FileEntry[];\n\tshouldRewriteFile: boolean;\n\tflushed?: boolean;\n}\n\nfunction collectLabelsForPath(\n\tpathEntryIds: ReadonlySet<string>,\n\tlabelsById: ReadonlyMap<string, string>,\n\tlabelTimestampsById: ReadonlyMap<string, string>,\n): Array<{ targetId: string; label: string; timestamp: string }> {\n\tconst labelsToWrite: Array<{ targetId: string; label: string; timestamp: string }> = [];\n\tfor (const [targetId, label] of labelsById) {\n\t\tif (pathEntryIds.has(targetId)) {\n\t\t\tlabelsToWrite.push({ targetId, label, timestamp: labelTimestampsById.get(targetId)! });\n\t\t}\n\t}\n\treturn labelsToWrite;\n}\n\nfunction buildPersistedLabelEntries(\n\tpathEntryIds: Set<string>,\n\tlastEntryId: string | null,\n\tlabelsToWrite: Array<{ targetId: string; label: string; timestamp: string }>,\n): LabelEntry[] {\n\tlet parentId = lastEntryId;\n\tconst labelEntries: LabelEntry[] = [];\n\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\tconst labelEntry = createLabelEntry(targetId, label, new Set(pathEntryIds), parentId, labelTimestamp);\n\t\tpathEntryIds.add(labelEntry.id);\n\t\tlabelEntries.push(labelEntry);\n\t\tparentId = labelEntry.id;\n\t}\n\treturn labelEntries;\n}\n\nfunction buildInMemoryLabelEntries(\n\tpathEntryIds: Set<string>,\n\tlastEntryId: string | null,\n\tlabelsToWrite: Array<{ targetId: string; label: string; timestamp: string }>,\n): LabelEntry[] {\n\tconst labelEntries: LabelEntry[] = [];\n\tlet parentId = lastEntryId;\n\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\tconst labelEntry: LabelEntry = {\n\t\t\ttype: \"label\",\n\t\t\tid: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),\n\t\t\tparentId,\n\t\t\ttimestamp: labelTimestamp,\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t};\n\t\tlabelEntries.push(labelEntry);\n\t\tparentId = labelEntry.id;\n\t}\n\treturn labelEntries;\n}\n\nexport function createBranchedSessionState(input: BranchedSessionStateInput): BranchedSessionState {\n\tif (input.path.length === 0) {\n\t\tthrow new Error(`Entry ${input.leafId} not found`);\n\t}\n\n\t// Filter labels out, re-chain the retained path, and translate compaction boundaries\n\t// that pointed at a removed label to the first retained entry after it.\n\tconst pathWithoutLabels: SessionEntry[] = [];\n\tconst replacementByLabelId = new Map<string, string>();\n\tconst pendingLabelIds: string[] = [];\n\tlet pathParentId: string | null = null;\n\tfor (const entry of input.path) {\n\t\tif (entry.type === \"label\") {\n\t\t\tpendingLabelIds.push(entry.id);\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const labelId of pendingLabelIds) replacementByLabelId.set(labelId, entry.id);\n\t\tpendingLabelIds.length = 0;\n\t\tpathWithoutLabels.push(\n\t\t\tentry.type === \"compaction\"\n\t\t\t\t? {\n\t\t\t\t\t\t...entry,\n\t\t\t\t\t\tparentId: pathParentId,\n\t\t\t\t\t\tfirstKeptEntryId:\n\t\t\t\t\t\t\tentry.firstKeptEntryId === null\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: (replacementByLabelId.get(entry.firstKeptEntryId) ?? entry.firstKeptEntryId),\n\t\t\t\t\t}\n\t\t\t\t: { ...entry, parentId: pathParentId },\n\t\t);\n\t\tpathParentId = entry.id;\n\t}\n\tconst newSessionId = createSessionId();\n\tconst timestamp = new Date().toISOString();\n\tconst newSessionFile = createSessionFilePath(input.sessionDir, timestamp, newSessionId);\n\tconst header: SessionHeader = createSessionHeader(\n\t\tnewSessionId,\n\t\tinput.cwd,\n\t\ttimestamp,\n\t\tinput.persist ? input.previousSessionFile : undefined,\n\t\tinput.workflow !== undefined,\n\t\tinput.workflow,\n\t);\n\n\t// Collect labels for entries in the path\n\tconst pathEntryIds = new Set(pathWithoutLabels.map((entry) => entry.id));\n\tconst labelsToWrite = collectLabelsForPath(pathEntryIds, input.labelsById, input.labelTimestampsById);\n\tconst lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\tconst labelEntries = input.persist\n\t\t? buildPersistedLabelEntries(pathEntryIds, lastEntryId, labelsToWrite)\n\t\t: buildInMemoryLabelEntries(pathEntryIds, lastEntryId, labelsToWrite);\n\tconst fileEntries: FileEntry[] = [header, ...pathWithoutLabels, ...labelEntries];\n\n\tif (!input.persist) {\n\t\treturn { sessionId: newSessionId, sessionFile: undefined, fileEntries, shouldRewriteFile: false };\n\t}\n\n\t// Use the same rule as appended entries: write now if the branched path already has a\n\t// conversation, otherwise let the first user or assistant message create the file.\n\tconst shouldRewriteFile = hasConversationMessage(fileEntries);\n\treturn {\n\t\tsessionId: newSessionId,\n\t\tsessionFile: newSessionFile,\n\t\tfileEntries,\n\t\tshouldRewriteFile,\n\t\tflushed: shouldRewriteFile,\n\t};\n}\n\nexport interface ForkedSessionFile {\n\tcwd: string;\n\tsessionDir: string;\n\tsessionFile: string;\n}\n\nexport function forkSessionFromFile(\n\tsourcePath: string,\n\ttargetCwd: string,\n\tsessionDir?: string,\n\toptions?: NewSessionOptions,\n): ForkedSessionFile {\n\tconst resolvedSourcePath = resolvePath(sourcePath);\n\tconst resolvedTargetCwd = resolvePath(targetCwd);\n\tconst sourceEntries = loadEntriesFromFile(resolvedSourcePath);\n\tif (sourceEntries.length === 0) {\n\t\tthrow new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);\n\t}\n\n\tconst sourceHeader = sourceEntries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\tif (!sourceHeader) {\n\t\tthrow new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);\n\t}\n\n\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(resolvedTargetCwd);\n\tensureDirectory(dir);\n\n\t// Create new session file with new ID but forked content\n\tif (options?.id !== undefined) {\n\t\tassertValidSessionId(options.id);\n\t}\n\tconst newSessionId = options?.id ?? createSessionId();\n\tconst timestamp = new Date().toISOString();\n\tconst newSessionFile = join(dir, `${timestamp.replace(/[:.]/g, \"-\")}_${newSessionId}.jsonl`);\n\n\t// Write new header pointing to source as parent, with updated cwd\n\tconst newHeader: SessionHeader = createSessionHeader(\n\t\tnewSessionId,\n\t\tresolvedTargetCwd,\n\t\ttimestamp,\n\t\tresolvedSourcePath,\n\t\toptions?.internal,\n\t\toptions?.workflow,\n\t);\n\tappendSessionEntry(newSessionFile, newHeader);\n\n\t// Copy all non-header entries from source\n\tfor (const entry of sourceEntries) {\n\t\tif (entry.type !== \"session\") {\n\t\t\tappendSessionEntry(newSessionFile, entry);\n\t\t}\n\t}\n\n\treturn { cwd: resolvedTargetCwd, sessionDir: dir, sessionFile: newSessionFile };\n}\n"]}
1
+ {"version":3,"file":"session-manager-archive.js","sourceRoot":"","sources":["../../src/core/session-manager-archive.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAC5G,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAC/F,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EACN,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,GACnB,MAAM,8BAA8B,CAAC;AAStC,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAEpG,MAAM,UAAU,oBAAoB,CACnC,WAA+B,EAC/B,OAAoB,EACpB,KAAK,GAAG,SAAS;IAEjB,IAAI,CAAC,WAAW;QAAE,OAAO,SAAS,CAAC;IACnC,MAAM,SAAS,GACd,KAAK;SACH,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AC,SAAS,EAAE,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;KACtF,CAAC;AACH,CAAC","sourcesContent":["import { createReadStream } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline\";\nimport { join } from \"path\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport { createLabelEntry, createSessionFilePath, createSessionHeader } from \"./session-manager-entries.ts\";\nimport { migrateToCurrentVersion, parseSessionEntries } from \"./session-manager-migrations.ts\";\nimport { getDefaultSessionDirPath } from \"./session-manager-paths.ts\";\nimport {\n\tensureDirectory,\n\thasConversationMessage,\n\tloadEntriesFromFile,\n\tserializeSessionEntries,\n\twriteSessionEntries,\n} from \"./session-manager-storage.ts\";\nimport type {\n\tFileEntry,\n\tLabelEntry,\n\tNewSessionOptions,\n\tSessionEntry,\n\tSessionHeader,\n\tSessionWorkflowMetadata,\n} from \"./session-manager-types.ts\";\nimport { assertValidSessionId, createSessionId, generateId } from \"./session-manager-validation.ts\";\n\nexport function createBackupSnapshot(\n\tsessionFile: string | undefined,\n\tentries: FileEntry[],\n\tlabel = \"compact\",\n): string | undefined {\n\tif (!sessionFile) return undefined;\n\tconst safeLabel =\n\t\tlabel\n\t\t\t.replace(/[^a-z0-9_-]/gi, \"-\")\n\t\t\t.replace(/-+/g, \"-\")\n\t\t\t.replace(/^-|-$/g, \"\") || \"backup\";\n\tconst timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n\tconst backupPath = `${sessionFile}.${timestamp}.${safeLabel}.bak`;\n\twriteSessionEntries(backupPath, entries);\n\treturn backupPath;\n}\n\nexport interface BranchedSessionStateInput {\n\tleafId: string;\n\tpersist: boolean;\n\tsessionDir: string;\n\tcwd: string;\n\tpreviousSessionFile: string | undefined;\n\tworkflow?: SessionWorkflowMetadata;\n\tpath: SessionEntry[];\n\tlabelsById: ReadonlyMap<string, string>;\n\tlabelTimestampsById: ReadonlyMap<string, string>;\n}\n\nexport interface BranchedSessionState {\n\tsessionId: string;\n\tsessionFile: string | undefined;\n\tfileEntries: FileEntry[];\n\tshouldRewriteFile: boolean;\n\tflushed?: boolean;\n}\n\nfunction collectLabelsForPath(\n\tpathEntryIds: ReadonlySet<string>,\n\tlabelsById: ReadonlyMap<string, string>,\n\tlabelTimestampsById: ReadonlyMap<string, string>,\n): Array<{ targetId: string; label: string; timestamp: string }> {\n\tconst labelsToWrite: Array<{ targetId: string; label: string; timestamp: string }> = [];\n\tfor (const [targetId, label] of labelsById) {\n\t\tif (pathEntryIds.has(targetId)) {\n\t\t\tlabelsToWrite.push({ targetId, label, timestamp: labelTimestampsById.get(targetId)! });\n\t\t}\n\t}\n\treturn labelsToWrite;\n}\n\nfunction buildPersistedLabelEntries(\n\tpathEntryIds: Set<string>,\n\tlastEntryId: string | null,\n\tlabelsToWrite: Array<{ targetId: string; label: string; timestamp: string }>,\n): LabelEntry[] {\n\tlet parentId = lastEntryId;\n\tconst labelEntries: LabelEntry[] = [];\n\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\tconst labelEntry = createLabelEntry(targetId, label, new Set(pathEntryIds), parentId, labelTimestamp);\n\t\tpathEntryIds.add(labelEntry.id);\n\t\tlabelEntries.push(labelEntry);\n\t\tparentId = labelEntry.id;\n\t}\n\treturn labelEntries;\n}\n\nfunction buildInMemoryLabelEntries(\n\tpathEntryIds: Set<string>,\n\tlastEntryId: string | null,\n\tlabelsToWrite: Array<{ targetId: string; label: string; timestamp: string }>,\n): LabelEntry[] {\n\tconst labelEntries: LabelEntry[] = [];\n\tlet parentId = lastEntryId;\n\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\tconst labelEntry: LabelEntry = {\n\t\t\ttype: \"label\",\n\t\t\tid: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),\n\t\t\tparentId,\n\t\t\ttimestamp: labelTimestamp,\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t};\n\t\tlabelEntries.push(labelEntry);\n\t\tparentId = labelEntry.id;\n\t}\n\treturn labelEntries;\n}\n\nexport function createBranchedSessionState(input: BranchedSessionStateInput): BranchedSessionState {\n\tif (input.path.length === 0) {\n\t\tthrow new Error(`Entry ${input.leafId} not found`);\n\t}\n\n\t// Filter labels out, re-chain the retained path, and translate compaction boundaries\n\t// that pointed at a removed label to the first retained entry after it.\n\tconst pathWithoutLabels: SessionEntry[] = [];\n\tconst replacementByLabelId = new Map<string, string>();\n\tconst pendingLabelIds: string[] = [];\n\tlet pathParentId: string | null = null;\n\tfor (const entry of input.path) {\n\t\tif (entry.type === \"label\") {\n\t\t\tpendingLabelIds.push(entry.id);\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const labelId of pendingLabelIds) replacementByLabelId.set(labelId, entry.id);\n\t\tpendingLabelIds.length = 0;\n\t\tpathWithoutLabels.push(\n\t\t\tentry.type === \"compaction\"\n\t\t\t\t? {\n\t\t\t\t\t\t...entry,\n\t\t\t\t\t\tparentId: pathParentId,\n\t\t\t\t\t\tfirstKeptEntryId:\n\t\t\t\t\t\t\tentry.firstKeptEntryId === null\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: (replacementByLabelId.get(entry.firstKeptEntryId) ?? entry.firstKeptEntryId),\n\t\t\t\t\t}\n\t\t\t\t: { ...entry, parentId: pathParentId },\n\t\t);\n\t\tpathParentId = entry.id;\n\t}\n\tconst newSessionId = createSessionId();\n\tconst timestamp = new Date().toISOString();\n\tconst newSessionFile = createSessionFilePath(input.sessionDir, timestamp, newSessionId);\n\tconst header: SessionHeader = createSessionHeader(\n\t\tnewSessionId,\n\t\tinput.cwd,\n\t\ttimestamp,\n\t\tinput.persist ? input.previousSessionFile : undefined,\n\t\tinput.workflow !== undefined,\n\t\tinput.workflow,\n\t);\n\n\t// Collect labels for entries in the path\n\tconst pathEntryIds = new Set(pathWithoutLabels.map((entry) => entry.id));\n\tconst labelsToWrite = collectLabelsForPath(pathEntryIds, input.labelsById, input.labelTimestampsById);\n\tconst lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\tconst labelEntries = input.persist\n\t\t? buildPersistedLabelEntries(pathEntryIds, lastEntryId, labelsToWrite)\n\t\t: buildInMemoryLabelEntries(pathEntryIds, lastEntryId, labelsToWrite);\n\tconst fileEntries: FileEntry[] = [header, ...pathWithoutLabels, ...labelEntries];\n\n\tif (!input.persist) {\n\t\treturn { sessionId: newSessionId, sessionFile: undefined, fileEntries, shouldRewriteFile: false };\n\t}\n\n\t// Use the same rule as appended entries: write now if the branched path already has a\n\t// conversation, otherwise let the first user or assistant message create the file.\n\tconst shouldRewriteFile = hasConversationMessage(fileEntries);\n\treturn {\n\t\tsessionId: newSessionId,\n\t\tsessionFile: newSessionFile,\n\t\tfileEntries,\n\t\tshouldRewriteFile,\n\t\tflushed: shouldRewriteFile,\n\t};\n}\n\nexport interface ForkedSessionFile {\n\tcwd: string;\n\tsessionDir: string;\n\tsessionFile: string;\n\tfileEntries: FileEntry[];\n}\n\nexport function forkSessionFromFile(\n\tsourcePath: string,\n\ttargetCwd: string,\n\tsessionDir?: string,\n\toptions?: NewSessionOptions,\n): ForkedSessionFile {\n\tconst sourceEntries = loadEntriesFromFile(resolvePath(sourcePath));\n\tconst forked = prepareFork(sourcePath, targetCwd, sourceEntries, sessionDir, options);\n\tensureDirectory(forked.sessionDir);\n\twriteSessionEntries(forked.sessionFile, forked.fileEntries);\n\treturn forked;\n}\n\nexport async function forkSessionFromFileAsync(\n\tsourcePath: string,\n\ttargetCwd: string,\n\tsessionDir?: string,\n\toptions?: NewSessionOptions,\n): Promise<ForkedSessionFile> {\n\tconst sourceEntries: FileEntry[] = [];\n\tconst input = createReadStream(resolvePath(sourcePath), { encoding: \"utf8\" });\n\tconst lines = createInterface({ input, crlfDelay: Infinity });\n\ttry {\n\t\tfor await (const line of lines) sourceEntries.push(...parseSessionEntries(line));\n\t} finally {\n\t\tlines.close();\n\t\tinput.destroy();\n\t}\n\tconst forked = prepareFork(sourcePath, targetCwd, sourceEntries, sessionDir, options);\n\tawait mkdir(forked.sessionDir, { recursive: true });\n\tawait writeFile(forked.sessionFile, serializeSessionEntries(forked.fileEntries));\n\treturn forked;\n}\n\nfunction prepareFork(\n\tsourcePath: string,\n\ttargetCwd: string,\n\tsourceEntries: FileEntry[],\n\tsessionDir?: string,\n\toptions?: NewSessionOptions,\n): ForkedSessionFile {\n\tconst resolvedSourcePath = resolvePath(sourcePath);\n\tconst resolvedTargetCwd = resolvePath(targetCwd);\n\tif (sourceEntries.length === 0) {\n\t\tthrow new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);\n\t}\n\tconst sourceHeader = sourceEntries[0];\n\tif (sourceHeader.type !== \"session\" || typeof sourceHeader.id !== \"string\") {\n\t\tthrow new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);\n\t}\n\tmigrateToCurrentVersion(sourceEntries);\n\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDirPath(resolvedTargetCwd);\n\tif (options?.id !== undefined) assertValidSessionId(options.id);\n\tconst newSessionId = options?.id ?? createSessionId();\n\tconst timestamp = new Date().toISOString();\n\tconst newSessionFile = join(dir, `${timestamp.replace(/[:.]/g, \"-\")}_${newSessionId}.jsonl`);\n\tconst newHeader = createSessionHeader(\n\t\tnewSessionId,\n\t\tresolvedTargetCwd,\n\t\ttimestamp,\n\t\tresolvedSourcePath,\n\t\toptions?.internal,\n\t\toptions?.workflow,\n\t);\n\treturn {\n\t\tcwd: resolvedTargetCwd,\n\t\tsessionDir: dir,\n\t\tsessionFile: newSessionFile,\n\t\tfileEntries: [newHeader, ...sourceEntries.filter((entry) => entry.type !== \"session\")],\n\t};\n}\n"]}
@@ -113,6 +113,7 @@ export declare class SessionManager {
113
113
  static inMemory(cwd?: string, options?: NewSessionOptions, entries?: FileEntry[]): SessionManager;
114
114
  /** Fork a session from another project directory into the current project. */
115
115
  static forkFrom(sourcePath: string, targetCwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager;
116
+ static forkFromAsync(sourcePath: string, targetCwd: string, sessionDir?: string, options?: NewSessionOptions): Promise<SessionManager>;
116
117
  /** Find an exact, non-internal session ID by reading headers, not transcripts. */
117
118
  static findById(cwd: string, id: string, sessionDir?: string): string | undefined;
118
119
  /** List sessions for a directory. Internal (workflow) sessions are excluded unless `includeInternal: true`. */
@@ -1 +1 @@
1
- {"version":3,"file":"session-manager-core.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-core.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAKvF,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAClF,OAAO,KAAK,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AA0CzE,OAAO,KAAK,EAEX,gBAAgB,EAChB,SAAS,EACT,iBAAiB,EACjB,cAAc,EACd,YAAY,EACZ,aAAa,EACb,WAAW,EACX,mBAAmB,EACnB,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,uBAAuB,EACvB,UAAU,EACV,MAAM,4BAA4B,CAAC;AAGpC,qfAAqf;AACrf,qBAAa,cAAc;IAC1B,OAAO,CAAC,SAAS,CAAc;IAC/B,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,OAAO,CAAU;IACzB,OAAO,CAAC,OAAO,CAAkB;IACjC,OAAO,CAAC,WAAW,CAAmB;IACtC,OAAO,CAAC,IAAI,CAAwC;IACpD,OAAO,CAAC,UAAU,CAAkC;IACpD,OAAO,CAAC,mBAAmB,CAAkC;IAC7D,OAAO,CAAC,MAAM,CAAuB;IAErC,OAAO,eAsBN;IAED,OAAO,C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EAAE,MAAM,EACnB,UAAU,CAAC,EAAE,mBAAmB,EAChC,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,WAAW,GACzE,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;CAiB1B"}
1
+ {"version":3,"file":"session-manager-core.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-core.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAKvF,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAClF,OAAO,KAAK,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AA+CzE,OAAO,KAAK,EAEX,gBAAgB,EAChB,SAAS,EACT,iBAAiB,EACjB,cAAc,EACd,YAAY,EACZ,aAAa,EACb,WAAW,EACX,mBAAmB,EACnB,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,uBAAuB,EACvB,UAAU,EACV,MAAM,4BAA4B,CAAC;AAGpC,qfAAqf;AACrf,qBAAa,cAAc;IAC1B,OAAO,CAAC,SAAS,CAAc;IAC/B,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,OAAO,CAAU;IACzB,OAAO,CAAC,OAAO,CAAkB;IACjC,OAAO,CAAC,WAAW,CAAmB;IACtC,OAAO,CAAC,IAAI,CAAwC;IACpD,OAAO,CAAC,UAAU,CAAkC;IACpD,OAAO,CAAC,mBAAmB,CAAkC;IAC7D,OAAO,CAAC,MAAM,CAAuB;IAErC,OAAO,eAsBN;IAED,OAAO,CAAC,YAAY;IAepB,yEAAyE;IACzE,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAExC;IAED,OAAO,CAAC,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O,CAAC,WAAW,EAAE,CAAC,CAAC;IACrG,OAAa,OAAO,CACnB,UAAU,CAAC,EAAE,MAAM,EACnB,UAAU,CAAC,EAAE,mBAAmB,EAChC,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,WAAW,GACzE,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;CAiB1B"}
@@ -3,7 +3,7 @@ import { existsSync, readdirSync, statSync } from "fs";
3
3
  import { join, resolve } from "path";
4
4
  import { APP_TITLE } from "../config.js";
5
5
  import { normalizePath, resolvePath } from "../utils/paths.js";
6
- import { createBackupSnapshot, createBranchedSessionState, forkSessionFromFile } from "./session-manager-archive.js";
6
+ import { createBackupSnapshot, createBranchedSessionState, forkSessionFromFile, forkSessionFromFileAsync, } from "./session-manager-archive.js";
7
7
  import { classifiedWorkflowMetadata, validSessionWorkflowMetadata } from "./session-manager-classification.js";
8
8
  import { createBranchSummaryEntry, createCompactionEntry, createContextEditEntry, createCustomEntry, createCustomMessageEntry, createLabelEntry, createMessageEntry, createModelChangeEntry, createSessionFilePath, createSessionHeader, createSessionInfoEntry, createSessionSummaryEntry, createThinkingLevelChangeEntry, getEntriesWithoutHeader, getLatestSessionName, } from "./session-manager-entries.js";
9
9
  import { buildContextEntries, buildSessionIndex, buildSessionProjection, buildSessionTree, getBranchPath, } from "./session-manager-history.js";
@@ -29,7 +29,7 @@ export class SessionManager {
29
29
  this.cwd = resolvePath(cwd);
30
30
  this.sessionDir = normalizePath(sessionDir);
31
31
  this.persist = persist;
32
- if (persist && this.sessionDir) {
32
+ if (persist && this.sessionDir && !preloadedFileEntries?.length) {
33
33
  ensureDirectory(this.sessionDir);
34
34
  }
35
35
  if (sessionFile) {
@@ -63,7 +63,7 @@ export class SessionManager {
63
63
  }
64
64
  _setSessionFile(sessionFile, preloadedFileEntries) {
65
65
  this.sessionFile = resolvePath(sessionFile);
66
- if (existsSync(this.sessionFile)) {
66
+ if (preloadedFileEntries?.length || existsSync(this.sessionFile)) {
67
67
  this.fileEntries = preloadedFileEntries ?? loadEntriesFromFile(this.sessionFile);
68
68
  // If file was empty, initialize it with a valid session header. If it was non-empty but did not parse as a session, fail without modifying it.
69
69
  if (this.fileEntries.length === 0) {
@@ -437,7 +437,7 @@ export class SessionManager {
437
437
  const header = entries.find((entry) => entry.type === "session");
438
438
  const cwd = cwdOverride ?? header?.cwd ?? process.cwd();
439
439
  const dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, "..");
440
- return new SessionManager(cwd, dir, resolvedPath, true, undefined, entries);
440
+ return new SessionManager(cwd, dir, resolvedPath, true);
441
441
  }
442
442
  /** Continue the most recent session (skips internal workflow sessions unless `includeInternal: true`). */
443
443
  static continueRecent(cwd, sessionDir, options) {
@@ -455,6 +455,10 @@ export class SessionManager {
455
455
  const forked = forkSessionFromFile(sourcePath, targetCwd, sessionDir, options);
456
456
  return new SessionManager(forked.cwd, forked.sessionDir, forked.sessionFile, true);
457
457
  }
458
+ static async forkFromAsync(sourcePath, targetCwd, sessionDir, options) {
459
+ const forked = await forkSessionFromFileAsync(sourcePath, targetCwd, sessionDir, options);
460
+ return new SessionManager(forked.cwd, forked.sessionDir, forked.sessionFile, true, undefined, forked.fileEntries);
461
+ }
458
462
  /** Find an exact, non-internal session ID by reading headers, not transcripts. */
459
463
  static findById(cwd, id, sessionDir) {
460
464
  const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);