experimental-ash 0.24.2 → 0.25.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 (258) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/docs/public/typescript-api.md +0 -12
  3. package/dist/src/channel/adapter.d.ts +5 -18
  4. package/dist/src/channel/adapter.js +2 -8
  5. package/dist/src/channel/cross-channel-receive.d.ts +10 -1
  6. package/dist/src/channel/cross-channel-receive.js +21 -3
  7. package/dist/src/channel/routes.d.ts +2 -1
  8. package/dist/src/channel/routes.js +6 -3
  9. package/dist/src/channel/schedule.js +2 -2
  10. package/dist/src/channel/types.d.ts +1 -1
  11. package/dist/src/chunks/{client-DLHAGI2g.js → client-BShLWzR6.js} +3 -3
  12. package/dist/src/chunks/compile-agent-CyP6FrL8.js +5 -0
  13. package/dist/src/chunks/dev-authored-source-watcher-DIWfVUsu.js +1 -0
  14. package/dist/src/chunks/host-BxT35q6K.js +70 -0
  15. package/dist/src/chunks/paths-B2hLA0Fn.js +85 -0
  16. package/dist/src/chunks/{token-D98SQdvs.js → token-BOkIxJeV.js} +1 -1
  17. package/dist/src/chunks/types-CjIyrcYo.js +1 -0
  18. package/dist/src/cli/commands/info.js +1 -1
  19. package/dist/src/cli/dev/environment.d.ts +0 -5
  20. package/dist/src/cli/dev/environment.js +1 -1
  21. package/dist/src/cli/dev/repl.d.ts +1 -1
  22. package/dist/src/cli/dev/repl.js +3 -3
  23. package/dist/src/cli/run.d.ts +0 -1
  24. package/dist/src/cli/run.js +2 -2
  25. package/dist/src/client/index.d.ts +1 -1
  26. package/dist/src/client/message-reducer.js +13 -25
  27. package/dist/src/client/message-response.d.ts +2 -1
  28. package/dist/src/client/open-stream.d.ts +3 -3
  29. package/dist/src/client/open-stream.js +1 -2
  30. package/dist/src/client/session.d.ts +2 -1
  31. package/dist/src/client/session.js +0 -3
  32. package/dist/src/client/types.d.ts +3 -2
  33. package/dist/src/compiler/artifacts.d.ts +7 -10
  34. package/dist/src/compiler/artifacts.js +3 -3
  35. package/dist/src/compiler/manifest.d.ts +6 -15
  36. package/dist/src/compiler/manifest.js +3 -3
  37. package/dist/src/compiler/normalize-agent-config.js +12 -10
  38. package/dist/src/compiler/normalize-manifest.js +3 -2
  39. package/dist/src/context/container.d.ts +1 -16
  40. package/dist/src/context/container.js +1 -24
  41. package/dist/src/context/hook-lifecycle.d.ts +2 -7
  42. package/dist/src/context/hook-lifecycle.js +0 -6
  43. package/dist/src/context/provider.d.ts +1 -11
  44. package/dist/src/context/providers/sandbox.js +4 -1
  45. package/dist/src/context/run-step.d.ts +2 -4
  46. package/dist/src/context/run-step.js +4 -17
  47. package/dist/src/context/seed-keys.d.ts +1 -1
  48. package/dist/src/discover/connections.d.ts +2 -1
  49. package/dist/src/discover/diagnostics.d.ts +0 -8
  50. package/dist/src/discover/diagnostics.js +4 -16
  51. package/dist/src/discover/discover-agent.d.ts +3 -13
  52. package/dist/src/discover/discover-agent.js +1 -11
  53. package/dist/src/discover/discover-subagent.d.ts +3 -2
  54. package/dist/src/discover/discover-subagent.js +1 -1
  55. package/dist/src/discover/filesystem.d.ts +0 -37
  56. package/dist/src/discover/filesystem.js +0 -115
  57. package/dist/src/discover/grammar.d.ts +10 -20
  58. package/dist/src/discover/grammar.js +11 -33
  59. package/dist/src/discover/lib.d.ts +3 -2
  60. package/dist/src/discover/manifest.d.ts +3 -3
  61. package/dist/src/discover/markdown.d.ts +2 -1
  62. package/dist/src/discover/sandbox.d.ts +2 -1
  63. package/dist/src/discover/schedules.d.ts +3 -2
  64. package/dist/src/discover/schedules.js +1 -1
  65. package/dist/src/discover/skills.d.ts +3 -2
  66. package/dist/src/discover/skills.js +1 -1
  67. package/dist/src/discover/slots.d.ts +3 -2
  68. package/dist/src/evals/cli/eval.d.ts +0 -6
  69. package/dist/src/evals/cli/eval.js +1 -1
  70. package/dist/src/evals/loaders/index.d.ts +2 -22
  71. package/dist/src/evals/loaders/index.js +1 -1
  72. package/dist/src/evals/reporters/index.d.ts +2 -14
  73. package/dist/src/evals/reporters/index.js +1 -1
  74. package/dist/src/evals/runner/discover.d.ts +0 -6
  75. package/dist/src/evals/runner/discover.js +1 -1
  76. package/dist/src/evals/runner/execute-case.d.ts +2 -1
  77. package/dist/src/evals/runner/execute-suite.d.ts +2 -1
  78. package/dist/src/evals/runner/reporters/braintrust.js +1 -1
  79. package/dist/src/evals/runner/resolve-git-metadata.d.ts +3 -3
  80. package/dist/src/evals/scorers/autoevals-client.d.ts +2 -2
  81. package/dist/src/execution/await-authorization-orchestrator.d.ts +0 -2
  82. package/dist/src/execution/await-authorization-orchestrator.js +11 -19
  83. package/dist/src/execution/connection-auth-steps.d.ts +1 -5
  84. package/dist/src/execution/connection-auth-steps.js +5 -9
  85. package/dist/src/execution/node-step.d.ts +1 -1
  86. package/dist/src/execution/skills/instructions.d.ts +2 -1
  87. package/dist/src/execution/subagent-hitl-proxy.d.ts +1 -1
  88. package/dist/src/execution/subagent-tool.d.ts +0 -8
  89. package/dist/src/execution/subagent-tool.js +9 -16
  90. package/dist/src/execution/tool-compaction.js +0 -2
  91. package/dist/src/execution/turn-workflow.d.ts +1 -1
  92. package/dist/src/execution/turn-workflow.js +2 -3
  93. package/dist/src/execution/web-fetch/tool.js +1 -1
  94. package/dist/src/execution/workflow-steps.d.ts +15 -1
  95. package/dist/src/execution/workflow-steps.js +8 -18
  96. package/dist/src/harness/action-result-helpers.d.ts +0 -12
  97. package/dist/src/harness/action-result-helpers.js +1 -1
  98. package/dist/src/harness/emission.d.ts +2 -2
  99. package/dist/src/harness/execute-tool.d.ts +2 -1
  100. package/dist/src/harness/input-requests.d.ts +2 -1
  101. package/dist/src/harness/prompt-cache.d.ts +1 -9
  102. package/dist/src/harness/prompt-cache.js +0 -12
  103. package/dist/src/harness/runtime-actions.d.ts +2 -11
  104. package/dist/src/harness/runtime-actions.js +1 -1
  105. package/dist/src/harness/step-hooks.d.ts +3 -2
  106. package/dist/src/harness/step-hooks.js +3 -7
  107. package/dist/src/harness/tool-loop.js +0 -2
  108. package/dist/src/harness/types.d.ts +1 -1
  109. package/dist/src/internal/application/package.js +2 -2
  110. package/dist/src/internal/application/runtime-compiled-artifacts-source.js +0 -1
  111. package/dist/src/internal/attachments/errors.d.ts +8 -2
  112. package/dist/src/internal/attachments/url-refs.d.ts +0 -1
  113. package/dist/src/internal/attachments/url-refs.js +1 -1
  114. package/dist/src/internal/authored-definition/channel.d.ts +0 -5
  115. package/dist/src/internal/authored-definition/channel.js +1 -10
  116. package/dist/src/internal/authored-definition/sandbox.d.ts +2 -1
  117. package/dist/src/internal/authored-definition/schema-backed.d.ts +3 -2
  118. package/dist/src/internal/authored-module-loader.d.ts +0 -6
  119. package/dist/src/internal/authored-module-loader.js +0 -9
  120. package/dist/src/internal/authored-module.d.ts +0 -4
  121. package/dist/src/internal/authored-module.js +0 -10
  122. package/dist/src/internal/bundler/nitro-rolldown.d.ts +2 -10
  123. package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
  124. package/dist/src/{public → internal}/helpers/markdown.d.ts +2 -23
  125. package/dist/src/{public → internal}/helpers/markdown.js +1 -1
  126. package/dist/src/internal/logging.d.ts +2 -8
  127. package/dist/src/internal/nitro/host/build-vercel-agent-summary.d.ts +1 -1
  128. package/dist/src/internal/nitro/host/build-vercel-agent-summary.js +1 -1
  129. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  130. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +2 -2
  131. package/dist/src/internal/nitro/routes/channel-dispatch.js +2 -2
  132. package/dist/src/internal/nitro/routes/runtime-artifacts.js +0 -1
  133. package/dist/src/internal/node-esm-compat-banner.d.ts +1 -1
  134. package/dist/src/internal/runtime-registry.d.ts +2 -1
  135. package/dist/src/{protocol → internal}/vercel-agent-summary.d.ts +1 -1
  136. package/dist/src/protocol/message.d.ts +0 -34
  137. package/dist/src/protocol/message.js +0 -30
  138. package/dist/src/public/channels/index.d.ts +1 -1
  139. package/dist/src/public/channels/index.js +1 -1
  140. package/dist/src/public/channels/slack/api.d.ts +1 -7
  141. package/dist/src/public/channels/slack/api.js +1 -1
  142. package/dist/src/public/channels/slack/connections.d.ts +2 -6
  143. package/dist/src/public/channels/slack/hitl.d.ts +3 -2
  144. package/dist/src/public/channels/slack/inbound.d.ts +0 -35
  145. package/dist/src/public/definitions/channel.d.ts +2 -2
  146. package/dist/src/public/definitions/channel.js +1 -1
  147. package/dist/src/public/definitions/defineChannel.d.ts +1 -1
  148. package/dist/src/public/definitions/defineChannel.js +1 -1
  149. package/dist/src/public/definitions/instructions.d.ts +0 -11
  150. package/dist/src/public/definitions/instructions.js +0 -5
  151. package/dist/src/public/definitions/tool.d.ts +3 -7
  152. package/dist/src/public/definitions/tool.js +1 -1
  153. package/dist/src/public/instructions/index.d.ts +1 -5
  154. package/dist/src/public/instructions/index.js +1 -3
  155. package/dist/src/public/tool-result-narrowing.d.ts +2 -1
  156. package/dist/src/react/use-ash-agent.d.ts +2 -1
  157. package/dist/src/react/use-ash-agent.js +1 -5
  158. package/dist/src/runtime/actions/types.d.ts +8 -50
  159. package/dist/src/runtime/actions/types.js +5 -21
  160. package/dist/src/runtime/agent/bootstrap-model-utils.d.ts +2 -1
  161. package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
  162. package/dist/src/runtime/channels/registry.js +3 -8
  163. package/dist/src/runtime/compiled-artifacts-source.d.ts +4 -11
  164. package/dist/src/runtime/compiled-artifacts-source.js +3 -7
  165. package/dist/src/runtime/connections/authorization-tokens.d.ts +1 -14
  166. package/dist/src/runtime/connections/authorization-tokens.js +2 -28
  167. package/dist/src/runtime/connections/principal-context.d.ts +3 -2
  168. package/dist/src/runtime/connections/validate-authorization.d.ts +0 -11
  169. package/dist/src/runtime/connections/validate-authorization.js +0 -16
  170. package/dist/src/runtime/framework-channels/index.d.ts +0 -1
  171. package/dist/src/runtime/framework-channels/index.js +1 -1
  172. package/dist/src/runtime/framework-tools/connection-search.d.ts +0 -46
  173. package/dist/src/runtime/framework-tools/connection-search.js +3 -78
  174. package/dist/src/runtime/framework-tools/connection-tools.d.ts +3 -6
  175. package/dist/src/runtime/framework-tools/connection-tools.js +6 -13
  176. package/dist/src/runtime/framework-tools/index.d.ts +2 -1
  177. package/dist/src/runtime/framework-tools/index.js +2 -1
  178. package/dist/src/runtime/framework-tools/skill.d.ts +0 -13
  179. package/dist/src/runtime/framework-tools/skill.js +1 -1
  180. package/dist/src/runtime/governance/auth/token-claims.d.ts +1 -16
  181. package/dist/src/runtime/governance/auth/token-claims.js +3 -3
  182. package/dist/src/runtime/governance/auth/types.d.ts +0 -4
  183. package/dist/src/runtime/governance/network/ip-allow-list.d.ts +0 -17
  184. package/dist/src/runtime/governance/network/ip-allow-list.js +0 -39
  185. package/dist/src/runtime/hooks/registry.d.ts +7 -4
  186. package/dist/src/runtime/hooks/registry.js +4 -2
  187. package/dist/src/runtime/loaders/bundled-artifacts.d.ts +0 -5
  188. package/dist/src/runtime/loaders/bundled-artifacts.js +0 -7
  189. package/dist/src/runtime/loaders/compile-metadata.d.ts +3 -10
  190. package/dist/src/runtime/loaders/compile-metadata.js +6 -8
  191. package/dist/src/runtime/loaders/manifest.d.ts +2 -2
  192. package/dist/src/runtime/loaders/manifest.js +4 -5
  193. package/dist/src/runtime/loaders/module-map.d.ts +2 -2
  194. package/dist/src/runtime/loaders/module-map.js +3 -4
  195. package/dist/src/runtime/prompt/compose.d.ts +2 -1
  196. package/dist/src/runtime/resolve-agent-graph.d.ts +2 -15
  197. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  198. package/dist/src/runtime/sandbox/keys.d.ts +2 -1
  199. package/dist/src/runtime/sandbox/registry.d.ts +3 -3
  200. package/dist/src/runtime/schedules/resolve-schedule.d.ts +3 -12
  201. package/dist/src/runtime/schedules/resolve-schedule.js +1 -1
  202. package/dist/src/runtime/sessions/auth.d.ts +2 -13
  203. package/dist/src/runtime/sessions/auth.js +1 -11
  204. package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
  205. package/dist/src/runtime/sessions/runtime-session.d.ts +0 -6
  206. package/dist/src/runtime/sessions/runtime-session.js +0 -13
  207. package/dist/src/runtime/sessions/turn.d.ts +2 -2
  208. package/dist/src/runtime/subagents/registry.d.ts +2 -5
  209. package/dist/src/runtime/subagents/registry.js +0 -6
  210. package/dist/src/runtime/tools/registry.d.ts +2 -1
  211. package/dist/src/runtime/tools/registry.js +1 -4
  212. package/dist/src/runtime/types.d.ts +4 -3
  213. package/dist/src/runtime/workspace/seed-files.d.ts +2 -1
  214. package/dist/src/services/dev-client/request-headers.d.ts +37 -8
  215. package/dist/src/services/dev-client/request-headers.js +71 -46
  216. package/dist/src/services/dev-client/stream.d.ts +0 -19
  217. package/dist/src/services/dev-client/stream.js +0 -37
  218. package/dist/src/services/dev-client/url.d.ts +3 -7
  219. package/dist/src/services/dev-client/url.js +4 -10
  220. package/dist/src/services/dev-client.d.ts +0 -12
  221. package/dist/src/services/dev-client.js +6 -92
  222. package/dist/src/shared/agent-definition.d.ts +1 -1
  223. package/dist/src/shared/json.d.ts +0 -4
  224. package/dist/src/shared/json.js +0 -38
  225. package/dist/src/shared/skill-definition.d.ts +0 -2
  226. package/package.json +1 -6
  227. package/dist/src/chunks/dev-authored-source-watcher-CBID_Dwh.js +0 -1
  228. package/dist/src/chunks/host-zBy9FyyX.js +0 -70
  229. package/dist/src/chunks/package-HUaeub_D.js +0 -1
  230. package/dist/src/chunks/paths-CebY5GCi.js +0 -89
  231. package/dist/src/chunks/types-DDA2QUED.js +0 -1
  232. package/dist/src/compiler/resource-files.d.ts +0 -19
  233. package/dist/src/compiler/resource-files.js +0 -28
  234. package/dist/src/execution/subagent-invocation.d.ts +0 -19
  235. package/dist/src/execution/subagent-invocation.js +0 -17
  236. package/dist/src/execution/task-mode.d.ts +0 -9
  237. package/dist/src/execution/task-mode.js +0 -12
  238. package/dist/src/execution/types.d.ts +0 -20
  239. package/dist/src/execution/types.js +0 -1
  240. package/dist/src/internal/logical-paths.d.ts +0 -13
  241. package/dist/src/internal/logical-paths.js +0 -25
  242. package/dist/src/runtime/sessions/messages.d.ts +0 -140
  243. package/dist/src/runtime/sessions/messages.js +0 -170
  244. package/dist/src/runtime/standard-schema.d.ts +0 -27
  245. package/dist/src/runtime/standard-schema.js +0 -64
  246. package/dist/src/services/dev-client/live-stream.d.ts +0 -35
  247. package/dist/src/services/dev-client/live-stream.js +0 -157
  248. package/dist/src/services/dev-client/send-message.d.ts +0 -24
  249. package/dist/src/services/dev-client/send-message.js +0 -185
  250. package/dist/src/services/dev-client/session.d.ts +0 -54
  251. package/dist/src/services/dev-client/session.js +0 -52
  252. package/dist/src/services/host.d.ts +0 -14
  253. package/dist/src/services/host.js +0 -13
  254. /package/dist/src/{package-name.d.ts → internal/package-name.d.ts} +0 -0
  255. /package/dist/src/{package-name.js → internal/package-name.js} +0 -0
  256. /package/dist/src/{protocol → internal}/vercel-agent-summary.js +0 -0
  257. /package/dist/src/{run-mode.d.ts → shared/run-mode.d.ts} +0 -0
  258. /package/dist/src/{run-mode.js → shared/run-mode.js} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # experimental-ash
2
2
 
3
+ ## 0.25.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 6bc0e26: Remove non-interactive connection auth drain mechanism. Missing credentials on API-key-based connections now surface as tool execution errors instead of silent retryable results.
8
+
9
+ ## 0.25.0
10
+
11
+ ### Minor Changes
12
+
13
+ - f78e0fa: Remove the deprecated `experimental-ash/system` package entry along with the
14
+ `defineSystem` function and `SystemDefinition` type from
15
+ `experimental-ash/instructions`. The authored file slot was renamed from
16
+ `system.{md,ts,...}` to `instructions.{md,ts,...}` in an earlier release;
17
+ authors who still import from `experimental-ash/system` or call
18
+ `defineSystem(...)` should migrate to `experimental-ash/instructions` and
19
+ `defineInstructions(...)`.
20
+
3
21
  ## 0.24.2
4
22
 
5
23
  ### Patch Changes
@@ -123,18 +123,6 @@ sessions must finish inside the current invocation.
123
123
 
124
124
  These helpers only work inside active authored runtime execution.
125
125
 
126
- ## Markdown Helpers
127
-
128
- Ash also exports helpers for turning markdown into the same shapes as module-authored definitions:
129
-
130
- - `parseMarkdownDocument(markdown)`
131
- - `lowerInstructionsMarkdown(markdown, options?)`
132
- - `lowerSkillMarkdown(markdown, options?)` -- supports both packaged (`SKILL.md` with frontmatter) and flat (`<name>.md`) skill files; pass `options.name` for flat mode
133
- - `lowerScheduleMarkdown(markdown)` -- parses a `schedules/<name>.md` file (frontmatter `cron:` plus the body as the prompt) into a `ScheduleDefinition`
134
-
135
- These are most useful if you are building higher-level authoring tools or tests around Ash's public
136
- shapes.
137
-
138
126
  ## Common Import Patterns
139
127
 
140
128
  ### Agent Config
@@ -1,5 +1,4 @@
1
1
  import type { ContextAccessor } from "#context/key.js";
2
- import type { ContextProvider } from "#context/provider.js";
3
2
  import type { StepInput } from "#harness/types.js";
4
3
  import type { HandleMessageStreamEvent } from "#protocol/message.js";
5
4
  import type { SessionHandle } from "#channel/session.js";
@@ -85,13 +84,13 @@ export type ChannelAdapter<TCtx extends ChannelAdapterContext<any> = ChannelAdap
85
84
  * Stable durable identifier for serialization across step boundaries.
86
85
  * Must be unique across all adapters visible to one runtime bundle.
87
86
  *
88
- * Optional — defaults to {@link HTTP_ADAPTER_KIND} (`"http"`) for the
89
- * canonical session channel and every behaviorless authored channel,
90
- * or is derived from the route file path as `channel:<name>` once
87
+ * Defaults to {@link HTTP_ADAPTER_KIND} (`"http"`) for the canonical
88
+ * session channel and every behaviorless authored channel, or is derived
89
+ * from the route file path as `channel:<name>` once
91
90
  * `runtime/resolve-channel.ts` rewrites authored adapters that carry
92
91
  * behavior.
93
92
  */
94
- readonly kind?: string;
93
+ readonly kind: string;
95
94
  /**
96
95
  * Initial state shape. Auto-serialized at step boundaries via JSON
97
96
  * snapshot. On rehydration, the runtime restores the serialized state
@@ -105,14 +104,6 @@ export type ChannelAdapter<TCtx extends ChannelAdapterContext<any> = ChannelAdap
105
104
  * return void to use the default payload projection.
106
105
  */
107
106
  deliver?(payload: DeliverPayload, ctx: TCtx): StepInput | void | Promise<StepInput | void>;
108
- /**
109
- * Optional per-step virtual providers attached to this adapter.
110
- *
111
- * The runtime rebuilds these providers after deliver on every step for
112
- * sessions using this adapter. Replaces the static `contextProviders`
113
- * field on the old `ChannelClass` interface.
114
- */
115
- readonly contextProviders?: readonly ContextProvider<unknown>[];
116
107
  /**
117
108
  * Optional factory that builds the adapter context for this adapter.
118
109
  *
@@ -142,13 +133,9 @@ export type ChannelAdapter<TCtx extends ChannelAdapterContext<any> = ChannelAdap
142
133
  */
143
134
  export declare function defaultDeliverResult(payload: DeliverPayload): StepInput | undefined;
144
135
  /**
145
- * Returns the durable kind for an adapter, falling back to `"unknown"`.
136
+ * Returns the durable kind for an adapter.
146
137
  */
147
138
  export declare function getAdapterKind(adapter: ChannelAdapter): string;
148
- /**
149
- * Returns the adapter's context providers, defaulting to an empty array.
150
- */
151
- export declare function getAdapterContextProviders(adapter: ChannelAdapter): readonly ContextProvider<unknown>[];
152
139
  /**
153
140
  * Calls an adapter's event handler for a given event. Returns the event
154
141
  * unchanged (adapters don't transform events — they perform side effects).
@@ -31,16 +31,10 @@ export function defaultDeliverResult(payload) {
31
31
  return undefined;
32
32
  }
33
33
  /**
34
- * Returns the durable kind for an adapter, falling back to `"unknown"`.
34
+ * Returns the durable kind for an adapter.
35
35
  */
36
36
  export function getAdapterKind(adapter) {
37
- return adapter.kind ?? "unknown";
38
- }
39
- /**
40
- * Returns the adapter's context providers, defaulting to an empty array.
41
- */
42
- export function getAdapterContextProviders(adapter) {
43
- return adapter.contextProviders ?? [];
37
+ return adapter.kind;
44
38
  }
45
39
  /**
46
40
  * Calls an adapter's event handler for a given event. Returns the event
@@ -4,6 +4,7 @@ import { type CompiledChannel } from "#channel/compiled-channel.js";
4
4
  import type { InferReceiveArgs } from "#channel/receive-args.js";
5
5
  import type { Session } from "#channel/session.js";
6
6
  import type { Runtime, SessionAuthContext } from "#channel/types.js";
7
+ import type { ResolvedChannelDefinition } from "#runtime/types.js";
7
8
  /**
8
9
  * Options accepted by {@link CrossChannelReceiveFn}. Mirrors the input
9
10
  * argument of a channel's authored `receive(input, { send })` hook —
@@ -29,10 +30,18 @@ export type CrossChannelReceiveFn = <TChannel>(channel: TChannel, options: Cross
29
30
  */
30
31
  export interface CrossChannelTarget {
31
32
  readonly name: string;
32
- readonly definition?: CompiledChannel;
33
+ readonly definition: CompiledChannel;
33
34
  readonly receive?: CompiledChannel["receive"];
34
35
  readonly adapter?: ChannelAdapter;
35
36
  }
37
+ /**
38
+ * Projects an agent's resolved channels into the receiver-input shape.
39
+ *
40
+ * Framework-internal fetch-only channels carry no `definition` reference
41
+ * and are filtered out at this boundary — only authored channels backed
42
+ * by a `defineChannel` value can be receive targets.
43
+ */
44
+ export declare function toCrossChannelTargets(channels: readonly ResolvedChannelDefinition[]): readonly CrossChannelTarget[];
36
45
  /**
37
46
  * Builds the `args.receive` closure used by every route handler. The
38
47
  * closure resolves the target channel by reference identity against
@@ -1,5 +1,24 @@
1
1
  import { isCompiledChannel } from "#channel/compiled-channel.js";
2
2
  import { createSendFn } from "#channel/send.js";
3
+ /**
4
+ * Projects an agent's resolved channels into the receiver-input shape.
5
+ *
6
+ * Framework-internal fetch-only channels carry no `definition` reference
7
+ * and are filtered out at this boundary — only authored channels backed
8
+ * by a `defineChannel` value can be receive targets.
9
+ */
10
+ export function toCrossChannelTargets(channels) {
11
+ return channels.flatMap((channel) => channel.definition === undefined
12
+ ? []
13
+ : [
14
+ {
15
+ name: channel.name,
16
+ definition: channel.definition,
17
+ receive: channel.receive,
18
+ adapter: channel.adapter,
19
+ },
20
+ ]);
21
+ }
3
22
  /**
4
23
  * Builds the `args.receive` closure used by every route handler. The
5
24
  * closure resolves the target channel by reference identity against
@@ -41,7 +60,7 @@ export async function invokeChannelReceive(args) {
41
60
  }
42
61
  function resolveTargetByReference(ref, channels) {
43
62
  for (const channel of channels) {
44
- if (channel.definition !== undefined && channel.definition === ref) {
63
+ if (channel.definition === ref) {
45
64
  return channel;
46
65
  }
47
66
  }
@@ -63,8 +82,7 @@ function resolveTargetByRouteFingerprint(ref, channels) {
63
82
  }
64
83
  const matches = new Map();
65
84
  for (const channel of channels) {
66
- const definition = channel.definition;
67
- if (definition === undefined || createRouteFingerprint(definition) !== refFingerprint) {
85
+ if (createRouteFingerprint(channel.definition) !== refFingerprint) {
68
86
  continue;
69
87
  }
70
88
  matches.set(channel.name, channel);
@@ -53,7 +53,8 @@ export interface RouteDefinition<TState = undefined> {
53
53
  readonly path: string;
54
54
  readonly handler: RouteHandler<TState>;
55
55
  }
56
- export declare function POST<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
57
56
  export declare function GET<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
57
+ export declare function POST<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
58
58
  export declare function PUT<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
59
+ export declare function PATCH<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
59
60
  export declare function DELETE<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
@@ -1,12 +1,15 @@
1
- export function POST(path, handler) {
2
- return { method: "POST", path, handler };
3
- }
4
1
  export function GET(path, handler) {
5
2
  return { method: "GET", path, handler };
6
3
  }
4
+ export function POST(path, handler) {
5
+ return { method: "POST", path, handler };
6
+ }
7
7
  export function PUT(path, handler) {
8
8
  return { method: "PUT", path, handler };
9
9
  }
10
+ export function PATCH(path, handler) {
11
+ return { method: "PATCH", path, handler };
12
+ }
10
13
  export function DELETE(path, handler) {
11
14
  return { method: "DELETE", path, handler };
12
15
  }
@@ -1,4 +1,4 @@
1
- import { createCrossChannelReceiveFn } from "#channel/cross-channel-receive.js";
1
+ import { createCrossChannelReceiveFn, toCrossChannelTargets, } from "#channel/cross-channel-receive.js";
2
2
  import { createSession } from "#channel/session.js";
3
3
  import { expectFunction } from "#internal/authored-module.js";
4
4
  /**
@@ -33,7 +33,7 @@ export class ScheduleDispatcher {
33
33
  async trigger(input) {
34
34
  const sessions = [];
35
35
  const waitUntilTasks = [];
36
- const receive = createCrossChannelReceiveFn(this.runtime, this.channels);
36
+ const receive = createCrossChannelReceiveFn(this.runtime, toCrossChannelTargets(this.channels));
37
37
  const args = {
38
38
  appAuth: SCHEDULE_APP_AUTH,
39
39
  receive: async (channel, options) => {
@@ -1,6 +1,6 @@
1
1
  import type { ModelMessage, UserContent } from "ai";
2
2
  import type { HandleMessageStreamEvent } from "#protocol/message.js";
3
- import type { RunMode } from "#run-mode.js";
3
+ import type { RunMode } from "#shared/run-mode.js";
4
4
  import type { RuntimeActionResult } from "#runtime/actions/types.js";
5
5
  import type { InputRequest, InputResponse } from "#runtime/input/types.js";
6
6
  import type { ChannelAdapter } from "#channel/adapter.js";
@@ -1,4 +1,4 @@
1
- import{i as e,r as t,t as n}from"./chunk-DSjMdhoD.js";import{_ as r,f as i,g as a,l as o,p as s,v as c}from"./types-DDA2QUED.js";var l=class extends Error{status;body;constructor(e,t){super(t||`Server returned ${e}.`),this.name=`ClientError`,this.status=e,this.body=t}};function u(e){if(e instanceof DOMException)return e.name===`AbortError`;if(!(e instanceof Error))return!1;let t=`code`in e&&typeof e.code==`string`?e.code:void 0;return e.name===`AbortError`||e.message===`terminated`||t===`UND_ERR_SOCKET`||/abort|cancel|disconnect|premature close|socket|terminated/i.test(e.message)}async function*d(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let e=await t.read();if(e.done){r+=n.decode();break}e.value&&(r+=n.decode(e.value,{stream:!0}));let i=r.indexOf(`
1
+ import{i as e,r as t,t as n}from"./chunk-DSjMdhoD.js";import{_ as r,c as i,d as a,f as o,g as s,h as c}from"./types-CjIyrcYo.js";var l=class extends Error{status;body;constructor(e,t){super(t||`Server returned ${e}.`),this.name=`ClientError`,this.status=e,this.body=t}};function u(e){if(e instanceof DOMException)return e.name===`AbortError`;if(!(e instanceof Error))return!1;let t=`code`in e&&typeof e.code==`string`?e.code:void 0;return e.name===`AbortError`||e.message===`terminated`||t===`UND_ERR_SOCKET`||/abort|cancel|disconnect|premature close|socket|terminated/i.test(e.message)}async function*d(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let e=await t.read();if(e.done){r+=n.decode();break}e.value&&(r+=n.decode(e.value,{stream:!0}));let i=r.indexOf(`
2
2
  `);for(;i!==-1;){let e=r.slice(0,i).trim();r=r.slice(i+1),e.length>0&&(yield JSON.parse(e)),i=r.indexOf(`
3
- `)}}let e=r.trim();e.length>0&&(yield JSON.parse(e))}finally{t.releaseLock()}}function f(e,t,n){let r=t.startsWith(`/`)?t:`/${t}`,i=h(n);if(p(e)){let t=new URL(e);return t.pathname=`${m(t.pathname)}${r}`,t.search=i,t.hash=``,t.toString()}return`${m(e)}${r}${i}`}function p(e){return/^[a-z][a-z\d+\-.]*:/i.test(e)}function m(e){return e===`/`?``:e.endsWith(`/`)?e.slice(0,-1):e}function h(e){return!e||Object.keys(e).length===0?``:`?${new URLSearchParams(e).toString()}`}async function*g(e){let t=e.startIndex,n=e.maxReconnectAttempts;for(;;){let r=f(e.host,c(e.sessionId),t>0?{startIndex:String(t)}:void 0),i=await e.resolveHeaders(),a=await fetch(r,{headers:i,signal:e.signal??null});if(!a.ok){let e=await a.text();throw new l(a.status,e)}if(!a.body)throw new l(a.status,`Response body is null.`);let o=!1;try{for await(let e of d(a.body))t+=1,yield e}catch(e){if(!u(e))throw e;o=!0}if(!o||n<=0)return;--n}}var _=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}})),v=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{VercelOidcTokenError:()=>u}),t.exports=c(l);var u=class extends Error{constructor(e,t){super(e),this.name=`VercelOidcTokenError`,this.cause=t}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}}})),y=n(((t,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),u={};s(u,{getVercelOidcToken:()=>p,getVercelOidcTokenSync:()=>m}),n.exports=l(u);var d=_(),f=v();async function p(t){let n=``,r;try{n=m()}catch(e){r=e}try{let[{getTokenPayload:r,isExpired:i},{refreshToken:a}]=await Promise.all([await Promise.resolve().then(()=>e(w())),await import(`./token-D98SQdvs.js`).then(t=>e(t.default))]);(!n||i(r(n),t?.expirationBufferMs))&&(await a(t),n=m())}catch(e){let t=r instanceof Error?r.message:``;throw e instanceof Error&&(t=`${t}
4
- ${e.message}`),t?new f.VercelOidcTokenError(t):e}return n}function m(){let e=(0,d.getContext)().headers?.[`x-vercel-oidc-token`]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error(`The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`);return e}})),b=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>u,RefreshAccessTokenFailedError:()=>d}),t.exports=c(l);var u=class extends Error{constructor(){super(`No authentication found. Please log in with the Vercel CLI (vercel login).`),this.name=`AccessTokenMissingError`}},d=class extends Error{constructor(e){super(`Failed to refresh authentication token.`,{cause:e}),this.name=`RefreshAccessTokenFailedError`}}})),x=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{findRootDir:()=>y,getUserDataDir:()=>b}),n.exports=f(p);var m=d(t(`path`)),h=d(t(`fs`)),g=d(t(`os`)),_=v();function y(){try{let e=process.cwd();for(;e!==m.default.dirname(e);){let t=m.default.join(e,`.vercel`);if(h.default.existsSync(t))return e;e=m.default.dirname(e)}}catch{throw new _.VercelOidcTokenError(`Token refresh only supported in node server environments`)}return null}function b(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(g.default.platform()){case`darwin`:return m.default.join(g.default.homedir(),`Library/Application Support`);case`linux`:return m.default.join(g.default.homedir(),`.local/share`);case`win32`:return process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:null;default:return null}}})),S=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{isValidAccessToken:()=>b,readAuthConfig:()=>v,writeAuthConfig:()=>y}),n.exports=f(p);var m=d(t(`fs`)),h=d(t(`path`)),g=w();function _(){let e=(0,g.getVercelDataDir)();if(!e)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(e,`auth.json`)}function v(){try{let e=_();if(!m.existsSync(e))return null;let t=m.readFileSync(e,`utf8`);return t?JSON.parse(t):null}catch{return null}}function y(e){let t=_(),n=h.dirname(t);m.existsSync(n)||m.mkdirSync(n,{mode:504,recursive:!0}),m.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}function b(e,t=0){if(!e.token)return!1;if(typeof e.expiresAt!=`number`)return!0;let n=Math.floor(Date.now()/1e3),r=t/1e3;return e.expiresAt>=n+r}})),C=n(((e,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),u={};s(u,{processTokenResponse:()=>g,refreshTokenRequest:()=>h}),n.exports=l(u);var d=t(`os`);let f=`@vercel/oidc node-${process.version} ${(0,d.platform)()} (${(0,d.arch)()}) ${(0,d.hostname)()}`,p=null;async function m(){if(p)return p;let e=await fetch(`https://vercel.com/.well-known/openid-configuration`,{headers:{"user-agent":f}});if(!e.ok)throw Error(`Failed to discover OAuth endpoints`);let t=await e.json();if(!t||typeof t.token_endpoint!=`string`)throw Error(`Invalid OAuth discovery response`);let n=t.token_endpoint;return p=n,n}async function h(e){let t=await m();return await fetch(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":f},body:new URLSearchParams({client_id:`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,grant_type:`refresh_token`,...e})})}async function g(e){let t=await e.json();if(!e.ok){let e=typeof t==`object`&&t&&`error`in t?String(t.error):`Token refresh failed`;return[Error(e)]}return typeof t!=`object`||!t?[Error(`Invalid token response`)]:typeof t.access_token==`string`?t.token_type===`Bearer`?typeof t.expires_in==`number`?[null,t]:[Error(`Missing expires_in in response`)]:[Error(`Invalid token_type in response`)]:[Error(`Missing access_token in response`)]}})),w=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{assertVercelOidcTokenResponse:()=>k,findProjectInfo:()=>A,getTokenPayload:()=>N,getVercelDataDir:()=>E,getVercelOidcToken:()=>O,getVercelToken:()=>D,isExpired:()=>P,loadToken:()=>M,saveToken:()=>j}),n.exports=f(p);var m=d(t(`path`)),h=d(t(`fs`)),g=v(),_=x(),y=S(),w=C(),T=b();function E(){let e=(0,_.getUserDataDir)();return e?m.join(e,`com.vercel.cli`):null}async function D(e){let t=(0,y.readAuthConfig)();if(!t?.token)throw new T.AccessTokenMissingError;if((0,y.isValidAccessToken)(t,e?.expirationBufferMs))return t.token;if(!t.refreshToken)throw(0,y.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(`No refresh token available`);try{let e=await(0,w.refreshTokenRequest)({refresh_token:t.refreshToken}),[n,r]=await(0,w.processTokenResponse)(e);if(n||!r)throw(0,y.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(n);let i={token:r.access_token,expiresAt:Math.floor(Date.now()/1e3)+r.expires_in};return r.refresh_token&&(i.refreshToken=r.refresh_token),(0,y.writeAuthConfig)(i),i.token}catch(e){throw(0,y.writeAuthConfig)({}),e instanceof T.AccessTokenMissingError||e instanceof T.RefreshAccessTokenFailedError?e:new T.RefreshAccessTokenFailedError(e)}}async function O(e,t,n){let r=`https://api.vercel.com/v1/projects/${t}/token?source=vercel-oidc-refresh${n?`&teamId=${n}`:``}`,i=await fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new g.VercelOidcTokenError(`Failed to refresh OIDC token: ${i.statusText}`);let a=await i.json();return k(a),a}function k(e){if(!e||typeof e!=`object`)throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!(`token`in e)||typeof e.token!=`string`)throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function A(){let e=(0,_.findRootDir)();if(!e)throw new g.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let t=m.join(e,`.vercel`,`project.json`);if(!h.existsSync(t))throw new g.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let n=JSON.parse(h.readFileSync(t,`utf8`));if(typeof n.projectId!=`string`&&typeof n.orgId!=`string`)throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:n.projectId,teamId:n.orgId}}function j(e,t){let n=(0,_.getUserDataDir)();if(!n)throw new g.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let r=m.join(n,`com.vercel.token`,`${t}.json`),i=JSON.stringify(e);h.mkdirSync(m.dirname(r),{mode:504,recursive:!0}),h.writeFileSync(r,i),h.chmodSync(r,432)}function M(e){let t=(0,_.getUserDataDir)();if(!t)throw new g.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let n=m.join(t,`com.vercel.token`,`${e}.json`);if(!h.existsSync(n))return null;let r=JSON.parse(h.readFileSync(n,`utf8`));return k(r),r}function N(e){let t=e.split(`.`);if(t.length!==3)throw new g.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=n.padEnd(n.length+(4-n.length%4)%4,`=`);return JSON.parse(Buffer.from(r,`base64`).toString(`utf8`))}function P(e,t=0){return e.exp*1e3<Date.now()+t}})),T=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>f.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>f.RefreshAccessTokenFailedError,getContext:()=>d.getContext,getVercelOidcToken:()=>u.getVercelOidcToken,getVercelOidcTokenSync:()=>u.getVercelOidcTokenSync,getVercelToken:()=>p.getVercelToken}),t.exports=c(l);var u=y(),d=_(),f=b(),p=w()})),E=T();const D=`${a}/`,O=new Set([`localhost`,`127.0.0.1`,`0.0.0.0`,`::1`,`[::1]`]);function k(e){return O.has(e.hostname)}const A=`x-vercel-protection-bypass`,j=`x-vercel-trusted-oidc-idp-token`;function M(e){return e.pathname.endsWith(`/ash/v1`)||e.pathname.includes(D)}async function N(e){let t=P(e),n=await I(t,e.resourceUrl);return n!==null&&F(t,n),t}function P(e){let t=new Headers(z(e.headers)),n=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return n&&M(e.resourceUrl)&&t.set(A,n),t}function F(e,t){e.has(`authorization`)||e.set(`authorization`,`Bearer ${t}`),e.set(j,t)}async function I(e,t){return L(t)?e.get(`x-vercel-oidc-token`)?.trim()||await R():null}function L(e){return!(!M(e)||k(e))}async function R(){let e=process.env.VERCEL_OIDC_TOKEN?.trim();try{let e=(await(0,E.getVercelOidcToken)()).trim();if(e.length>0)return e}catch{return e??null}return e??null}function z(e){if(e!==void 0)return e instanceof Headers?e:Array.isArray(e)?e.map(([e,t])=>[e,t]):e}function B(){return{streamIndex:0}}function V(e){let t=W(e.events),n=e.session.streamIndex+e.events.length;return t?.type===`session.waiting`?{continuationToken:e.continuationToken??e.session.continuationToken,sessionId:e.sessionId,streamIndex:n}:B()}function H(e){let t;for(let n of e)G(n)&&(t=n.data.message??void 0);return t}function U(e){let t=W(e);return t?.type===`session.waiting`?`waiting`:t?.type===`session.failed`?`failed`:`completed`}function W(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&o(n))return n}}function G(e){return e.type===`message.completed`&&e.data.finishReason!==`tool-calls`}var K=class{continuationToken;sessionId;#e=!1;#t;constructor(e){this.continuationToken=e.continuationToken,this.sessionId=e.sessionId,this.#t=e.createStream}async result(){let e=[];for await(let t of this)e.push(t);return{events:e,message:H(e),sessionId:this.sessionId,status:U(e)}}[Symbol.asyncIterator](){if(this.#e)throw Error(`MessageResponse has already been consumed.`);return this.#e=!0,this.#t()}},q=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async sendMessage(e,t){return this.send({message:e},t)}async send(e,t){let n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(e,n,t);return new K({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}openStream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return g({host:this.#e.host,maxReconnectAttempts:this.#e.maxReconnectAttempts,resolveHeaders:()=>this.#e.resolveHeaders(),sessionId:t,signal:e?.signal,startIndex:e?.startIndex??this.#t.streamIndex})}async#n(e,t,n){let a=t.sessionId?r(t.sessionId):i,o=f(this.#e.host,a),s=await this.#e.resolveHeaders(n?.headers);s.set(`content-type`,`application/json`);let c=J({input:e,session:t});if(c===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let u=await fetch(o,{body:JSON.stringify(c),headers:s,method:`POST`,signal:n?.signal??null});if(!u.ok){let e=await u.text();throw new l(u.status,e)}let d=await u.json(),p=(typeof d.sessionId==`string`?d.sessionId:void 0)??u.headers.get(`x-ash-session-id`)?.trim()??t.sessionId;if(!p)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof d.continuationToken==`string`?d.continuationToken:void 0,sessionId:p}}async*#r(e,t,n,r){let i=[];try{let t=n.sessionId===e?n.streamIndex:0,a=this.#e.maxReconnectAttempts;for(;;){let n=await this.#i(e,t,r?.signal),s=!1;try{for await(let e of d(n))if(i.push(e),t+=1,yield e,o(e)){s=!0;break}}catch(e){if(!u(e))throw e}if(s||a<=0)break;--a}}finally{this.#t=V({continuationToken:t,events:i,sessionId:e,session:n})}}async#i(e,t,n){let r=f(this.#e.host,c(e),t>0?{startIndex:String(t)}:void 0),i=await this.#e.resolveHeaders(),a=await fetch(r,{headers:i,signal:n??null});if(!a.ok){let e=await a.text();throw new l(a.status,e)}if(!a.body)throw new l(a.status,`Response body is null.`);return a.body}};function J(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0||`continuationToken`in t&&Object.keys(t).length===1?null:t}var Y=class{#e;#t;#n;#r;constructor(e){this.#n=e.host,this.#e=e.auth,this.#t=e.headers,this.#r=e.maxReconnectAttempts??3}async health(){let e=f(this.#n,s),t=await this.#i(),n=await fetch(e,{headers:t});if(!n.ok){let e=await n.text();throw new l(n.status,e)}return await n.json()}session(e){let t;return t=typeof e==`string`?{continuationToken:e,streamIndex:0}:e||B(),new q({host:this.#n,maxReconnectAttempts:this.#r,resolveHeaders:e=>this.#i(e)},t)}async#i(e){let t=new Headers,n=await Z(this.#t);for(let[e,r]of Object.entries(n))t.set(e,r);if(e)for(let[n,r]of Object.entries(e))t.set(n,r);let r=await this.#a();return r&&t.set(`authorization`,r),t}async#a(){let e=this.#e;if(e){if(`bearer`in e){let t=(await X(e.bearer)).trim();return t.length===0?void 0:`Bearer ${t}`}if(`basic`in e){let t=await X(e.basic.password);return`Basic ${Q(e.basic.username,t)}`}}}};async function X(e){return typeof e==`function`?e():e}async function Z(e){return e===void 0?{}:typeof e==`function`?await e():e}function Q(e,t){let n=new TextEncoder().encode(`${e}:${t}`),r=Array.from(n,e=>String.fromCodePoint(e)).join(``);return btoa(r)}export{T as a,g as c,N as i,l,A as n,w as o,j as r,v as s,Y as t};
3
+ `)}}let e=r.trim();e.length>0&&(yield JSON.parse(e))}finally{t.releaseLock()}}function f(e,t,n){let r=t.startsWith(`/`)?t:`/${t}`,i=h(n);if(p(e)){let t=new URL(e);return t.pathname=`${m(t.pathname)}${r}`,t.search=i,t.hash=``,t.toString()}return`${m(e)}${r}${i}`}function p(e){return/^[a-z][a-z\d+\-.]*:/i.test(e)}function m(e){return e===`/`?``:e.endsWith(`/`)?e.slice(0,-1):e}function h(e){return!e||Object.keys(e).length===0?``:`?${new URLSearchParams(e).toString()}`}async function*g(e){let t=e.startIndex,n=e.maxReconnectAttempts;for(;;){let i=f(e.host,r(e.sessionId),t>0?{startIndex:String(t)}:void 0),a=await e.resolveHeaders(),o=await fetch(i,{headers:a,signal:e.signal??null});if(!o.ok){let e=await o.text();throw new l(o.status,e)}if(!o.body)throw new l(o.status,`Response body is null.`);let s=!1;try{for await(let e of d(o.body))t+=1,yield e}catch(e){if(!u(e))throw e;s=!0}if(!s||n<=0)return;--n}}var _=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}})),v=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{VercelOidcTokenError:()=>u}),t.exports=c(l);var u=class extends Error{constructor(e,t){super(e),this.name=`VercelOidcTokenError`,this.cause=t}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}}})),y=n(((t,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),u={};s(u,{getVercelOidcToken:()=>p,getVercelOidcTokenSync:()=>m}),n.exports=l(u);var d=_(),f=v();async function p(t){let n=``,r;try{n=m()}catch(e){r=e}try{let[{getTokenPayload:r,isExpired:i},{refreshToken:a}]=await Promise.all([await Promise.resolve().then(()=>e(w())),await import(`./token-BOkIxJeV.js`).then(t=>e(t.default))]);(!n||i(r(n),t?.expirationBufferMs))&&(await a(t),n=m())}catch(e){let t=r instanceof Error?r.message:``;throw e instanceof Error&&(t=`${t}
4
+ ${e.message}`),t?new f.VercelOidcTokenError(t):e}return n}function m(){let e=(0,d.getContext)().headers?.[`x-vercel-oidc-token`]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error(`The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`);return e}})),b=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>u,RefreshAccessTokenFailedError:()=>d}),t.exports=c(l);var u=class extends Error{constructor(){super(`No authentication found. Please log in with the Vercel CLI (vercel login).`),this.name=`AccessTokenMissingError`}},d=class extends Error{constructor(e){super(`Failed to refresh authentication token.`,{cause:e}),this.name=`RefreshAccessTokenFailedError`}}})),x=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{findRootDir:()=>y,getUserDataDir:()=>b}),n.exports=f(p);var m=d(t(`path`)),h=d(t(`fs`)),g=d(t(`os`)),_=v();function y(){try{let e=process.cwd();for(;e!==m.default.dirname(e);){let t=m.default.join(e,`.vercel`);if(h.default.existsSync(t))return e;e=m.default.dirname(e)}}catch{throw new _.VercelOidcTokenError(`Token refresh only supported in node server environments`)}return null}function b(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(g.default.platform()){case`darwin`:return m.default.join(g.default.homedir(),`Library/Application Support`);case`linux`:return m.default.join(g.default.homedir(),`.local/share`);case`win32`:return process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:null;default:return null}}})),S=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{isValidAccessToken:()=>b,readAuthConfig:()=>v,writeAuthConfig:()=>y}),n.exports=f(p);var m=d(t(`fs`)),h=d(t(`path`)),g=w();function _(){let e=(0,g.getVercelDataDir)();if(!e)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(e,`auth.json`)}function v(){try{let e=_();if(!m.existsSync(e))return null;let t=m.readFileSync(e,`utf8`);return t?JSON.parse(t):null}catch{return null}}function y(e){let t=_(),n=h.dirname(t);m.existsSync(n)||m.mkdirSync(n,{mode:504,recursive:!0}),m.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}function b(e,t=0){if(!e.token)return!1;if(typeof e.expiresAt!=`number`)return!0;let n=Math.floor(Date.now()/1e3),r=t/1e3;return e.expiresAt>=n+r}})),C=n(((e,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),u={};s(u,{processTokenResponse:()=>g,refreshTokenRequest:()=>h}),n.exports=l(u);var d=t(`os`);let f=`@vercel/oidc node-${process.version} ${(0,d.platform)()} (${(0,d.arch)()}) ${(0,d.hostname)()}`,p=null;async function m(){if(p)return p;let e=await fetch(`https://vercel.com/.well-known/openid-configuration`,{headers:{"user-agent":f}});if(!e.ok)throw Error(`Failed to discover OAuth endpoints`);let t=await e.json();if(!t||typeof t.token_endpoint!=`string`)throw Error(`Invalid OAuth discovery response`);let n=t.token_endpoint;return p=n,n}async function h(e){let t=await m();return await fetch(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":f},body:new URLSearchParams({client_id:`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,grant_type:`refresh_token`,...e})})}async function g(e){let t=await e.json();if(!e.ok){let e=typeof t==`object`&&t&&`error`in t?String(t.error):`Token refresh failed`;return[Error(e)]}return typeof t!=`object`||!t?[Error(`Invalid token response`)]:typeof t.access_token==`string`?t.token_type===`Bearer`?typeof t.expires_in==`number`?[null,t]:[Error(`Missing expires_in in response`)]:[Error(`Invalid token_type in response`)]:[Error(`Missing access_token in response`)]}})),w=n(((e,n)=>{var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e=>u(i({},`__esModule`,{value:!0}),e),p={};l(p,{assertVercelOidcTokenResponse:()=>k,findProjectInfo:()=>A,getTokenPayload:()=>N,getVercelDataDir:()=>E,getVercelOidcToken:()=>O,getVercelToken:()=>D,isExpired:()=>P,loadToken:()=>M,saveToken:()=>j}),n.exports=f(p);var m=d(t(`path`)),h=d(t(`fs`)),g=v(),_=x(),y=S(),w=C(),T=b();function E(){let e=(0,_.getUserDataDir)();return e?m.join(e,`com.vercel.cli`):null}async function D(e){let t=(0,y.readAuthConfig)();if(!t?.token)throw new T.AccessTokenMissingError;if((0,y.isValidAccessToken)(t,e?.expirationBufferMs))return t.token;if(!t.refreshToken)throw(0,y.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(`No refresh token available`);try{let e=await(0,w.refreshTokenRequest)({refresh_token:t.refreshToken}),[n,r]=await(0,w.processTokenResponse)(e);if(n||!r)throw(0,y.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(n);let i={token:r.access_token,expiresAt:Math.floor(Date.now()/1e3)+r.expires_in};return r.refresh_token&&(i.refreshToken=r.refresh_token),(0,y.writeAuthConfig)(i),i.token}catch(e){throw(0,y.writeAuthConfig)({}),e instanceof T.AccessTokenMissingError||e instanceof T.RefreshAccessTokenFailedError?e:new T.RefreshAccessTokenFailedError(e)}}async function O(e,t,n){let r=`https://api.vercel.com/v1/projects/${t}/token?source=vercel-oidc-refresh${n?`&teamId=${n}`:``}`,i=await fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new g.VercelOidcTokenError(`Failed to refresh OIDC token: ${i.statusText}`);let a=await i.json();return k(a),a}function k(e){if(!e||typeof e!=`object`)throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!(`token`in e)||typeof e.token!=`string`)throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function A(){let e=(0,_.findRootDir)();if(!e)throw new g.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let t=m.join(e,`.vercel`,`project.json`);if(!h.existsSync(t))throw new g.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let n=JSON.parse(h.readFileSync(t,`utf8`));if(typeof n.projectId!=`string`&&typeof n.orgId!=`string`)throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:n.projectId,teamId:n.orgId}}function j(e,t){let n=(0,_.getUserDataDir)();if(!n)throw new g.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let r=m.join(n,`com.vercel.token`,`${t}.json`),i=JSON.stringify(e);h.mkdirSync(m.dirname(r),{mode:504,recursive:!0}),h.writeFileSync(r,i),h.chmodSync(r,432)}function M(e){let t=(0,_.getUserDataDir)();if(!t)throw new g.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let n=m.join(t,`com.vercel.token`,`${e}.json`);if(!h.existsSync(n))return null;let r=JSON.parse(h.readFileSync(n,`utf8`));return k(r),r}function N(e){let t=e.split(`.`);if(t.length!==3)throw new g.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=n.padEnd(n.length+(4-n.length%4)%4,`=`);return JSON.parse(Buffer.from(r,`base64`).toString(`utf8`))}function P(e,t=0){return e.exp*1e3<Date.now()+t}})),T=n(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>f.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>f.RefreshAccessTokenFailedError,getContext:()=>d.getContext,getVercelOidcToken:()=>u.getVercelOidcToken,getVercelOidcTokenSync:()=>u.getVercelOidcTokenSync,getVercelToken:()=>p.getVercelToken}),t.exports=c(l);var u=y(),d=_(),f=b(),p=w()})),E=T();const D=`${c}/`,O=new Set([`localhost`,`127.0.0.1`,`0.0.0.0`,`::1`,`[::1]`]);function k(e){return O.has(e.hostname)}function A(e){try{return k(new URL(e))}catch{return!1}}async function j(){try{let e=(await(0,E.getVercelOidcToken)()).trim();if(e.length>0)return e}catch{}return process.env.VERCEL_OIDC_TOKEN?.trim()??``}const M=`x-vercel-protection-bypass`,N=`x-vercel-trusted-oidc-idp-token`;function P(e){return e.pathname.endsWith(`/ash/v1`)||e.pathname.includes(D)}async function F(e){let t=I(e),n=await R(t,e.resourceUrl);return n!==null&&L(t,n),t}function I(e){let t=new Headers(V(e.headers)),n=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return n&&P(e.resourceUrl)&&t.set(M,n),t}function L(e,t){e.has(`authorization`)||e.set(`authorization`,`Bearer ${t}`),e.set(N,t)}async function R(e,t){return z(t)?e.get(`x-vercel-oidc-token`)?.trim()||await B():null}function z(e){return!(!P(e)||k(e))}async function B(){let e=await j();return e.length>0?e:null}function V(e){if(e!==void 0)return e instanceof Headers?e:Array.isArray(e)?e.map(([e,t])=>[e,t]):e}async function H(e){let t={},n=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();if(n&&(t[M]=n),!A(e.serverUrl)){let e=await j();e.length>0&&(t[N]=e)}return t}function U(){return{streamIndex:0}}function W(e){let t=q(e.events),n=e.session.streamIndex+e.events.length;return t?.type===`session.waiting`?{continuationToken:e.continuationToken??e.session.continuationToken,sessionId:e.sessionId,streamIndex:n}:U()}function G(e){let t;for(let n of e)J(n)&&(t=n.data.message??void 0);return t}function K(e){let t=q(e);return t?.type===`session.waiting`?`waiting`:t?.type===`session.failed`?`failed`:`completed`}function q(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&i(n))return n}}function J(e){return e.type===`message.completed`&&e.data.finishReason!==`tool-calls`}var Y=class{continuationToken;sessionId;#e=!1;#t;constructor(e){this.continuationToken=e.continuationToken,this.sessionId=e.sessionId,this.#t=e.createStream}async result(){let e=[];for await(let t of this)e.push(t);return{events:e,message:G(e),sessionId:this.sessionId,status:K(e)}}[Symbol.asyncIterator](){if(this.#e)throw Error(`MessageResponse has already been consumed.`);return this.#e=!0,this.#t()}},X=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async sendMessage(e,t){return this.send({message:e},t)}async send(e,t){let n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(e,n,t);return new Y({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}openStream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return g({host:this.#e.host,maxReconnectAttempts:this.#e.maxReconnectAttempts,resolveHeaders:()=>this.#e.resolveHeaders(),sessionId:t,signal:e?.signal,startIndex:e?.startIndex??this.#t.streamIndex})}async#n(e,t,n){let r=t.sessionId?s(t.sessionId):a,i=f(this.#e.host,r),o=await this.#e.resolveHeaders(n?.headers);o.set(`content-type`,`application/json`);let c=Z({input:e,session:t});if(c===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let u=await fetch(i,{body:JSON.stringify(c),headers:o,method:`POST`,signal:n?.signal??null});if(!u.ok){let e=await u.text();throw new l(u.status,e)}let d=await u.json(),p=(typeof d.sessionId==`string`?d.sessionId:void 0)??u.headers.get(`x-ash-session-id`)?.trim()??t.sessionId;if(!p)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof d.continuationToken==`string`?d.continuationToken:void 0,sessionId:p}}async*#r(e,t,n,r){let a=[];try{let t=n.sessionId===e?n.streamIndex:0,o=this.#e.maxReconnectAttempts;for(;;){let n=await this.#i(e,t,r?.signal),s=!1;try{for await(let e of d(n))if(a.push(e),t+=1,yield e,i(e)){s=!0;break}}catch(e){if(!u(e))throw e}if(s||o<=0)break;--o}}finally{this.#t=W({continuationToken:t,events:a,sessionId:e,session:n})}}async#i(e,t,n){let i=f(this.#e.host,r(e),t>0?{startIndex:String(t)}:void 0),a=await this.#e.resolveHeaders(),o=await fetch(i,{headers:a,signal:n??null});if(!o.ok){let e=await o.text();throw new l(o.status,e)}if(!o.body)throw new l(o.status,`Response body is null.`);return o.body}};function Z(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0?null:t}var Q=class{#e;#t;#n;#r;constructor(e){this.#n=e.host,this.#e=e.auth,this.#t=e.headers,this.#r=e.maxReconnectAttempts??3}async health(){let e=f(this.#n,o),t=await this.#i(),n=await fetch(e,{headers:t});if(!n.ok){let e=await n.text();throw new l(n.status,e)}return await n.json()}session(e){let t;return t=typeof e==`string`?{continuationToken:e,streamIndex:0}:e||U(),new X({host:this.#n,maxReconnectAttempts:this.#r,resolveHeaders:e=>this.#i(e)},t)}async#i(e){let t=new Headers,n=await ee(this.#t);for(let[e,r]of Object.entries(n))t.set(e,r);if(e)for(let[n,r]of Object.entries(e))t.set(n,r);let r=await this.#a();return r&&t.set(`authorization`,r),t}async#a(){let e=this.#e;if(e){if(`bearer`in e){let t=(await $(e.bearer)).trim();return t.length===0?void 0:`Bearer ${t}`}if(`basic`in e){let t=await $(e.basic.password);return`Basic ${te(e.basic.username,t)}`}}}};async function $(e){return typeof e==`function`?e():e}async function ee(e){return e===void 0?{}:typeof e==`function`?await e():e}function te(e,t){let n=new TextEncoder().encode(`${e}:${t}`),r=Array.from(n,e=>String.fromCodePoint(e)).join(``);return btoa(r)}export{H as a,w as c,l as d,A as i,v as l,M as n,j as o,F as r,T as s,Q as t,g as u};
@@ -0,0 +1,5 @@
1
+ import{i as e}from"./chunk-DSjMdhoD.js";import{$ as t,B as n,F as r,G as i,H as a,I as o,J as s,K as c,L as l,N as u,P as d,Q as f,R as p,U as m,V as h,W as g,X as _,Y as v,Z as y,et as b,q as x,tt as ee,y as te,z as ne}from"./paths-B2hLA0Fn.js";import{t as re}from"./gray-matter-D-9jHwOT.js";import{n as S}from"./guards-26p6sOw3.js";import{t as ie}from"./errors-HYWjHxV6.js";import{basename as ae,dirname as C,join as w,relative as T,resolve as E}from"node:path";import{readFile as oe,readdir as se,stat as ce}from"node:fs/promises";var le=e(re(),1);function ue(e){return e}function de(e){return e}function fe(e){return e}const pe=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;function D(e){if(!le.default.test(e))return{hasFrontmatter:!1,frontmatter:{},markdown:e};let t;try{t=(0,le.default)(e)}catch(t){throw ge(e)&&!_e(e)?Error(`Markdown frontmatter is missing a closing delimiter.`):t}if(!S(t.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:t.data,markdown:ve(t.content)}}function me(e){return fe(ne({markdown:e},`Expected authored instructions markdown to match the public Ash shape.`))}function he(e){let t=D(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`run`in t.frontmatter)throw Error('Markdown-form schedules do not support the "run" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to author a handler.');return ue(n({...t.frontmatter,markdown:t.markdown},`Expected authored schedule markdown to match the public Ash shape.`))}function O(e,t={}){let n=D(e),r=t.slug;if(r===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let i=xe(n.frontmatter),a=k(i.description,`description`),o=r===void 0?Se(i.description,`description`):a??t.description??we(n.markdown,r),s={...i,description:o,markdown:n.markdown};return ye(s,i),de(h(s,`Expected authored skill markdown to match the public Ash shape.`))}function ge(e){return e.startsWith(`---
2
+ `)||e.startsWith(`---\r
3
+ `)}function _e(e){return pe.test(e)}function ve(e){return e.replace(/^\r?\n/u,``)}function ye(e,t){let n=k(t.license,`license`);n!==void 0&&(e.license=n);let r=Ce(t.metadata,`metadata`);r!==void 0&&(e.metadata=r)}const be=[`name`];function xe(e){let t={...e};for(let e of be)delete t[e];return t}function k(e,t){if(e!=null){if(typeof e!=`string`)throw Error(`Expected "${t}" frontmatter to be a string.`);return e}}function Se(e,t){let n=k(e,t);if(n===void 0)throw Error(`Missing required "${t}" frontmatter.`);return n}function Ce(e,t){if(e==null)return;if(!S(e))throw Error(`Expected "${t}" frontmatter to be an object.`);let n=Object.entries(e).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected "${t}.${e}" frontmatter to be a string.`);return[e,n]});return Object.fromEntries(n)}function we(e,t){let n=e.split(/\r?\n/u).map(e=>e.trim()).find(e=>e!==``&&!e.startsWith("```"));return n===void 0?`Instructions for the ${t} skill.`:n.replace(/^[#>*\-\s]+/u,``).trim()||`Instructions for the ${t} skill.`}async function A(e){let t=v(e.logicalPath);return{definition:e.lower(await e.source.readTextFile(e.sourcePath),{name:_(t)}),sourceKind:`markdown`,logicalPath:t,sourceId:l(t)}}function j(e,t){let n={moduleFileNames:[]};for(let r of e)if(r.isFile()){if(t.markdownFileName!==void 0&&r.name===t.markdownFileName){n.markdownFileName=r.name;continue}t.moduleBaseName!==void 0&&x(r.name)===t.moduleBaseName&&n.moduleFileNames.push(r.name)}return n.moduleFileNames.sort((e,t)=>e.localeCompare(t)),n}function M(e,t){let n=new Map;for(let r of e){if(!r.isFile())continue;let e=t.allowMarkdown?Te(r.name):null,i=t.allowModules?x(r.name):null,a=e??i;if(a===null)continue;let o=n.get(a);if(o===void 0&&(o={moduleFileNames:[],slotName:a},n.set(a,o)),e!==null){o.markdownFileName=r.name;continue}i!==null&&o.moduleFileNames.push(r.name)}return[...n.values()].map(e=>(e.moduleFileNames.sort((e,t)=>e.localeCompare(t)),e)).sort((e,t)=>e.slotName.localeCompare(t.slotName))}function Te(e){return!e.endsWith(`.md`)||e.length<=3?null:e.slice(0,-3)}async function N(e){let t=w(e.rootPath,e.directoryName),n=e.rootEntries.find(t=>t.name===e.directoryName);if(n===void 0)return{diagnostics:[],sources:[]};if(!n.isDirectory())return{diagnostics:[f({code:e.invalidDirectoryCode,message:e.invalidDirectoryMessage,sourcePath:t})],sources:[]};let r=[],i=[];return await P({allowMarkdown:e.allowMarkdown===!0,diagnostics:r,markdownLowerer:e.allowMarkdown===!0?e.markdownLowerer:void 0,projectSource:e.source,recursive:e.recursive,relativeDirectory:e.directoryName,rootDirectoryPath:t,sources:i,subdirectoryRelative:``,unsupportedEntryCode:e.unsupportedEntryCode,unsupportedEntryMessage:e.unsupportedEntryMessage,unsupportedFileCode:e.unsupportedFileCode,unsupportedFileMessage:e.unsupportedFileMessage,validateSegment:e.validateSegment}),{diagnostics:r,sources:i}}async function P(e){let t=e.subdirectoryRelative===``?e.rootDirectoryPath:w(e.rootDirectoryPath,e.subdirectoryRelative),n=await R(e.projectSource,t);e.recursive&&await Ee(e,n,t),(e.unsupportedFileCode!==void 0||e.unsupportedEntryCode!==void 0)&&De(e,n,t),await Oe(e,n,t)}async function Ee(e,t,n){for(let r of t){if(!r.isDirectory())continue;let t=w(n,r.name);if(e.validateSegment!==void 0){let n=e.validateSegment(r.name,t);if(n!==null){e.diagnostics.push(n);continue}}await P({allowMarkdown:e.allowMarkdown,diagnostics:e.diagnostics,markdownLowerer:e.markdownLowerer,projectSource:e.projectSource,recursive:e.recursive,relativeDirectory:e.relativeDirectory,rootDirectoryPath:e.rootDirectoryPath,sources:e.sources,subdirectoryRelative:e.subdirectoryRelative===``?r.name:w(e.subdirectoryRelative,r.name),unsupportedEntryCode:e.unsupportedEntryCode,unsupportedEntryMessage:e.unsupportedEntryMessage,unsupportedFileCode:e.unsupportedFileCode,unsupportedFileMessage:e.unsupportedFileMessage,validateSegment:e.validateSegment})}}function De(e,t,n){for(let r of t){let t=c(r),i=w(n,r.name);if(t===`directory`)continue;if(t===`other`){e.unsupportedEntryCode!==void 0&&e.diagnostics.push(f({code:e.unsupportedEntryCode,message:e.unsupportedEntryMessage?.(i,e.relativeDirectory)??`Expected "${i}" to be a regular file or directory within "${e.relativeDirectory}/".`,sourcePath:i}));continue}if(e.unsupportedFileCode===void 0)continue;let a=x(r.name)!==null,o=e.allowMarkdown&&r.name.endsWith(`.md`);a||o||e.diagnostics.push(f({code:e.unsupportedFileCode,message:e.unsupportedFileMessage?.(i,e.relativeDirectory)??`Expected "${i}" to be a supported authored source within "${e.relativeDirectory}/".`,sourcePath:i}))}}async function Oe(e,t,n){for(let r of M(t,{allowMarkdown:e.allowMarkdown,allowModules:!0})){let t=e.subdirectoryRelative===``?r.slotName:w(e.subdirectoryRelative,r.slotName),i=v(w(e.relativeDirectory,t));if(e.validateSegment!==void 0){let t=r.markdownFileName??r.moduleFileNames[0]??r.slotName,i=e.validateSegment(r.slotName,w(n,t));if(i!==null){e.diagnostics.push(i);continue}}if(r.markdownFileName!==void 0&&r.moduleFileNames.length>0){e.diagnostics.push(K(n,i,[r.markdownFileName,...r.moduleFileNames]));continue}if(r.moduleFileNames.length>1){e.diagnostics.push(q(n,i,r.moduleFileNames));continue}if(r.markdownFileName!==void 0){let t=e.subdirectoryRelative===``?r.markdownFileName:w(e.subdirectoryRelative,r.markdownFileName),n=v(w(e.relativeDirectory,t));if(e.markdownLowerer===void 0)continue;let i=await A({logicalPath:n,lower:e.markdownLowerer,source:e.projectSource,sourcePath:w(e.rootDirectoryPath,t)});e.sources.push(i);continue}let[a]=r.moduleFileNames;if(a===void 0)continue;let s=e.subdirectoryRelative===``?a:w(e.subdirectoryRelative,a);e.sources.push(o({logicalPath:v(w(e.relativeDirectory,s))}))}}const F=`discover/module-slot-collision`,I=`discover/tools-directory-invalid`,L=`discover/hooks-directory-invalid`,ke=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Ae=/^[a-z][a-z0-9-]{0,63}$/,je=/^(\.?[a-z][a-z0-9-]{0,63}|\[[a-zA-Z][a-zA-Z0-9_]{0,63}\])$/,Me=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;async function R(e,t){let n=[...await e.readDirectory(t)];return n.sort((e,t)=>e.name.localeCompare(t.name)),n}async function z(e){let n=await B({markdownFileName:`instructions.md`,moduleBaseName:`instructions`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`instructions`,source:e.source});if(n.diagnostics.length>0||n.source!==void 0)return{diagnostics:n.diagnostics,instructions:n.source};let r=await B({markdownFileName:`system.md`,moduleBaseName:`system`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`system`,source:e.source});if(r.source!==void 0){let n=r.source.sourceKind===`markdown`?`system.md`:r.source.logicalPath;return{diagnostics:[t({code:`discover/deprecated-system-slot`,message:`The "${n}" slot is deprecated. Rename it to "${n.replace(/^system/,`instructions`)}" — the runtime still loads the legacy slot for now, but support will be removed in a future release.`,sourcePath:w(e.rootPath,n)}),...r.diagnostics],instructions:r.source}}return r.diagnostics.length>0?{diagnostics:r.diagnostics}:e.required===!1?{diagnostics:[]}:{diagnostics:[f({code:`discover/required-instructions-missing`,message:`Expected one authored instructions prompt source at "instructions.md", "instructions.ts", "instructions.cts", "instructions.mts", "instructions.js", "instructions.cjs", or "instructions.mjs".`,sourcePath:e.rootPath})]}}async function B(e){let t=j(e.rootEntries,{markdownFileName:e.markdownFileName,moduleBaseName:e.moduleBaseName});if(t.markdownFileName!==void 0&&t.moduleFileNames.length>0)return{diagnostics:[K(e.rootPath,e.slotLabel,[t.markdownFileName,...t.moduleFileNames])]};if(t.moduleFileNames.length>1)return{diagnostics:[q(e.rootPath,e.slotLabel,t.moduleFileNames)]};if(t.markdownFileName!==void 0)return{diagnostics:[],source:await A({logicalPath:e.markdownFileName,lower:me,source:e.source,sourcePath:w(e.rootPath,t.markdownFileName)})};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:[]}:{diagnostics:[],source:o({logicalPath:n})}}function V(e){let t=j(e.rootEntries,{moduleBaseName:e.slotName});if(t.moduleFileNames.length>1)return{diagnostics:[q(e.rootPath,e.slotName,t.moduleFileNames)]};let[n]=t.moduleFileNames;return n===void 0?e.missingDiagnostic===void 0?{diagnostics:[]}:{diagnostics:[f({code:e.missingDiagnostic.code,message:e.missingDiagnostic.message,sourcePath:e.rootPath})]}:{diagnostics:[],module:o({logicalPath:n})}}function H(e,t){return ke.test(e)?null:f({code:`discover/tool-name-invalid`,message:`Tool filename "${e}" is not a legal tool name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function U(e,t){return Ae.test(e)?null:f({code:`discover/connection-name-invalid`,message:`Connection filename "${e}" is not a legal connection name. Expected lowercase ASCII letters, digits, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function Ne(e,t){return je.test(e)?null:f({code:`discover/channel-name-invalid`,message:`Channel path segment "${e}" is not a legal channel name. Expected lowercase kebab-case (\`my-channel\`), optionally with a leading dot (\`.well-known\`), or a path parameter form (\`[sessionId]\`).`,sourcePath:t})}function W(e,t){return Me.test(e)?null:f({code:`discover/hook-name-invalid`,message:`Hook path segment "${e}" is not a legal hook name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function G(e){return e.rootEntries.flatMap(n=>!n.isDirectory()||e.classifyEntry(n.name,c(n))!==`unknown`?[]:[t({code:`discover/unsupported-directory`,message:e.createUnsupportedDirectoryMessage(n.name),sourcePath:w(e.rootPath,n.name)})])}function K(e,t,n){return f({code:`discover/slot-collision`,message:`Found conflicting authored sources for "${t}": ${J(n)}.`,sourcePath:e})}function q(e,t,n){return f({code:F,message:`Found multiple authored module sources for "${t}": ${J(n)}.`,sourcePath:e})}function J(e){return e.map(e=>`"${e}"`).join(`, `)}async function Pe(e){let t=`connections`,n=w(e.rootPath,t),r=e.rootEntries.find(e=>e.name===t);if(r===void 0)return{connections:[],diagnostics:[]};if(!r.isDirectory())return{connections:[],diagnostics:[f({code:`discover/connections-directory-invalid`,message:`Expected "${n}" to be a directory of authored connections.`,sourcePath:n})]};let i=await R(e.source,n),a=[],o=[],s=new Set;for(let e of M(i,{allowMarkdown:!1,allowModules:!0})){let r=v(w(t,e.slotName));if(e.moduleFileNames.length>1){s.add(e.slotName),o.push(q(n,r,e.moduleFileNames));continue}let[i]=e.moduleFileNames;if(i===void 0)continue;s.add(e.slotName);let c=U(e.slotName,w(n,i));if(c!==null){o.push(c);continue}a.push(d({connectionName:e.slotName,logicalPath:w(t,i)}))}for(let r of i){if(!r.isDirectory())continue;let i=r.name,c=w(n,i);if(s.has(i)){o.push(f({code:`discover/connection-file-folder-collision`,message:`Connection "${i}" is defined twice. Found both file-form "connections/${i}.ts" and folder-form "connections/${i}/". Use one form, not both.`,sourcePath:c}));let e=a.findIndex(e=>e.connectionName===i);e!==-1&&a.splice(e,1);continue}let l=U(i,c);if(l!==null){o.push(l);continue}let u=Fe(await R(e.source,c));if(u.length>1){o.push(f({code:F,message:`Found multiple connection definition modules inside "${v(w(t,i))}": `+u.map(e=>`"${e}"`).join(`, `),sourcePath:c}));continue}let[p]=u;if(p===void 0){o.push(f({code:`discover/connection-folder-empty`,message:`Connection folder "connections/${i}/" contains no "connection.ts" definition. Add "connections/${i}/connection.ts" or use the file form "connections/${i}.ts".`,sourcePath:c}));continue}a.push(d({connectionName:i,logicalPath:w(t,i,p)}))}return{connections:a,diagnostics:o}}function Fe(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of M(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===`connection`&&n.push(...e.moduleFileNames);return n}const Ie=`discover/lib-entry-unsupported`;async function Le(e){let t=await N({directoryName:`lib`,invalidDirectoryCode:`discover/lib-directory-invalid`,invalidDirectoryMessage:`Expected "${e.agentRoot}/lib" to be a directory of authored helper modules.`,recursive:!0,rootEntries:e.rootEntries,rootPath:e.agentRoot,source:e.source,unsupportedEntryCode:Ie,unsupportedEntryMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`,unsupportedFileCode:Ie,unsupportedFileMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`});return{diagnostics:t.diagnostics,lib:t.sources}}function Y(){return{kind:`disk`,async readDirectory(e){return await se(e,{withFileTypes:!0})},async readTextFile(e){return await oe(e,`utf8`)},async stat(e){try{let t=await ce(e);return t.isDirectory()?`directory`:t.isFile()?`file`:`other`}catch{return`missing`}}}}const X=`sandbox`,Z=`workspace`,Re=`sandbox`;async function ze(e){let t=[],n=e.rootEntries.find(e=>e.name===X);if(n===void 0)return Be({diagnostics:t,rootEntries:e.rootEntries,rootPath:e.rootPath});let r=w(e.rootPath,X);if(!n.isDirectory())return t.push(f({code:`discover/sandbox-directory-invalid`,message:`Expected "${r}" to be the sandbox folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let i=await R(e.source,r),a=Ve(i),s=i.find(e=>e.name===Z&&e.isDirectory());if(a.length>1)return t.push(f({code:F,message:`Found multiple sandbox definition modules inside "${v(X)}": `+a.map(e=>`"${e}"`).join(`, `),sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let[c]=a,u=c!==void 0,d=s!==void 0;if(!u&&!d)return t.push(f({code:`discover/sandbox-folder-empty`,message:`Sandbox folder "sandbox/" contains neither a "sandbox.<ext>" definition nor a "workspace/" subdirectory. Add one or the other, or remove the folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let p=null;u&&(p=o({logicalPath:w(X,c)}));let m=null;if(d){let n=w(r,Z),i=v(w(X,Z)),a=await Ue(e.source,n);a===null?m={logicalPath:i,rootEntries:await He(e.source,n),sourceId:l(i),sourcePath:n}:t.push(a)}return{diagnostics:t,sandbox:p,sandboxWorkspace:m}}function Be(e){let t=j(e.rootEntries,{moduleBaseName:Re});if(t.moduleFileNames.length>1)return e.diagnostics.push(f({code:F,message:`Found multiple top-level sandbox definition modules: `+t.moduleFileNames.map(e=>`"${e}"`).join(`, `),sourcePath:e.rootPath})),{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null}:{diagnostics:e.diagnostics,sandbox:o({logicalPath:n}),sandboxWorkspace:null}}function Ve(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of M(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===Re&&n.push(...e.moduleFileNames);return n}async function He(e,t){let n=await R(e,t),r=[];for(let e of n){if(e.isDirectory()){r.push(`${e.name}/`);continue}e.isFile()&&r.push(e.name)}return r}async function Ue(e,t){return(await R(e,t)).find(e=>e.name===`skills`)===void 0?null:f({code:`discover/sandbox-workspace-skills-reserved`,message:`"sandbox/workspace/skills/" is reserved for the framework skill discovery. Move skill files under "agent/skills/" instead, or rename the subtree.`,sourcePath:w(t,`skills`)})}const We=`discover/skill-frontmatter-invalid`;async function Ge(e){let t=e.source??Y(),n=E(e.agentRoot),r=E(e.skillsDirectoryPath??w(n,`skills`)),i=v(e.skillsLogicalPath??T(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],skills:[]};if(a!==`directory`)return{diagnostics:[f({code:`discover/skills-directory-invalid`,message:`Expected "${r}" to be a directory of authored skills.`,sourcePath:r})],skills:[]};let o=[],s=new Set,l=new Map,u=await R(t,r);for(let e of u){let n=await Ke({entryName:e.name,entryType:c(e),skillsDirectoryPath:r,skillsLogicalPath:i,source:t});if(o.push(...n.diagnostics),n.skill===null||n.skillId===null||s.has(n.skillId))continue;let a=l.get(n.skillId);if(a!==void 0){o.push(f({code:`discover/skill-collision`,message:`Found conflicting authored skill sources for "${n.skillId}": "${a.logicalPath}" and "${n.logicalPath}".`,sourcePath:w(r,n.skillId)})),s.add(n.skillId),l.delete(n.skillId);continue}l.set(n.skillId,{logicalPath:n.logicalPath,skill:n.skill})}return{diagnostics:o,skills:[...l.values()].map(e=>e.skill)}}async function Ke(e){let t=w(e.skillsDirectoryPath,e.entryName);switch(i(e.entryName,e.entryType)){case`skill-package-directory`:return qe({logicalSkillsPath:e.skillsLogicalPath,skillId:e.entryName,skillRootPath:t,source:e.source});case`flat-skill-markdown`:return Je({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName,skillFilePath:t,source:e.source});case`flat-skill-module`:return Ye({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName});default:return{diagnostics:[f({code:`discover/skill-entry-not-directory`,message:`Expected "${t}" to be a skill directory containing SKILL.md or a flat ".md", ".ts", ".cts", ".mts", ".js", ".cjs", or ".mjs" skill file.`,sourcePath:t})],logicalPath:v(w(e.skillsLogicalPath,e.entryName)),skill:null,skillId:null}}}async function qe(e){let t=w(e.skillRootPath,`SKILL.md`),n=v(w(e.logicalSkillsPath,e.skillId,`SKILL.md`));if(await e.source.stat(t)!==`file`)return{diagnostics:[f({code:`discover/skill-markdown-missing`,message:`Expected "${t}" to exist for the "${e.skillId}" skill.`,sourcePath:e.skillRootPath})],logicalPath:n,skill:null,skillId:null};let r;try{r=O(await e.source.readTextFile(t))}catch(e){return{diagnostics:[f({code:We,message:Ze(t,e),sourcePath:t})],logicalPath:n,skill:null,skillId:null}}let i=await Xe(e.source,e.skillRootPath),a={description:r.description,logicalPath:n,markdown:r.markdown,name:e.skillId,rootPath:e.skillRootPath,skillFilePath:t,skillId:e.skillId,sourceId:l(n)};return i.assetsPath!==void 0&&(a.assetsPath=i.assetsPath),r.license!==void 0&&(a.license=r.license),r.metadata!==void 0&&(a.metadata=r.metadata),i.referencesPath!==void 0&&(a.referencesPath=i.referencesPath),i.scriptsPath!==void 0&&(a.scriptsPath=i.scriptsPath),{diagnostics:[],logicalPath:n,skill:p(a),skillId:e.skillId}}async function Je(e){let t=Qe(e.skillFileName),n=v(w(e.logicalSkillsPath,e.skillFileName)),r;try{r=O(await e.source.readTextFile(e.skillFilePath),{slug:t})}catch(t){return{diagnostics:[f({code:We,message:Ze(e.skillFilePath,t),sourcePath:e.skillFilePath})],logicalPath:n,skill:null,skillId:null}}return{diagnostics:[],logicalPath:n,skill:{definition:r,sourceKind:`markdown`,logicalPath:n,sourceId:l(n)},skillId:t}}async function Ye(e){let t=x(e.skillFileName),n=v(w(e.logicalSkillsPath,e.skillFileName));return t===null?{diagnostics:[],logicalPath:n,skill:null,skillId:null}:{diagnostics:[],logicalPath:n,skill:o({logicalPath:n}),skillId:t}}async function Xe(e,t){let n=await e.readDirectory(t),r={};for(let e of n)if(e.isDirectory())switch(g(e.name,c(e))){case`skill-assets-directory`:r.assetsPath=w(t,e.name);break;case`skill-references-directory`:r.referencesPath=w(t,e.name);break;case`skill-scripts-directory`:r.scriptsPath=w(t,e.name);break;default:break}return r}function Ze(e,t){return`Invalid authored skill frontmatter in "${e}": ${ie(t)}`}function Qe(e){return e.endsWith(`.md`)?e.slice(0,-3):e}async function Q(e){let t=e.source??Y(),n=E(e.agentRoot),r=E(e.subagentsDirectoryPath??w(n,`subagents`)),i=v(e.subagentsLogicalPath??T(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],subagents:[]};if(a!==`directory`)return{diagnostics:[f({code:`discover/subagents-directory-invalid`,message:`Expected "${r}" to be a directory of authored subagents.`,sourcePath:r})],subagents:[]};let o=await R(t,r),s=[],c=[];for(let a of o){if(a.isFile()){let t=x(a.name);if(t===null)continue;c.push($e({agentRoot:n,appRoot:e.appRoot,subagentId:t,subagentLogicalPath:w(i,a.name),subagentPath:w(r,a.name)}));continue}if(!a.isDirectory())continue;let o=await et({appRoot:e.appRoot,source:t,subagentId:a.name,subagentLogicalPath:w(i,a.name),subagentRoot:w(r,a.name)});s.push(...o.diagnostics),c.push(o.subagent)}return{diagnostics:s,subagents:c}}function $e(e){let t=o({logicalPath:e.subagentLogicalPath}),n=u({agentId:e.subagentId,agentRoot:e.agentRoot,appRoot:e.appRoot,configModule:t});return r({entryPath:e.subagentPath,logicalPath:e.subagentLogicalPath,manifest:n,rootPath:e.agentRoot,subagentId:e.subagentId})}async function et(e){let t=[],n=await R(e.source,e.subagentRoot);t.push(...G({classifyEntry:m,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the local subagent root.`},rootEntries:n,rootPath:e.subagentRoot}));let i=await z({required:!1,rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...i.diagnostics);let a=V({missingDiagnostic:{code:`discover/required-subagent-config-module-missing`,message:`Expected one authored subagent config module at "agent.ts", "agent.cts", "agent.mts", "agent.js", "agent.cjs", or "agent.mjs".`},rootEntries:n,rootPath:e.subagentRoot,slotName:`agent`});t.push(...a.diagnostics);let o=await Pe({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...o.diagnostics);let s=await ze({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...s.diagnostics);let c=await N({directoryName:`tools`,invalidDirectoryCode:I,invalidDirectoryMessage:`Expected "${w(e.subagentRoot,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:H});t.push(...c.diagnostics);let l=await N({directoryName:`hooks`,invalidDirectoryCode:L,invalidDirectoryMessage:`Expected "${w(e.subagentRoot,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:W});t.push(...l.diagnostics);let d=await Le({agentRoot:e.subagentRoot,rootEntries:n,source:e.source});t.push(...d.diagnostics),t.push(...tt(e.subagentRoot,n));let f=await Ge({agentRoot:e.subagentRoot,source:e.source});t.push(...f.diagnostics);let p=await Q({agentRoot:e.subagentRoot,appRoot:e.appRoot,source:e.source});t.push(...p.diagnostics);let h={agentRoot:e.subagentRoot,appRoot:e.appRoot,connections:o.connections,diagnostics:t,hooks:l.sources,lib:d.lib,instructions:i.instructions,sandbox:s.sandbox,sandboxWorkspaces:s.sandboxWorkspace===null?[]:[s.sandboxWorkspace],skills:f.skills,tools:c.sources,subagents:p.subagents};a.module!==void 0&&(h.configModule=a.module);let g=u(h);return{diagnostics:t,subagent:r({entryPath:e.subagentRoot,logicalPath:e.subagentLogicalPath,manifest:g,rootPath:e.subagentRoot,subagentId:e.subagentId})}}function tt(e,t){return t.flatMap(t=>m(t.name,c(t))===`invalid-schedules-directory`?[f({code:`discover/local-subagent-schedules-invalid`,message:`Local subagent packages cannot define schedules at "${w(e,t.name)}".`,sourcePath:w(e,t.name)})]:[])}async function nt(e){let t=await N({allowMarkdown:!0,directoryName:`schedules`,invalidDirectoryCode:`discover/schedules-directory-invalid`,invalidDirectoryMessage:`Expected "${w(e.agentRoot,`schedules`)}" to be a directory of authored schedules.`,markdownLowerer:e=>he(e),recursive:!0,rootEntries:e.rootEntries,rootPath:e.agentRoot,source:e.source,unsupportedFileCode:`discover/schedule-file-unsupported`,unsupportedFileMessage:e=>`Expected "${e}" to be a TypeScript or markdown schedule file within "schedules/".`});return{diagnostics:t.diagnostics,schedules:t.sources}}async function rt(e){let t=e.source??Y(),n=E(e.appRoot),r=E(e.agentRoot),i=[],o=await it(t,n),s=await R(t,r);i.push(...G({classifyEntry:a,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the agent root.`},rootEntries:s,rootPath:r}));let c=await z({rootEntries:s,rootPath:r,source:t});i.push(...c.diagnostics);let l=V({rootEntries:s,rootPath:r,slotName:`agent`});i.push(...l.diagnostics);let d=await N({directoryName:`channels`,invalidDirectoryCode:`discover/channels-directory-invalid`,invalidDirectoryMessage:`Expected "${w(r,`channels`)}" to be a directory of authored channels.`,recursive:!0,rootEntries:s,rootPath:r,source:t,validateSegment:Ne});i.push(...d.diagnostics);let f=await Le({agentRoot:r,rootEntries:s,source:t});i.push(...f.diagnostics);let p=await nt({agentRoot:r,rootEntries:s,source:t});i.push(...p.diagnostics);let m=await Pe({rootEntries:s,rootPath:r,source:t});i.push(...m.diagnostics);let h=await ze({rootEntries:s,rootPath:r,source:t});i.push(...h.diagnostics);let g=await N({directoryName:`tools`,invalidDirectoryCode:I,invalidDirectoryMessage:`Expected "${w(r,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:s,rootPath:r,source:t,validateSegment:H});i.push(...g.diagnostics);let _=await N({directoryName:`hooks`,invalidDirectoryCode:L,invalidDirectoryMessage:`Expected "${w(r,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:s,rootPath:r,source:t,validateSegment:W});i.push(..._.diagnostics);let v=await Ge({agentRoot:r,source:t});i.push(...v.diagnostics);let y=await Q({agentRoot:r,appRoot:n,source:t});i.push(...y.diagnostics);let b={agentRoot:r,appRoot:n,channels:d.sources,connections:m.connections,packageName:o,diagnostics:i,hooks:_.sources,lib:f.lib,instructions:c.instructions,sandbox:h.sandbox,sandboxWorkspaces:h.sandboxWorkspace===null?[]:[h.sandboxWorkspace],schedules:p.schedules,skills:v.skills,tools:g.sources,subagents:y.subagents};return l.module!==void 0&&(b.configModule=l.module),{diagnostics:i,manifest:u(b)}}async function it(e,t){try{let n=w(t,`package.json`),r=JSON.parse(await e.readTextFile(n)).name;if(typeof r!=`string`||r.length===0)return;let i=r.lastIndexOf(`/`);return i===-1?r:r.slice(i+1)}catch{return}}var at=class extends Error{diagnostic;constructor(e){super(e.message),this.name=`DiscoveryProjectResolutionError`,this.diagnostic=e}};async function ot(e=process.cwd(),t={}){let n=t.source??Y(),r=await st(n,e),i=r;for(;;){let e=await ct(n,i);if(e!==null)return e;let t=await lt(n,i);if(t!==null)return t;if(await ut(n,i))return{agentRoot:i,appRoot:i,layout:`flat`};let r=C(i);if(r===i)break;i=r}throw new at(f({code:y,message:`Could not resolve an Ash agent root from "${r}".`,sourcePath:r}))}async function st(e,t){let n=E(t);return await e.stat(n)===`directory`?n:C(n)}async function ct(e,t){if(ae(t)!==`agent`)return null;let n=C(t);return await dt(e,n)?{agentRoot:t,appRoot:n,layout:`nested`}:null}async function lt(e,t){if(!await dt(e,t))return null;let n=w(t,`agent`);return await pt(e,n)?{agentRoot:n,appRoot:t,layout:`nested`}:null}async function ut(e,t){let n=await ft(e,t);return Array.from(n.entries()).some(([e,t])=>{let n=a(e,t);return n!==`unknown`&&n!==`lib-directory`})}async function dt(e,t){let n=await ft(e,t);return Array.from(n.entries()).some(([e,t])=>s(e,t))}async function ft(e,t){if(await e.stat(t)!==`directory`)return new Map;let n=await e.readDirectory(t);return new Map(n.map(e=>[e.name,c(e)]))}async function pt(e,t){return await e.stat(t)===`directory`}var $=class extends Error{result;constructor(e){super(gt({diagnostics:e.diagnostics,diagnosticsPath:e.paths.diagnosticsPath})),this.name=`CompileAgentError`,this.result=e}};async function mt(e={}){let t=e.source??Y(),n=await ot(e.startPath,{source:t}),r=await rt({...n,source:t}),i=await te({appRoot:n.appRoot,diagnostics:r.diagnostics,manifest:r.manifest}),a={diagnostics:r.diagnostics,manifest:i.compiledManifest,metadata:i.metadata,paths:i.paths,project:n};if(b(r.diagnostics))throw new $(a);return ht(r.diagnostics),a}function ht(e){let t=e.filter(e=>e.severity===`warning`);if(t.length!==0)for(let e of t)console.warn(`Warning [${e.code}]: ${e.message}\n source: ${e.sourcePath}`)}function gt(e){let t=ee(e.diagnostics),n=[`Discovery failed with ${t.errors} error(s) and ${t.warnings} warning(s).`];if(e.diagnosticsPath!==void 0&&n.push(`Diagnostics artifact: ${e.diagnosticsPath}`),e.diagnostics.length===0)return n.join(`
4
+ `);n.push(`Discovery diagnostics:`);for(let t of e.diagnostics)n.push(`- ${_t(t.severity)}: ${t.message}`),n.push(` source: ${t.sourcePath}`);return n.join(`
5
+ `)}function _t(e){return e===`error`?`Error`:`Warning`}export{mt as n,at as r,$ as t};
@@ -0,0 +1 @@
1
+ import{A as e,s as t}from"./paths-B2hLA0Fn.js";import{t as n}from"./errors-HYWjHxV6.js";import{getDevelopmentEnvironmentFilePaths as r,loadDevelopmentEnvironmentFiles as i}from"../cli/dev/environment.js";import{a,c as o,i as s,o as c,r as l,s as u}from"./host-BxT35q6K.js";import{createRequire as d}from"node:module";import*as f from"node:path";import{dirname as p,isAbsolute as m,join as h,relative as g,resolve as _,sep as v}from"node:path";import{lstat as y,open as b,readFile as x,readdir as S,realpath as C,stat as w}from"node:fs/promises";import{existsSync as ee,stat as te,unwatchFile as T,watch as ne,watchFile as re}from"node:fs";import{parse as ie}from"#compiled/jsonc-parser/index.js";import{EventEmitter as ae}from"node:events";import{Readable as oe}from"node:stream";import{type as se}from"node:os";const E={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},D={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:E.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(D);const O=`READDIRP_RECURSIVE_ERROR`,ce=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,O]),k=[E.DIR_TYPE,E.EVERYTHING_TYPE,E.FILE_DIR_TYPE,E.FILE_TYPE],le=new Set([E.DIR_TYPE,E.EVERYTHING_TYPE,E.FILE_DIR_TYPE]),ue=new Set([E.EVERYTHING_TYPE,E.FILE_DIR_TYPE,E.FILE_TYPE]),de=e=>ce.has(e.code),fe=process.platform===`win32`,pe=e=>!0,A=e=>{if(e===void 0)return pe;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return pe};var me=class extends oe{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...D,...e},{root:n,type:r}=t;this._fileFilter=A(t.fileFilter),this._directoryFilter=A(t.directoryFilter);let i=t.lstat?y:w;fe?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:D.depth,this._wantsDir=r?le.has(r):!1,this._wantsFile=r?ue.has(r):!1,this._wantsEverything=r===E.EVERYTHING_TYPE,this._root=_(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await S(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=_(h(t,r));n={path:g(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){de(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await C(t),n=await y(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===v){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=O,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function he(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=E.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!k.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${k.join(`, `)}`);return t.root=e,new me(t)}const j=()=>{},M=process.platform,N=M===`win32`,ge=M===`darwin`,_e=M===`linux`,ve=M===`freebsd`,ye=se()===`OS400`,P={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},F=P,be={lstat:y,stat:w},I=`listeners`,L=`errHandlers`,R=`rawEmitters`,xe=[I,L,R],Se=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),Ce=e=>Se.has(f.extname(e).slice(1).toLowerCase()),z=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},B=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},we=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},V=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},H=e=>e instanceof Set?e.size===0:!e,U=new Map;function W(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&G(f.resolve(e,r),I,f.join(e,r))};try{return ne(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const G=(e,t,n,r,i)=>{let a=U.get(e);a&&z(a[t],e=>{e(n,r,i)})},Te=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=U.get(t),c;if(!n.persistent)return c=W(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)B(s,I,i),B(s,L,a),B(s,R,o);else{if(c=W(e,n,G.bind(null,t,I),a,G.bind(null,t,R)),!c)return;c.on(F.ERROR,async n=>{let r=G.bind(null,t,L);if(s&&(s.watcherUnusable=!0),N&&n.code===`EPERM`)try{await(await b(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},U.set(t,s)}return()=>{V(s,I,i),V(s,L,a),V(s,R,o),H(s.listeners)&&(s.watcher.close(),U.delete(t),xe.forEach(we(s)),s.watcher=void 0,Object.freeze(s))}},K=new Map,Ee=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=K.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(T(t),o=void 0),o?(B(o,I,i),B(o,R,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:re(t,n,(n,r)=>{z(o.rawEmitters,e=>{e(F.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&z(o.listeners,t=>t(e,n))})},K.set(t,o)),()=>{V(o,I,i),V(o,R,a),H(o.listeners)&&(K.delete(t),T(t),o.options=o.watcher=void 0,Object.freeze(o))}};var De=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=f.dirname(e),i=f.basename(e);this.fsw._getWatchedDir(r).add(i);let a=f.resolve(e),o={persistent:n.persistent};t||=j;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&Ce(i)?n.binaryInterval:n.interval,s=Ee(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=Te(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=f.dirname(e),i=f.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(`watch`,e,5)){if(!n||n.mtimeMs===0)try{let n=await w(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(F.CHANGE,e,n),(ge||_e||ve)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(F.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(F.ADD,e,0))return;this.fsw._emit(F.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await C(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(F.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(F.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){e=f.join(e,``);let s=r?`${e}:${r}`:e;if(o=this.fsw._throttle(`readdir`,s,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,u=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(u)return u.on(`data`,async o=>{if(this.fsw.closed){u=void 0;return}let s=o.path,d=f.join(e,s);if(l.add(s),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,s))){if(this.fsw.closed){u=void 0;return}(s===r||!r&&!c.has(s))&&(this.fsw._incrReadyCount(),d=f.join(i,f.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(F.ERROR,this._boundHandleError),new Promise((t,s)=>{if(!u)return s();u.once(`end`,()=>{if(this.fsw.closed){u=void 0;return}let s=o?o.clear():!1;t(void 0),c.getChildren().filter(t=>t!==e&&!l.has(t)).forEach(t=>{this.fsw._remove(e,t)}),u=void 0,s&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(f.dirname(e)),c=s.has(f.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(F.ADD_DIR,e,t),s.add(f.basename(e)),this.fsw._getWatchedDir(e);let l,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await be[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=f.resolve(e),l=s?await C(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await C(e):e;if(this.fsw.closed)return;let a=f.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(F.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(f.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}};const Oe=/\\/g,q=/\/\//g,ke=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Ae=/^\.[/\\]/;function J(e){return Array.isArray(e)?e:[e]}const Y=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function je(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=f.relative(e.path,t);return n?!n.startsWith(`..`)&&!f.isAbsolute(n):!1}return!1}:()=>!1}function Me(e){if(typeof e!=`string`)throw Error(`string expected`);e=f.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;return e.startsWith(`//`)&&(t=!0),e=e.replace(q,`/`),t&&(e=`/`+e),e}function X(e,t,n){let r=Me(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Ne(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=J(e).map(e=>je(e));return t==null?(e,t)=>X(n,e,t):X(n,t)}const Z=e=>{let t=J(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Pe)},Q=e=>{let t=e.replace(Oe,`/`),n=!1;return t.startsWith(`//`)&&(n=!0),t=t.replace(q,`/`),n&&(t=`/`+t),t},Pe=e=>Q(f.normalize(Q(e))),Fe=(e=``)=>t=>typeof t==`string`?Pe(f.isAbsolute(t)?t:f.join(e,t)):t,Ie=(e,t)=>f.isAbsolute(e)?e:f.join(t,e),Le=Object.freeze(new Set);var Re=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==`.`&&e!==`..`&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await S(n)}catch{this._removeWatcher&&this._removeWatcher(f.dirname(n),f.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=j,this.items=Le,Object.freeze(this)}},ze=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Ae,``),this.watchPath=r,this.fullWatchPath=f.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return f.join(this.watchPath,f.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Be=class extends ae{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?J(e.ignored):J([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};ye&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=j,this._readyEmitted=!0,process.nextTick(()=>this.emit(P.READY)))},this._emitRaw=(...e)=>this.emit(P.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new De(this),Object.freeze(r)}_addIgnoredPath(e){if(Y(e)){for(let t of this._ignoredPaths)if(Y(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)Y(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Z(e);return r&&(i=i.map(e=>Ie(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(f.dirname(e),f.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Z(e),{cwd:n}=this.options;return t.forEach(e=>{!f.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=f.join(n,e)),e=f.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?f.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==P.ERROR&&this.emit(P.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;N&&(t=f.normalize(t)),r.cwd&&(t=f.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===P.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(P.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===P.ADD&&this._pendingUnlinks.has(t)&&(e=P.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===P.ADD||e===P.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=P.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===P.CHANGE&&!this._throttle(P.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===P.ADD||e===P.ADD_DIR||e===P.CHANGE)){let e=r.cwd?f.join(r.cwd,t):t,n;try{n=await w(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(P.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!f.isAbsolute(e)&&(s=f.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){te(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&ke.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Fe(e)),n=[...[...this._ignoredPaths].map(Fe(e)),...t];this._userIgnored=Ne(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new ze(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=f.resolve(e);return this._watched.has(t)||this._watched.set(t,new Re(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=f.join(e,t),i=f.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=f.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===P.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?P.UNLINK_DIR:P.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=f.dirname(e);this._getWatchedDir(t).remove(f.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=he(e,{type:P.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(`close`,()=>{n=void 0}),n.once(`end`,()=>{n&&=(this._streams.delete(n),void 0)}),n}};function Ve(e,t={}){let n=new Be(t);return n.add(e),n}const He=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Ue=[`.git`,`pnpm-workspace.yaml`],We=[`**/.ash/**`,`**/.git/**`,`**/.output/**`,`**/.turbo/**`,`**/.vercel/**`,`**/.workflow-data/**`,`**/node_modules/**`];async function Ge(r){let d=r.schedulesEnabled!==!1,f=r.preparedHost,p=!1,m=Promise.resolve(),h,g=new Set,_=new Set,v=await qe(f),y=Je(v),b=Ve(v,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:We}),x=Ke(b),S=()=>{p||(m=m.then(async()=>{if(p)return;let m=g.size,h=[..._];g.clear(),_.clear();let v=f,x=Xe(v.appRoot,h);console.log(`[ash:dev] change detected (${m} event${m===1?``:`s`}), rebuilding authored artifacts...`);try{x&&i(v.appRoot);let n=await s(v.appRoot);await l({appRoot:n.appRoot,log:e=>console.log(e)});let p=o({appRoot:n.appRoot,dev:r.nitro.options.dev===!0}),m=u(r.nitro,{artifactsConfig:p,next:c(n),previous:c(v)}),h=a(r.nitro,{artifactsConfig:p,dispatchModulePath:e(`src/internal/nitro/routes/schedule-task.ts`),next:d?n.scheduleRegistrations:[],previous:d?v.scheduleRegistrations:[]});t(),f=n,m||h||x?(console.log(`[ash:dev] structural change detected, reloading Nitro worker...`),await r.nitro.hooks.callHook(`rollup:reload`)):console.log(`[ash:dev] authored artifacts updated.`),y=Ye({nextWatchPaths:await qe(n),previousWatchPathsByKey:y,watcher:b})}catch(e){console.error(`[ash:dev] rebuild failed: ${n(e)}`)}}).catch(e=>{console.error(`[ash:dev] rebuild queue error: ${n(e)}`)}))};return b.on(`all`,(e,t)=>{p||(g.add(`${e}:${t}`),_.add(t),h!==void 0&&clearTimeout(h),h=setTimeout(()=>{h=void 0,S()},120))}),await x,{async close(){p=!0,h!==void 0&&(clearTimeout(h),h=void 0),await b.close(),await m}}}async function Ke(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function qe(e){let t=new Set([e.compileResult.project.agentRoot,h(e.appRoot,`package.json`),h(e.appRoot,`jsconfig.json`),h(e.appRoot,`tsconfig.json`),h(e.appRoot,`tsconfig.*.json`)]),n=await $e(e.appRoot);for(let n of r(e.appRoot))t.add(n);for(let e of n)t.add(e);for(let n of Ze(e.appRoot))for(let e of He)t.add(h(n,e));return[...t].sort((e,t)=>e.localeCompare(t))}function Je(e){let t=new Map;for(let n of e)t.set($(n),n);return t}function Ye(e){let t=Je(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function $(e){return e.replaceAll(`\\`,`/`)}function Xe(e,t){let n=new Set(r(e).map(e=>$(_(e))));return t.some(e=>n.has($(_(e))))}function Ze(e){let t=[],n=_(e);for(;t.push(n),!Qe(n);){let e=p(n);if(e===n)break;n=e}return t}function Qe(e){return Ue.some(t=>ee(h(e,t)))}async function $e(e){let t=await et(e),n=new Set,r=new Set;for(let e of t)await tt({configPath:e,resolvedConfigPaths:n,visitingConfigPaths:r});return[...n].sort((e,t)=>e.localeCompare(t))}async function et(e){let t=new Set([h(e,`tsconfig.json`),h(e,`jsconfig.json`)]);try{let n=await S(e,{withFileTypes:!0});for(let r of n)r.isFile()&&/^tsconfig\..+\.json$/i.test(r.name)&&t.add(h(e,r.name))}catch{}return[...t]}async function tt(e){let t=_(e.configPath);if(e.resolvedConfigPaths.has(t)||e.visitingConfigPaths.has(t))return;let n=await nt(t);if(n!==void 0){e.resolvedConfigPaths.add(t),e.visitingConfigPaths.add(t);try{let r=rt(n);for(let n of r)for(let r of it({configPath:t,extendsSpecifier:n}))await tt({configPath:r,resolvedConfigPaths:e.resolvedConfigPaths,visitingConfigPaths:e.visitingConfigPaths})}finally{e.visitingConfigPaths.delete(t)}}}async function nt(e){try{return await x(e,`utf8`)}catch{return}}function rt(e){let t=[],n=ie(e,t,{allowTrailingComma:!0});if(t.length>0||typeof n!=`object`||!n||Array.isArray(n))return[];let r=n.extends;return typeof r==`string`?r.length>0?[r]:[]:Array.isArray(r)?r.filter(e=>typeof e==`string`&&e.length>0):[]}function it(e){let t=new Set;if(st(e.extendsSpecifier))for(let n of at({configPath:e.configPath,extendsSpecifier:e.extendsSpecifier}))t.add(n);else for(let n of ot({configPath:e.configPath,extendsSpecifier:e.extendsSpecifier}))t.add(n);return[...t]}function at(e){let t=_(p(e.configPath),e.extendsSpecifier),n=new Set;return n.add(t),t.endsWith(`.json`)||(n.add(`${t}.json`),n.add(h(t,`tsconfig.json`))),[...n]}function ot(e){let t=new Set([e.extendsSpecifier]);e.extendsSpecifier.endsWith(`.json`)||(t.add(`${e.extendsSpecifier}.json`),t.add(`${e.extendsSpecifier}/tsconfig.json`));let n=new Set,r=d(e.configPath);for(let e of t)try{n.add(r.resolve(e))}catch{}return[...n]}function st(e){return e.startsWith(`.`)||m(e)?!0:/^[A-Za-z]:[\\/]/.test(e)}export{Ge as startAuthoredSourceWatcher};